repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
mwol/gobblin
gobblin-modules/gobblin-compliance/src/main/java/gobblin/compliance/HivePartitionDatasetPolicy.java
2154
/* * 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 gobblin.compliance; import java.util.ArrayList; import java.util.List; /** * This policy checks if a Hive Partition is a valid dataset. * Hive table to which Hive partition belongs must be an external table. * Hive table name must not contain "_trash_", "_staging_" and "_backup_" * in it's name since they will considered as {@link HivePartitionVersion} rather * than {@link HivePartitionDataset} */ public class HivePartitionDatasetPolicy implements Policy<HivePartitionDataset> { @Override public boolean shouldSelect(HivePartitionDataset dataset) { if (dataset.getTableName().contains(ComplianceConfigurationKeys.TRASH)) { return false; } else if (dataset.getTableName().contains(ComplianceConfigurationKeys.BACKUP)) { return false; } else if (dataset.getTableName().contains(ComplianceConfigurationKeys.STAGING)) { return false; } else { return dataset.getTableMetadata().containsKey(ComplianceConfigurationKeys.EXTERNAL); } } @Override public List<HivePartitionDataset> selectedList(List<HivePartitionDataset> datasets) { List<HivePartitionDataset> selectedDatasetList = new ArrayList<>(); for (HivePartitionDataset dataset : datasets) { if (shouldSelect(dataset)) { selectedDatasetList.add(dataset); } } return selectedDatasetList; } }
apache-2.0
dhanuka84/andes
modules/andes-core/broker/src/test/java/org/wso2/andes/server/virtualhost/MockVirtualHost.java
5652
/* * * 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.wso2.andes.server.virtualhost; import java.util.UUID; import org.wso2.andes.server.binding.BindingFactory; import org.wso2.andes.server.configuration.BrokerConfig; import org.wso2.andes.server.configuration.ConfigStore; import org.wso2.andes.server.configuration.ConfiguredObject; import org.wso2.andes.server.configuration.VirtualHostConfig; import org.wso2.andes.server.configuration.VirtualHostConfigType; import org.wso2.andes.server.configuration.VirtualHostConfiguration; import org.wso2.andes.server.connection.IConnectionRegistry; import org.wso2.andes.server.exchange.ExchangeFactory; import org.wso2.andes.server.exchange.ExchangeRegistry; import org.wso2.andes.server.federation.BrokerLink; import org.wso2.andes.server.management.ManagedObject; import org.wso2.andes.server.queue.QueueRegistry; import org.wso2.andes.server.registry.IApplicationRegistry; import org.wso2.andes.server.security.SecurityManager; import org.wso2.andes.server.security.auth.manager.AuthenticationManager; import org.wso2.andes.server.stats.StatisticsCounter; import org.wso2.andes.server.store.DurableConfigurationStore; import org.wso2.andes.server.store.MessageStore; import org.wso2.andes.server.store.TransactionLog; public class MockVirtualHost implements VirtualHost { private String _name; public MockVirtualHost(String name) { _name = name; } public void close() { } public void createBrokerConnection(String transport, String host, int port, String vhost, boolean durable, String authMechanism, String username, String password) { } public IApplicationRegistry getApplicationRegistry() { return null; } public AuthenticationManager getAuthenticationManager() { return null; } public BindingFactory getBindingFactory() { return null; } public UUID getBrokerId() { return null; } public ConfigStore getConfigStore() { return null; } public VirtualHostConfiguration getConfiguration() { return null; } public IConnectionRegistry getConnectionRegistry() { return null; } public DurableConfigurationStore getDurableConfigurationStore() { return null; } public ExchangeFactory getExchangeFactory() { return null; } public ExchangeRegistry getExchangeRegistry() { return null; } public int getHouseKeepingActiveCount() { return 0; } public long getHouseKeepingCompletedTaskCount() { return 0; } public int getHouseKeepingPoolSize() { return 0; } public long getHouseKeepingTaskCount() { return 0; } public ManagedObject getManagedObject() { return null; } public MessageStore getMessageStore() { return null; } public String getName() { return _name; } public QueueRegistry getQueueRegistry() { return null; } public SecurityManager getSecurityManager() { return null; } public TransactionLog getTransactionLog() { return null; } public void removeBrokerConnection(BrokerLink brokerLink) { } public void scheduleHouseKeepingTask(long period, HouseKeepingTask task) { } public void setHouseKeepingPoolSize(int newSize) { } public BrokerConfig getBroker() { return null; } public String getFederationTag() { return null; } public void setBroker(BrokerConfig brokerConfig) { } public VirtualHostConfigType getConfigType() { return null; } public long getCreateTime() { return 0; } public UUID getId() { return null; } public ConfiguredObject<VirtualHostConfigType, VirtualHostConfig> getParent() { return null; } public boolean isDurable() { return false; } public StatisticsCounter getDataDeliveryStatistics() { return null; } public StatisticsCounter getDataReceiptStatistics() { return null; } public StatisticsCounter getMessageDeliveryStatistics() { return null; } public StatisticsCounter getMessageReceiptStatistics() { return null; } public void initialiseStatistics() { } public boolean isStatisticsEnabled() { return false; } public void registerMessageDelivered(long messageSize) { } public void registerMessageReceived(long messageSize, long timestamp) { } public void resetStatistics() { } public void setStatisticsEnabled(boolean enabled) { } }
apache-2.0
lugt/netty
codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java
44189
/* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.netty.handler.codec.http2; import static io.netty.handler.codec.http2.Http2CodecUtil.CONNECTION_STREAM_ID; import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT; import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_WEIGHT; import static io.netty.handler.codec.http2.Http2CodecUtil.MIN_WEIGHT; import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR; import static io.netty.handler.codec.http2.Http2Error.REFUSED_STREAM; import static io.netty.handler.codec.http2.Http2Exception.closedStreamError; import static io.netty.handler.codec.http2.Http2Exception.connectionError; import static io.netty.handler.codec.http2.Http2Exception.streamError; import static io.netty.handler.codec.http2.Http2Stream.State.CLOSED; import static io.netty.handler.codec.http2.Http2Stream.State.HALF_CLOSED_LOCAL; import static io.netty.handler.codec.http2.Http2Stream.State.HALF_CLOSED_REMOTE; import static io.netty.handler.codec.http2.Http2Stream.State.IDLE; import static io.netty.handler.codec.http2.Http2Stream.State.OPEN; import static io.netty.handler.codec.http2.Http2Stream.State.RESERVED_LOCAL; import static io.netty.handler.codec.http2.Http2Stream.State.RESERVED_REMOTE; import static io.netty.util.internal.ObjectUtil.checkNotNull; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http2.Http2Stream.State; import io.netty.util.collection.IntObjectHashMap; import io.netty.util.collection.IntObjectMap; import io.netty.util.collection.PrimitiveCollections; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Queue; import java.util.Set; /** * Simple implementation of {@link Http2Connection}. */ public class DefaultHttp2Connection implements Http2Connection { private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultHttp2Connection.class); // Fields accessed by inner classes final IntObjectMap<Http2Stream> streamMap = new IntObjectHashMap<Http2Stream>(); final PropertyKeyRegistry propertyKeyRegistry = new PropertyKeyRegistry(); final ConnectionStream connectionStream = new ConnectionStream(); final DefaultEndpoint<Http2LocalFlowController> localEndpoint; final DefaultEndpoint<Http2RemoteFlowController> remoteEndpoint; /** * The initial size of the children map is chosen to be conservative on initial memory allocations under * the assumption that most streams will have a small number of children. This choice may be * sub-optimal if when children are present there are many children (i.e. a web page which has many * dependencies to load). */ private static final int INITIAL_CHILDREN_MAP_SIZE = Math.max(1, SystemPropertyUtil.getInt("io.netty.http2.childrenMapSize", 4)); /** * We chose a {@link List} over a {@link Set} to avoid allocating an {@link Iterator} objects when iterating over * the listeners. */ final List<Listener> listeners = new ArrayList<Listener>(4); final ActiveStreams activeStreams; /** * Creates a new connection with the given settings. * * @param server * whether or not this end-point is the server-side of the HTTP/2 connection. */ public DefaultHttp2Connection(boolean server) { activeStreams = new ActiveStreams(listeners); localEndpoint = new DefaultEndpoint<Http2LocalFlowController>(server); remoteEndpoint = new DefaultEndpoint<Http2RemoteFlowController>(!server); // Add the connection stream to the map. streamMap.put(connectionStream.id(), connectionStream); } @Override public void addListener(Listener listener) { listeners.add(listener); } @Override public void removeListener(Listener listener) { listeners.remove(listener); } @Override public boolean isServer() { return localEndpoint.isServer(); } @Override public Http2Stream connectionStream() { return connectionStream; } @Override public Http2Stream stream(int streamId) { return streamMap.get(streamId); } @Override public boolean streamMayHaveExisted(int streamId) { return remoteEndpoint.mayHaveCreatedStream(streamId) || localEndpoint.mayHaveCreatedStream(streamId); } @Override public int numActiveStreams() { return activeStreams.size(); } @Override public Http2Stream forEachActiveStream(Http2StreamVisitor visitor) throws Http2Exception { return activeStreams.forEachActiveStream(visitor); } @Override public Endpoint<Http2LocalFlowController> local() { return localEndpoint; } @Override public Endpoint<Http2RemoteFlowController> remote() { return remoteEndpoint; } @Override public boolean goAwayReceived() { return localEndpoint.lastStreamKnownByPeer >= 0; } @Override public void goAwayReceived(final int lastKnownStream, long errorCode, ByteBuf debugData) { localEndpoint.lastStreamKnownByPeer(lastKnownStream); for (int i = 0; i < listeners.size(); ++i) { try { listeners.get(i).onGoAwayReceived(lastKnownStream, errorCode, debugData); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onGoAwayReceived.", e); } } try { forEachActiveStream(new Http2StreamVisitor() { @Override public boolean visit(Http2Stream stream) { if (stream.id() > lastKnownStream && localEndpoint.isValidStreamId(stream.id())) { stream.close(); } return true; } }); } catch (Http2Exception e) { PlatformDependent.throwException(e); } } @Override public boolean goAwaySent() { return remoteEndpoint.lastStreamKnownByPeer >= 0; } @Override public void goAwaySent(final int lastKnownStream, long errorCode, ByteBuf debugData) { remoteEndpoint.lastStreamKnownByPeer(lastKnownStream); for (int i = 0; i < listeners.size(); ++i) { try { listeners.get(i).onGoAwaySent(lastKnownStream, errorCode, debugData); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onGoAwaySent.", e); } } try { forEachActiveStream(new Http2StreamVisitor() { @Override public boolean visit(Http2Stream stream) { if (stream.id() > lastKnownStream && remoteEndpoint.isValidStreamId(stream.id())) { stream.close(); } return true; } }); } catch (Http2Exception e) { PlatformDependent.throwException(e); } } /** * Closed streams may stay in the priority tree if they have dependents that are in prioritizable states. * When a stream is requested to be removed we can only actually remove that stream when there are no more * prioritizable children. * (see [1] {@link Http2Stream#prioritizableForTree()} and [2] {@link DefaultStream#removeChild(DefaultStream)}). * When a priority tree edge changes we also have to re-evaluate viable nodes * (see [3] {@link DefaultStream#takeChild(DefaultStream, boolean, List)}). * @param stream The stream to remove. */ void removeStream(DefaultStream stream) { // [1] Check if this stream can be removed because it has no prioritizable descendants. if (stream.parent().removeChild(stream)) { // Remove it from the map and priority tree. streamMap.remove(stream.id()); for (int i = 0; i < listeners.size(); i++) { try { listeners.get(i).onStreamRemoved(stream); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onStreamRemoved.", e); } } } } static State activeState(int streamId, State initialState, boolean isLocal, boolean halfClosed) throws Http2Exception { switch (initialState) { case IDLE: return halfClosed ? isLocal ? HALF_CLOSED_LOCAL : HALF_CLOSED_REMOTE : OPEN; case RESERVED_LOCAL: return HALF_CLOSED_REMOTE; case RESERVED_REMOTE: return HALF_CLOSED_LOCAL; default: throw streamError(streamId, PROTOCOL_ERROR, "Attempting to open a stream in an invalid state: " + initialState); } } void notifyHalfClosed(Http2Stream stream) { for (int i = 0; i < listeners.size(); i++) { try { listeners.get(i).onStreamHalfClosed(stream); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onStreamHalfClosed.", e); } } } void notifyClosed(Http2Stream stream) { for (int i = 0; i < listeners.size(); i++) { try { listeners.get(i).onStreamClosed(stream); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onStreamClosed.", e); } } } @Override public PropertyKey newKey() { return propertyKeyRegistry.newKey(); } /** * Verifies that the key is valid and returns it as the internal {@link DefaultPropertyKey} type. * * @throws NullPointerException if the key is {@code null}. * @throws ClassCastException if the key is not of type {@link DefaultPropertyKey}. * @throws IllegalArgumentException if the key was not created by this connection. */ final DefaultPropertyKey verifyKey(PropertyKey key) { return checkNotNull((DefaultPropertyKey) key, "key").verifyConnection(this); } /** * Simple stream implementation. Streams can be compared to each other by priority. */ private class DefaultStream implements Http2Stream { private final int id; private final PropertyMap properties = new PropertyMap(); private State state; private short weight = DEFAULT_PRIORITY_WEIGHT; private DefaultStream parent; private IntObjectMap<DefaultStream> children = PrimitiveCollections.emptyIntObjectMap(); private int totalChildWeights; private int prioritizableForTree = 1; private boolean resetSent; DefaultStream(int id, State state) { this.id = id; this.state = state; } @Override public final int id() { return id; } @Override public final State state() { return state; } @Override public boolean isResetSent() { return resetSent; } @Override public Http2Stream resetSent() { resetSent = true; return this; } @Override public final <V> V setProperty(PropertyKey key, V value) { return properties.add(verifyKey(key), value); } @Override public final <V> V getProperty(PropertyKey key) { return properties.get(verifyKey(key)); } @Override public final <V> V removeProperty(PropertyKey key) { return properties.remove(verifyKey(key)); } @Override public final boolean isRoot() { return parent == null; } @Override public final short weight() { return weight; } @Override public final int totalChildWeights() { return totalChildWeights; } @Override public final DefaultStream parent() { return parent; } @Override public final int prioritizableForTree() { return prioritizableForTree; } @Override public final boolean isDescendantOf(Http2Stream stream) { Http2Stream next = parent(); while (next != null) { if (next == stream) { return true; } next = next.parent(); } return false; } @Override public final boolean isLeaf() { return numChildren() == 0; } @Override public final int numChildren() { return children.size(); } @Override public Http2Stream forEachChild(Http2StreamVisitor visitor) throws Http2Exception { for (DefaultStream stream : children.values()) { if (!visitor.visit(stream)) { return stream; } } return null; } @Override public Http2Stream setPriority(int parentStreamId, short weight, boolean exclusive) throws Http2Exception { if (weight < MIN_WEIGHT || weight > MAX_WEIGHT) { throw new IllegalArgumentException(String.format( "Invalid weight: %d. Must be between %d and %d (inclusive).", weight, MIN_WEIGHT, MAX_WEIGHT)); } DefaultStream newParent = (DefaultStream) stream(parentStreamId); if (newParent == null) { // Streams can depend on other streams in the IDLE state. We must ensure // the stream has been "created" in order to use it in the priority tree. newParent = createdBy().createIdleStream(parentStreamId); } else if (this == newParent) { throw new IllegalArgumentException("A stream cannot depend on itself"); } // Already have a priority. Re-prioritize the stream. weight(weight); if (newParent != parent() || (exclusive && newParent.numChildren() != 1)) { final List<ParentChangedEvent> events; if (newParent.isDescendantOf(this)) { events = new ArrayList<ParentChangedEvent>(2 + (exclusive ? newParent.numChildren() : 0)); parent.takeChild(newParent, false, events); } else { events = new ArrayList<ParentChangedEvent>(1 + (exclusive ? newParent.numChildren() : 0)); } newParent.takeChild(this, exclusive, events); notifyParentChanged(events); } return this; } @Override public Http2Stream open(boolean halfClosed) throws Http2Exception { state = activeState(id, state, isLocal(), halfClosed); activate(); return this; } void activate() { activeStreams.activate(this); } @Override public Http2Stream close() { if (state == CLOSED) { return this; } state = CLOSED; decrementPrioritizableForTree(1); activeStreams.deactivate(this); return this; } @Override public Http2Stream closeLocalSide() { switch (state) { case OPEN: state = HALF_CLOSED_LOCAL; notifyHalfClosed(this); break; case HALF_CLOSED_LOCAL: break; default: close(); break; } return this; } @Override public Http2Stream closeRemoteSide() { switch (state) { case OPEN: state = HALF_CLOSED_REMOTE; notifyHalfClosed(this); break; case HALF_CLOSED_REMOTE: break; default: close(); break; } return this; } /** * Recursively increment the {@link #prioritizableForTree} for this object up the parent links until * either we go past the root or {@code oldParent} is encountered. * @param amt The amount to increment by. This must be positive. * @param oldParent The previous parent for this stream. */ private void incrementPrioritizableForTree(int amt, Http2Stream oldParent) { if (amt != 0) { incrementPrioritizableForTree0(amt, oldParent); } } /** * Direct calls to this method are discouraged. * Instead use {@link #incrementPrioritizableForTree(int, Http2Stream)}. */ private void incrementPrioritizableForTree0(int amt, Http2Stream oldParent) { assert amt > 0 && Integer.MAX_VALUE - amt >= prioritizableForTree; prioritizableForTree += amt; if (parent != null && parent != oldParent) { parent.incrementPrioritizableForTree0(amt, oldParent); } } /** * Recursively increment the {@link #prioritizableForTree} for this object up the parent links until * either we go past the root. * @param amt The amount to decrement by. This must be positive. */ private void decrementPrioritizableForTree(int amt) { if (amt != 0) { decrementPrioritizableForTree0(amt); } } /** * Direct calls to this method are discouraged. Instead use {@link #decrementPrioritizableForTree(int)}. */ private void decrementPrioritizableForTree0(int amt) { assert amt > 0 && prioritizableForTree >= amt; prioritizableForTree -= amt; if (parent != null) { parent.decrementPrioritizableForTree0(amt); } } /** * Determine if this node by itself is considered to be valid in the priority tree. */ private boolean isPrioritizable() { return state != CLOSED; } private void initChildrenIfEmpty() { if (children == PrimitiveCollections.<DefaultStream>emptyIntObjectMap()) { initChildren(); } } private void initChildren() { children = new IntObjectHashMap<DefaultStream>(INITIAL_CHILDREN_MAP_SIZE); } @Override public final boolean remoteSideOpen() { return state == HALF_CLOSED_LOCAL || state == OPEN || state == RESERVED_REMOTE; } @Override public final boolean localSideOpen() { return state == HALF_CLOSED_REMOTE || state == OPEN || state == RESERVED_LOCAL; } final DefaultEndpoint<? extends Http2FlowController> createdBy() { return localEndpoint.isValidStreamId(id) ? localEndpoint : remoteEndpoint; } final boolean isLocal() { return localEndpoint.isValidStreamId(id); } final void weight(short weight) { if (weight != this.weight) { if (parent != null) { int delta = weight - this.weight; parent.totalChildWeights += delta; } final short oldWeight = this.weight; this.weight = weight; for (int i = 0; i < listeners.size(); i++) { try { listeners.get(i).onWeightChanged(this, oldWeight); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onWeightChanged.", e); } } } } /** * Remove all children with the exception of {@code streamToRetain}. * This method is intended to be used to support an exclusive priority dependency operation. * @return The map of children prior to this operation, excluding {@code streamToRetain} if present. */ private IntObjectMap<DefaultStream> retain(DefaultStream streamToRetain) { streamToRetain = children.remove(streamToRetain.id()); IntObjectMap<DefaultStream> prevChildren = children; // This map should be re-initialized in anticipation for the 1 exclusive child which will be added. // It will either be added directly in this method, or after this method is called...but it will be added. initChildren(); if (streamToRetain == null) { totalChildWeights = 0; prioritizableForTree = isPrioritizable() ? 1 : 0; } else { totalChildWeights = streamToRetain.weight(); // prioritizableForTree does not change because it is assumed all children node will still be // descendants through an exclusive priority tree operation. children.put(streamToRetain.id(), streamToRetain); } return prevChildren; } /** * Adds a child to this priority. If exclusive is set, any children of this node are moved to being dependent on * the child. */ final void takeChild(DefaultStream child, boolean exclusive, List<ParentChangedEvent> events) { DefaultStream oldParent = child.parent(); if (oldParent != this) { events.add(new ParentChangedEvent(child, oldParent)); notifyParentChanging(child, this); child.parent = this; // We need the removal operation to happen first so the prioritizableForTree for the old parent to root // path is updated with the correct child.prioritizableForTree() value. Note that the removal operation // may not be successful and may return null. This is because when an exclusive dependency is processed // the children are removed in a previous recursive call but the child's parent link is updated here. if (oldParent != null && oldParent.children.remove(child.id()) != null) { oldParent.totalChildWeights -= child.weight(); if (!child.isDescendantOf(oldParent)) { oldParent.decrementPrioritizableForTree(child.prioritizableForTree()); if (oldParent.prioritizableForTree() == 0) { // There are a few risks with immediately removing nodes from the priority tree: // 1. We are removing nodes while we are potentially shifting the tree. There are no // concrete cases known but is risky because it could invalidate the data structure. // 2. We are notifying listeners of the removal while the tree is in flux. Currently the // codec listeners make no assumptions about priority tree structure when being notified. removeStream(oldParent); } } } // Lazily initialize the children to save object allocations. initChildrenIfEmpty(); final Http2Stream oldChild = children.put(child.id(), child); assert oldChild == null : "A stream with the same stream ID was already in the child map."; totalChildWeights += child.weight(); incrementPrioritizableForTree(child.prioritizableForTree(), oldParent); } if (exclusive && !children.isEmpty()) { // If it was requested that this child be the exclusive dependency of this node, // move any previous children to the child node, becoming grand children of this node. for (DefaultStream grandchild : retain(child).values()) { child.takeChild(grandchild, false, events); } } } /** * Removes the child priority and moves any of its dependencies to being direct dependencies on this node. */ final boolean removeChild(DefaultStream child) { if (child.prioritizableForTree() == 0 && children.remove(child.id()) != null) { List<ParentChangedEvent> events = new ArrayList<ParentChangedEvent>(1 + child.numChildren()); events.add(new ParentChangedEvent(child, child.parent())); notifyParentChanging(child, null); child.parent = null; totalChildWeights -= child.weight(); decrementPrioritizableForTree(child.prioritizableForTree()); // Move up any grand children to be directly dependent on this node. for (DefaultStream grandchild : child.children.values()) { takeChild(grandchild, false, events); } if (prioritizableForTree() == 0) { // There are a few risks with immediately removing nodes from the priority tree: // 1. We are removing nodes while we are potentially shifting the tree. There are no // concrete cases known but is risky because it could invalidate the data structure. // 2. We are notifying listeners of the removal while the tree is in flux. Currently the // codec listeners make no assumptions about priority tree structure when being notified. removeStream(this); } notifyParentChanged(events); return true; } return false; } /** * Provides the lazy initialization for the {@link DefaultStream} data map. */ private class PropertyMap { Object[] values = EmptyArrays.EMPTY_OBJECTS; <V> V add(DefaultPropertyKey key, V value) { resizeIfNecessary(key.index); @SuppressWarnings("unchecked") V prevValue = (V) values[key.index]; values[key.index] = value; return prevValue; } @SuppressWarnings("unchecked") <V> V get(DefaultPropertyKey key) { if (key.index >= values.length) { return null; } return (V) values[key.index]; } @SuppressWarnings("unchecked") <V> V remove(DefaultPropertyKey key) { V prevValue = null; if (key.index < values.length) { prevValue = (V) values[key.index]; values[key.index] = null; } return prevValue; } void resizeIfNecessary(int index) { if (index >= values.length) { values = Arrays.copyOf(values, propertyKeyRegistry.size()); } } } } /** * Allows a correlation to be made between a stream and its old parent before a parent change occurs */ private static final class ParentChangedEvent { private final Http2Stream stream; private final Http2Stream oldParent; /** * Create a new instance * @param stream The stream who has had a parent change * @param oldParent The previous parent */ ParentChangedEvent(Http2Stream stream, Http2Stream oldParent) { this.stream = stream; this.oldParent = oldParent; } /** * Notify all listeners of the tree change event * @param l The listener to notify */ public void notifyListener(Listener l) { try { l.onPriorityTreeParentChanged(stream, oldParent); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onPriorityTreeParentChanged.", e); } } } /** * Notify all listeners of the priority tree change events (in ascending order) * @param events The events (top down order) which have changed */ private void notifyParentChanged(List<ParentChangedEvent> events) { for (int i = 0; i < events.size(); ++i) { ParentChangedEvent event = events.get(i); for (int j = 0; j < listeners.size(); j++) { event.notifyListener(listeners.get(j)); } } } private void notifyParentChanging(Http2Stream stream, Http2Stream newParent) { for (int i = 0; i < listeners.size(); i++) { try { listeners.get(i).onPriorityTreeParentChanging(stream, newParent); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onPriorityTreeParentChanging.", e); } } } /** * Stream class representing the connection, itself. */ private final class ConnectionStream extends DefaultStream { ConnectionStream() { super(CONNECTION_STREAM_ID, IDLE); } @Override public boolean isResetSent() { return false; } @Override public Http2Stream resetSent() { throw new UnsupportedOperationException(); } @Override public Http2Stream setPriority(int parentStreamId, short weight, boolean exclusive) { throw new UnsupportedOperationException(); } @Override public Http2Stream open(boolean halfClosed) { throw new UnsupportedOperationException(); } @Override public Http2Stream close() { throw new UnsupportedOperationException(); } @Override public Http2Stream closeLocalSide() { throw new UnsupportedOperationException(); } @Override public Http2Stream closeRemoteSide() { throw new UnsupportedOperationException(); } } /** * Simple endpoint implementation. */ private final class DefaultEndpoint<F extends Http2FlowController> implements Endpoint<F> { private final boolean server; private int nextStreamId; private int lastStreamCreated; private int lastStreamKnownByPeer = -1; private boolean pushToAllowed = true; private F flowController; private int maxActiveStreams; // Fields accessed by inner classes int numActiveStreams; DefaultEndpoint(boolean server) { this.server = server; // Determine the starting stream ID for this endpoint. Client-initiated streams // are odd and server-initiated streams are even. Zero is reserved for the // connection. Stream 1 is reserved client-initiated stream for responding to an // upgrade from HTTP 1.1. nextStreamId = server ? 2 : 1; // Push is disallowed by default for servers and allowed for clients. pushToAllowed = !server; maxActiveStreams = Integer.MAX_VALUE; } @Override public int nextStreamId() { // For manually created client-side streams, 1 is reserved for HTTP upgrade, so start at 3. return nextStreamId > 1 ? nextStreamId : nextStreamId + 2; } @Override public boolean isValidStreamId(int streamId) { boolean even = (streamId & 1) == 0; return streamId > 0 && server == even; } @Override public boolean mayHaveCreatedStream(int streamId) { return isValidStreamId(streamId) && streamId <= lastStreamCreated; } @Override public boolean canCreateStream() { return nextStreamId() > 0 && numActiveStreams + 1 <= maxActiveStreams; } private DefaultStream createStream(int streamId, State state) throws Http2Exception { checkNewStreamAllowed(streamId); // Create and initialize the stream. DefaultStream stream = new DefaultStream(streamId, state); // Update the next and last stream IDs. nextStreamId = streamId + 2; lastStreamCreated = streamId; addStream(stream); return stream; } @Override public DefaultStream createIdleStream(int streamId) throws Http2Exception { return createStream(streamId, IDLE); } @Override public DefaultStream createStream(int streamId, boolean halfClosed) throws Http2Exception { DefaultStream stream = createStream(streamId, activeState(streamId, IDLE, isLocal(), halfClosed)); stream.activate(); return stream; } @Override public boolean isServer() { return server; } @Override public DefaultStream reservePushStream(int streamId, Http2Stream parent) throws Http2Exception { if (parent == null) { throw connectionError(PROTOCOL_ERROR, "Parent stream missing"); } if (isLocal() ? !parent.localSideOpen() : !parent.remoteSideOpen()) { throw connectionError(PROTOCOL_ERROR, "Stream %d is not open for sending push promise", parent.id()); } if (!opposite().allowPushTo()) { throw connectionError(PROTOCOL_ERROR, "Server push not allowed to opposite endpoint."); } checkNewStreamAllowed(streamId); // Create and initialize the stream. DefaultStream stream = new DefaultStream(streamId, isLocal() ? RESERVED_LOCAL : RESERVED_REMOTE); // Update the next and last stream IDs. nextStreamId = streamId + 2; lastStreamCreated = streamId; // Register the stream. addStream(stream); return stream; } private void addStream(DefaultStream stream) { // Add the stream to the map and priority tree. streamMap.put(stream.id(), stream); List<ParentChangedEvent> events = new ArrayList<ParentChangedEvent>(1); connectionStream.takeChild(stream, false, events); // Notify the listeners of the event. for (int i = 0; i < listeners.size(); i++) { try { listeners.get(i).onStreamAdded(stream); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onStreamAdded.", e); } } notifyParentChanged(events); } @Override public void allowPushTo(boolean allow) { if (allow && server) { throw new IllegalArgumentException("Servers do not allow push"); } pushToAllowed = allow; } @Override public boolean allowPushTo() { return pushToAllowed; } @Override public int numActiveStreams() { return numActiveStreams; } @Override public int maxActiveStreams() { return maxActiveStreams; } @Override public void maxActiveStreams(int maxActiveStreams) { this.maxActiveStreams = maxActiveStreams; } @Override public int lastStreamCreated() { return lastStreamCreated; } @Override public int lastStreamKnownByPeer() { return lastStreamKnownByPeer; } private void lastStreamKnownByPeer(int lastKnownStream) { this.lastStreamKnownByPeer = lastKnownStream; } @Override public F flowController() { return flowController; } @Override public void flowController(F flowController) { this.flowController = checkNotNull(flowController, "flowController"); } @Override public Endpoint<? extends Http2FlowController> opposite() { return isLocal() ? remoteEndpoint : localEndpoint; } private void checkNewStreamAllowed(int streamId) throws Http2Exception { if (goAwayReceived() && streamId > localEndpoint.lastStreamKnownByPeer()) { throw connectionError(PROTOCOL_ERROR, "Cannot create stream %d since this endpoint has received a " + "GOAWAY frame with last stream id %d.", streamId, localEndpoint.lastStreamKnownByPeer()); } if (streamId < 0) { throw new Http2NoMoreStreamIdsException(); } if (!isValidStreamId(streamId)) { throw connectionError(PROTOCOL_ERROR, "Request stream %d is not correct for %s connection", streamId, server ? "server" : "client"); } // This check must be after all id validated checks, but before the max streams check because it may be // recoverable to some degree for handling frames which can be sent on closed streams. if (streamId < nextStreamId) { throw closedStreamError(PROTOCOL_ERROR, "Request stream %d is behind the next expected stream %d", streamId, nextStreamId); } if (!canCreateStream()) { throw connectionError(REFUSED_STREAM, "Maximum streams exceeded for this endpoint."); } } private boolean isLocal() { return this == localEndpoint; } } /** * Allows events which would modify the collection of active streams to be queued while iterating via {@link * #forEachActiveStream(Http2StreamVisitor)}. */ interface Event { /** * Trigger the original intention of this event. Expect to modify the active streams list. * <p/> * If a {@link RuntimeException} object is thrown it will be logged and <strong>not propagated</strong>. * Throwing from this method is not supported and is considered a programming error. */ void process(); } /** * Manages the list of currently active streams. Queues any {@link Event}s that would modify the list of * active streams in order to prevent modification while iterating. */ private final class ActiveStreams { private final List<Listener> listeners; private final Queue<Event> pendingEvents = new ArrayDeque<Event>(4); private final Set<Http2Stream> streams = new LinkedHashSet<Http2Stream>(); private int pendingIterations; public ActiveStreams(List<Listener> listeners) { this.listeners = listeners; } public int size() { return streams.size(); } public void activate(final DefaultStream stream) { if (allowModifications()) { addToActiveStreams(stream); } else { pendingEvents.add(new Event() { @Override public void process() { addToActiveStreams(stream); } }); } } public void deactivate(final DefaultStream stream) { if (allowModifications()) { removeFromActiveStreams(stream); } else { pendingEvents.add(new Event() { @Override public void process() { removeFromActiveStreams(stream); } }); } } public Http2Stream forEachActiveStream(Http2StreamVisitor visitor) throws Http2Exception { ++pendingIterations; try { for (Http2Stream stream : streams) { if (!visitor.visit(stream)) { return stream; } } return null; } finally { --pendingIterations; if (allowModifications()) { for (;;) { Event event = pendingEvents.poll(); if (event == null) { break; } try { event.process(); } catch (RuntimeException e) { logger.error("Caught RuntimeException while processing pending ActiveStreams$Event.", e); } } } } } void addToActiveStreams(DefaultStream stream) { if (streams.add(stream)) { // Update the number of active streams initiated by the endpoint. stream.createdBy().numActiveStreams++; for (int i = 0; i < listeners.size(); i++) { try { listeners.get(i).onStreamActive(stream); } catch (RuntimeException e) { logger.error("Caught RuntimeException from listener onStreamActive.", e); } } } } void removeFromActiveStreams(DefaultStream stream) { if (streams.remove(stream)) { // Update the number of active streams initiated by the endpoint. stream.createdBy().numActiveStreams--; } notifyClosed(stream); removeStream(stream); } private boolean allowModifications() { return pendingIterations == 0; } } /** * Implementation of {@link PropertyKey} that specifies the index position of the property. */ final class DefaultPropertyKey implements PropertyKey { private final int index; DefaultPropertyKey(int index) { this.index = index; } DefaultPropertyKey verifyConnection(Http2Connection connection) { if (connection != DefaultHttp2Connection.this) { throw new IllegalArgumentException("Using a key that was not created by this connection"); } return this; } } /** * A registry of all stream property keys known by this connection. */ private final class PropertyKeyRegistry { final List<DefaultPropertyKey> keys = new ArrayList<DefaultPropertyKey>(4); /** * Registers a new property key. */ DefaultPropertyKey newKey() { DefaultPropertyKey key = new DefaultPropertyKey(keys.size()); keys.add(key); return key; } int size() { return keys.size(); } } }
apache-2.0
stoksey69/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201505/DestinationUrlType.java
3144
/** * DestinationUrlType.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201505; public class DestinationUrlType implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected DestinationUrlType(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final java.lang.String _CLICK_TO_WEB = "CLICK_TO_WEB"; public static final java.lang.String _CLICK_TO_APP = "CLICK_TO_APP"; public static final java.lang.String _CLICK_TO_CALL = "CLICK_TO_CALL"; public static final DestinationUrlType UNKNOWN = new DestinationUrlType(_UNKNOWN); public static final DestinationUrlType CLICK_TO_WEB = new DestinationUrlType(_CLICK_TO_WEB); public static final DestinationUrlType CLICK_TO_APP = new DestinationUrlType(_CLICK_TO_APP); public static final DestinationUrlType CLICK_TO_CALL = new DestinationUrlType(_CLICK_TO_CALL); public java.lang.String getValue() { return _value_;} public static DestinationUrlType fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { DestinationUrlType enumeration = (DestinationUrlType) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static DestinationUrlType fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(DestinationUrlType.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "DestinationUrlType")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
apache-2.0
jeorme/OG-Platform
projects/OG-Engine/src/main/java/com/opengamma/engine/depgraph/AggregateResolvedValueProducer.java
9299
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.depgraph; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.engine.depgraph.ResolvedValueCallback.ResolvedValueCallbackChain; import com.opengamma.engine.value.ValueRequirement; /* package */class AggregateResolvedValueProducer extends AbstractResolvedValueProducer implements ResolvedValueCallbackChain { private static final Logger s_logger = LoggerFactory.getLogger(AggregateResolvedValueProducer.class); private int _pendingTasks = 1; private boolean _wantResult = true; private final List<ResolutionPump> _pumps = new ArrayList<ResolutionPump>(); public AggregateResolvedValueProducer(final ValueRequirement valueRequirement) { super(valueRequirement); } /** * Returns the number of pending tasks. The caller must hold the monitor. */ protected int getPendingTasks() { return _pendingTasks; } @Override public void failed(final GraphBuildingContext context, final ValueRequirement value, final ResolutionFailure failure) { s_logger.debug("Failed on {} for {}", value, this); Collection<ResolutionPump> pumps = null; synchronized (this) { if (_pendingTasks == Integer.MIN_VALUE) { // We were discarded after we requested the callback s_logger.debug("Failed resolution after discard of {}", this); return; } assert _pendingTasks > 0; if (--_pendingTasks == 0) { if (_wantResult) { s_logger.debug("Pumping underlying after last input failed for {}", this); pumps = pumpImpl(); } else { s_logger.debug("No pending tasks after last input failed for {} but no results requested", this); } } else { if (s_logger.isDebugEnabled()) { s_logger.debug("{} pending tasks for {}", _pendingTasks, this); } } } storeFailure(failure); pumpImpl(context, pumps); } /** * Tests if the result about to be pushed from {@link #resolved} can be considered the "last result". The result has come from the last pending task. The default behavior is to return true but a * sub-class that hooks the {@link #finished} call to introduce more productions must return false to avoid an intermediate last result being passed to the consumer of this aggregate. * <p> * This is called holding the monitor. * * @return true if the result really is the last result, false otherwise */ protected boolean isLastResult() { return true; } @Override public void resolved(final GraphBuildingContext context, final ValueRequirement valueRequirement, final ResolvedValue value, final ResolutionPump pump) { do { s_logger.debug("Received {} for {}", value, valueRequirement); boolean wantedResult = false; final boolean lastResult; synchronized (this) { if (_pendingTasks == Integer.MIN_VALUE) { // We were discarded after we requested the callback s_logger.debug("Successful resolution after discard of {}", this); break; } assert _pendingTasks > 0; if (_wantResult) { s_logger.debug("Clearing \"want result\" flag for {}", this); wantedResult = true; _wantResult = false; } lastResult = (pump == null) && (_pendingTasks == 1) && _pumps.isEmpty() && isLastResult(); } // Note that the lastResult indicator isn't 100% if there are concurrent calls to resolved. The "last" condition may // not be seen. The alternative would be to serialize the calls through pushResult so that we can guarantee spotting // the final one. if (pushResult(context, value, lastResult)) { Collection<ResolutionPump> pumps = null; synchronized (this) { if (_pendingTasks == Integer.MIN_VALUE) { // We were discarded while the result was handled s_logger.debug("Discard of {} while pushing result", this); break; } assert _pendingTasks > 0; if (pump != null) { _pumps.add(pump); } if (--_pendingTasks == 0) { if (_wantResult && !lastResult) { s_logger.debug("Pumping underlying after last input resolved for {}", this); pumps = pumpImpl(); } else { s_logger.debug("No pending tasks after last input resolved for {} but no further results requested", this); } } } pumpImpl(context, pumps); } else { if (wantedResult) { synchronized (this) { if (_pendingTasks == Integer.MIN_VALUE) { // We were discarded while the result was rejected s_logger.debug("Discard of {} while pushing rejected result", this); break; } assert _pendingTasks > 0; s_logger.debug("Reinstating \"want result\" flag for {}", this); _wantResult = true; } } if (pump != null) { context.pump(pump); } else { context.failed(this, valueRequirement, null); } } return; } while (false); if (pump != null) { context.close(pump); } } @Override public void recursionDetected() { // No-op by default } @Override protected void pumpImpl(final GraphBuildingContext context) { Collection<ResolutionPump> pumps = null; synchronized (this) { assert _pendingTasks >= 0; if (_pendingTasks == 0) { s_logger.debug("Pumping underlying since no pending tasks for {}", this); pumps = pumpImpl(); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Deferring pump while {} task(s) pending for {}", _pendingTasks, this); } _wantResult = true; } } pumpImpl(context, pumps); } // Caller must hold the monitor private Collection<ResolutionPump> pumpImpl() { if (_pumps.isEmpty()) { return Collections.emptyList(); } else { final List<ResolutionPump> pumps = new ArrayList<ResolutionPump>(_pumps); _pumps.clear(); _pendingTasks = pumps.size(); _wantResult = true; return pumps; } } private void pumpImpl(final GraphBuildingContext context, final Collection<ResolutionPump> pumps) { if (pumps != null) { if (pumps.isEmpty()) { // We have nothing to pump, so must have finished (failed) s_logger.debug("Finished {}", this); finished(context); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Pumping {} origin tasks from {}", pumps.size(), this); } for (ResolutionPump pump : pumps) { context.pump(pump); } } } } public void addProducer(final GraphBuildingContext context, final ResolvedValueProducer producer) { synchronized (this) { if (_pendingTasks == Integer.MIN_VALUE) { s_logger.debug("Discarded before fallback producer {} added to {}", producer, this); return; } assert _pendingTasks >= 0; if (_pendingTasks == 0) { _wantResult = true; } _pendingTasks++; if (s_logger.isDebugEnabled()) { s_logger.debug("{} pending tasks for {}", _pendingTasks, this); } } producer.addCallback(context, this); } public void start(final GraphBuildingContext context) { Collection<ResolutionPump> pumps = null; synchronized (this) { assert _pendingTasks >= 1; if (--_pendingTasks == 0) { if (_wantResult) { s_logger.debug("Pumping underlying after startup tasks completed for {}", this); pumps = pumpImpl(); } else { s_logger.debug("Startup tasks completed for {} but no further results requested", this); } } } pumpImpl(context, pumps); } @Override protected void finished(final GraphBuildingContext context) { assert _pendingTasks <= 1; super.finished(context); } @Override public int release(final GraphBuildingContext context) { final int count = super.release(context); if (count == 0) { List<ResolutionPump> pumps; synchronized (this) { if (s_logger.isDebugEnabled()) { s_logger.debug("Releasing {} - with {} pumped inputs", this, _pumps.size()); } // If _pendingTasks > 0 then there may be calls to failure or resolved from one or more of them. Setting _pendingTasks to // Integer.MIN_VALUE means we can detect these and discard them. Our reference count is zero so nothing subscribing to us // cares. _pendingTasks = Integer.MIN_VALUE; if (_pumps.isEmpty()) { return count; } pumps = new ArrayList<ResolutionPump>(_pumps); _pumps.clear(); } for (ResolutionPump pump : pumps) { context.close(pump); } } return count; } @Override public String toString() { return "AGGREGATE" + getObjectId(); } }
apache-2.0
apache/incubator-asterixdb-hyracks
hyracks/hyracks-storage-am-lsm-invertedindex/src/main/java/org/apache/hyracks/storage/am/lsm/invertedindex/tokenizers/NGramUTF8StringBinaryTokenizer.java
4452
/* * 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.hyracks.storage.am.lsm.invertedindex.tokenizers; import org.apache.hyracks.util.string.UTF8StringUtil; public class NGramUTF8StringBinaryTokenizer extends AbstractUTF8StringBinaryTokenizer { private int gramLength; private boolean usePrePost; private int gramNum; private int totalGrams; private final INGramToken concreteToken; public NGramUTF8StringBinaryTokenizer(int gramLength, boolean usePrePost, boolean ignoreTokenCount, boolean sourceHasTypeTag, ITokenFactory tokenFactory) { super(ignoreTokenCount, sourceHasTypeTag, tokenFactory); this.gramLength = gramLength; this.usePrePost = usePrePost; concreteToken = (INGramToken) token; } @Override public boolean hasNext() { if (gramNum < totalGrams) { return true; } else { return false; } } @Override public void next() { int currentTokenStart = byteIndex; int tokenCount = 1; int numPreChars = 0; int numPostChars = 0; if (usePrePost) { numPreChars = Math.max(gramLength - gramNum - 1, 0); numPostChars = (gramNum > totalGrams - gramLength) ? gramLength - totalGrams + gramNum : 0; } gramNum++; concreteToken.setNumPrePostChars(numPreChars, numPostChars); if (numPreChars == 0) { byteIndex += UTF8StringUtil.charSize(sentenceBytes, byteIndex); } // compute token count // ignore pre and post grams for duplicate detection if (!ignoreTokenCount && numPreChars == 0 && numPostChars == 0) { int tmpIndex = sentenceStartOffset; if (sourceHasTypeTag) { tmpIndex++; // skip type tag } int utfLength = UTF8StringUtil.getUTFLength(sentenceBytes, tmpIndex); tmpIndex += UTF8StringUtil.getNumBytesToStoreLength(utfLength); // skip utf8 length indicator while (tmpIndex < currentTokenStart) { tokenCount++; // assume found int offset = 0; for (int j = 0; j < gramLength; j++) { if (Character.toLowerCase(UTF8StringUtil.charAt(sentenceBytes, currentTokenStart + offset)) != Character.toLowerCase(UTF8StringUtil.charAt(sentenceBytes, tmpIndex + offset))) { tokenCount--; break; } offset += UTF8StringUtil.charSize(sentenceBytes, tmpIndex + offset); } tmpIndex += UTF8StringUtil.charSize(sentenceBytes, tmpIndex); } } // set token token.reset(sentenceBytes, currentTokenStart, sentenceEndOffset, gramLength, tokenCount); } @Override public void reset(byte[] sentenceData, int start, int length) { super.reset(sentenceData, start, length); gramNum = 0; int numChars = 0; int pos = byteIndex; int end = pos + sentenceUtf8Length; while (pos < end) { numChars++; pos += UTF8StringUtil.charSize(sentenceData, pos); } if (usePrePost) { totalGrams = numChars + gramLength - 1; } else { totalGrams = numChars - gramLength + 1; } } public void setGramlength(int gramLength) { this.gramLength = gramLength; } public void setPrePost(boolean usePrePost) { this.usePrePost = usePrePost; } @Override public short getTokensCount() { return (short) totalGrams; } }
apache-2.0
hsbhathiya/stratos
components/org.apache.stratos.autoscaler/src/main/java/org/apache/stratos/autoscaler/applications/topic/ApplicationsEventPublisher.java
7753
/* * 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.stratos.autoscaler.applications.topic; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.stratos.messaging.broker.publish.EventPublisher; import org.apache.stratos.messaging.broker.publish.EventPublisherPool; import org.apache.stratos.messaging.domain.application.Application; import org.apache.stratos.messaging.domain.application.Applications; import org.apache.stratos.messaging.domain.application.ClusterDataHolder; import org.apache.stratos.messaging.domain.instance.ApplicationInstance; import org.apache.stratos.messaging.domain.instance.GroupInstance; import org.apache.stratos.messaging.event.Event; import org.apache.stratos.messaging.event.application.*; import org.apache.stratos.messaging.util.MessagingUtil; import java.util.Set; /** * This will publish application related events to application status topic. */ public class ApplicationsEventPublisher { private static final Log log = LogFactory.getLog(ApplicationsEventPublisher.class); public static void sendCompleteApplicationsEvent(Applications completeApplications) { publishEvent(new CompleteApplicationsEvent(completeApplications)); } public static void sendApplicationCreatedEvent(Application application) { publishEvent(new ApplicationCreatedEvent(application)); } public static void sendApplicationDeletedEvent(String appId, Set<ClusterDataHolder> clusterData) { publishEvent(new ApplicationDeletedEvent(appId, clusterData)); } public static void sendApplicationInstanceCreatedEvent(String appId, ApplicationInstance applicationInstance) { publishEvent(new ApplicationInstanceCreatedEvent(appId, applicationInstance)); } public static void sendGroupInstanceCreatedEvent(String appId, String groupId, GroupInstance groupInstance) { if (log.isInfoEnabled()) { log.info("Publishing group instance created event: [application] " + appId + " [group] " + groupId + " [instance] " + groupInstance.getInstanceId()); } GroupInstanceCreatedEvent groupCreatedEvent = new GroupInstanceCreatedEvent(appId, groupId, groupInstance); publishEvent(groupCreatedEvent); } public static void sendGroupInstanceActivatedEvent(String appId, String groupId, String instanceId) { if (log.isInfoEnabled()) { log.info("Publishing group instance activated event: [application] " + appId + " [group] " + groupId + " [instance] " + instanceId); } GroupInstanceActivatedEvent groupActivatedEvent = new GroupInstanceActivatedEvent(appId, groupId, instanceId); publishEvent(groupActivatedEvent); } public static void sendGroupInstanceInactivateEvent(String appId, String groupId, String instanceId) { if (log.isInfoEnabled()) { log.info("Publishing group instance inactivate event: [application] " + appId + " [group] " + groupId + " [instance] " + instanceId); } GroupInstanceInactivatedEvent groupInactivateEvent = new GroupInstanceInactivatedEvent(appId, groupId, instanceId); publishEvent(groupInactivateEvent); } public static void sendGroupInstanceTerminatingEvent(String appId, String groupId, String instanceId) { if (log.isInfoEnabled()) { log.info("Publishing group instance terminating event: [application] " + appId + " [group] " + groupId + " [instance] " + instanceId); } GroupInstanceTerminatingEvent groupInTerminatingEvent = new GroupInstanceTerminatingEvent(appId, groupId, instanceId); publishEvent(groupInTerminatingEvent); } public static void sendGroupInstanceTerminatedEvent(String appId, String groupId, String instanceId) { if (log.isInfoEnabled()) { log.info("Publishing group instance terminated event: [application] " + appId + " [group] " + groupId + " [instance] " + instanceId); } GroupInstanceTerminatedEvent groupInTerminatedEvent = new GroupInstanceTerminatedEvent(appId, groupId, instanceId); publishEvent(groupInTerminatedEvent); } public static void sendApplicationInstanceActivatedEvent(String appId, String instanceId) { if (log.isInfoEnabled()) { log.info("Publishing application instance active event: [application] " + appId + " [instance] " + instanceId); } ApplicationInstanceActivatedEvent applicationActivatedEvent = new ApplicationInstanceActivatedEvent(appId, instanceId); publishEvent(applicationActivatedEvent); } public static void sendApplicationInstanceInactivatedEvent(String appId, String instanceId) { if (log.isInfoEnabled()) { log.info("Publishing application instance in-activated event: [application] " + appId + " [instance] " + instanceId); } ApplicationInstanceInactivatedEvent applicationInactivatedEvent = new ApplicationInstanceInactivatedEvent(appId, instanceId); publishEvent(applicationInactivatedEvent); } public static void sendApplicationInstanceTerminatingEvent(String appId, String instanceId) { if (log.isInfoEnabled()) { log.info("Publishing application instance terminating event: [application] " + appId + " [instance] " + instanceId); } ApplicationInstanceTerminatingEvent applicationTerminatingEvent = new ApplicationInstanceTerminatingEvent(appId, instanceId); publishEvent(applicationTerminatingEvent); } public static void sendApplicationInstanceTerminatedEvent(String appId, String instanceId) { if (log.isInfoEnabled()) { log.info("Publishing application instance terminated event: [application] " + appId + " [instance] " + instanceId); } ApplicationInstanceTerminatedEvent applicationTerminatedEvent = new ApplicationInstanceTerminatedEvent(appId, instanceId); publishEvent(applicationTerminatedEvent); } public static void publishEvent(Event event) { //publishing events to application status topic String applicationTopic = MessagingUtil.getMessageTopicName(event); EventPublisher eventPublisher = EventPublisherPool.getPublisher(applicationTopic); eventPublisher.publish(event); } }
apache-2.0
tkaefer/camunda-bpm-platform
engine/src/test/java/org/camunda/bpm/application/impl/deployment/parser/ProcessesXmlParserTest.java
9431
package org.camunda.bpm.application.impl.deployment.parser; import java.net.URL; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.camunda.bpm.application.impl.metadata.ProcessesXmlParser; import org.camunda.bpm.application.impl.metadata.spi.ProcessArchiveXml; import org.camunda.bpm.application.impl.metadata.spi.ProcessesXml; import org.camunda.bpm.container.impl.metadata.spi.ProcessEngineXml; import org.camunda.bpm.engine.ProcessEngineException; /** * <p>The testcases for the {@link ProcessesXmlParser}</p> * * @author Daniel Meyer * */ public class ProcessesXmlParserTest extends TestCase { private ProcessesXmlParser parser; protected void setUp() throws Exception { parser = new ProcessesXmlParser(); super.setUp(); } protected URL getStreamUrl(String filename) { return ProcessesXmlParserTest.class.getResource(filename); } public void testParseProcessesXmlOneEngine() { ProcessesXml processesXml = parser.createParse() .sourceUrl(getStreamUrl("process_xml_one_engine.xml")) .execute() .getProcessesXml(); assertNotNull(processesXml); assertEquals(1, processesXml.getProcessEngines().size()); assertEquals(0, processesXml.getProcessArchives().size()); ProcessEngineXml engineXml = processesXml.getProcessEngines().get(0); assertEquals("default", engineXml.getName()); assertEquals("default", engineXml.getJobAcquisitionName()); assertEquals("configuration", engineXml.getConfigurationClass()); assertEquals("datasource", engineXml.getDatasource()); Map<String, String> properties = engineXml.getProperties(); assertNotNull(properties); assertEquals(2, properties.size()); assertEquals("value1", properties.get("prop1")); assertEquals("value2", properties.get("prop2")); } public void testParseProcessesXmlTwoEngines() { ProcessesXml processesXml = parser.createParse() .sourceUrl(getStreamUrl("process_xml_two_engines.xml")) .execute() .getProcessesXml(); assertNotNull(processesXml); assertEquals(2, processesXml.getProcessEngines().size()); assertEquals(0, processesXml.getProcessArchives().size()); ProcessEngineXml engineXml1 = processesXml.getProcessEngines().get(0); assertEquals("engine1", engineXml1.getName()); assertEquals("configuration", engineXml1.getConfigurationClass()); assertEquals("datasource", engineXml1.getDatasource()); Map<String, String> properties1 = engineXml1.getProperties(); assertNotNull(properties1); assertEquals(2, properties1.size()); assertEquals("value1", properties1.get("prop1")); assertEquals("value2", properties1.get("prop2")); ProcessEngineXml engineXml2 = processesXml.getProcessEngines().get(1); assertEquals("engine2", engineXml2.getName()); assertEquals("configuration", engineXml2.getConfigurationClass()); assertEquals("datasource", engineXml2.getDatasource()); // the second engine has no properties Map<String, String> properties2 = engineXml2.getProperties(); assertNotNull(properties2); assertEquals(0, properties2.size()); } public void testParseProcessesXmlOneArchive() { ProcessesXml processesXml = parser.createParse() .sourceUrl(getStreamUrl("process_xml_one_archive.xml")) .execute() .getProcessesXml(); assertNotNull(processesXml); assertEquals(0, processesXml.getProcessEngines().size()); assertEquals(1, processesXml.getProcessArchives().size()); ProcessArchiveXml archiveXml1 = processesXml.getProcessArchives().get(0); assertEquals("pa1", archiveXml1.getName()); assertEquals("default", archiveXml1.getProcessEngineName()); List<String> resourceNames = archiveXml1.getProcessResourceNames(); assertEquals(2, resourceNames.size()); assertEquals("process1.bpmn", resourceNames.get(0)); assertEquals("process2.bpmn", resourceNames.get(1)); Map<String, String> properties1 = archiveXml1.getProperties(); assertNotNull(properties1); assertEquals(2, properties1.size()); assertEquals("value1", properties1.get("prop1")); assertEquals("value2", properties1.get("prop2")); } public void testParseProcessesXmlTwoArchives() { ProcessesXml processesXml = parser.createParse() .sourceUrl(getStreamUrl("process_xml_two_archives.xml")) .execute() .getProcessesXml(); assertNotNull(processesXml); assertEquals(0, processesXml.getProcessEngines().size()); assertEquals(2, processesXml.getProcessArchives().size()); ProcessArchiveXml archiveXml1 = processesXml.getProcessArchives().get(0); assertEquals("pa1", archiveXml1.getName()); assertEquals("default", archiveXml1.getProcessEngineName()); List<String> resourceNames = archiveXml1.getProcessResourceNames(); assertEquals(2, resourceNames.size()); assertEquals("process1.bpmn", resourceNames.get(0)); assertEquals("process2.bpmn", resourceNames.get(1)); Map<String, String> properties1 = archiveXml1.getProperties(); assertNotNull(properties1); assertEquals(2, properties1.size()); assertEquals("value1", properties1.get("prop1")); assertEquals("value2", properties1.get("prop2")); ProcessArchiveXml archiveXml2 = processesXml.getProcessArchives().get(1); assertEquals("pa2", archiveXml2.getName()); assertEquals("default", archiveXml2.getProcessEngineName()); List<String> resourceNames2 = archiveXml2.getProcessResourceNames(); assertEquals(2, resourceNames.size()); assertEquals("process1.bpmn", resourceNames2.get(0)); assertEquals("process2.bpmn", resourceNames2.get(1)); Map<String, String> properties2 = archiveXml2.getProperties(); assertNotNull(properties2); assertEquals(0, properties2.size()); } public void testParseProcessesXmlTwoArchivesAndTwoEngines() { ProcessesXml processesXml = parser.createParse() .sourceUrl(getStreamUrl("process_xml_two_archives_two_engines.xml")) .execute() .getProcessesXml(); assertNotNull(processesXml); assertEquals(2, processesXml.getProcessEngines().size()); assertEquals(2, processesXml.getProcessArchives().size()); // validate archives ProcessArchiveXml archiveXml1 = processesXml.getProcessArchives().get(0); assertEquals("pa1", archiveXml1.getName()); assertEquals("default", archiveXml1.getProcessEngineName()); List<String> resourceNames = archiveXml1.getProcessResourceNames(); assertEquals(2, resourceNames.size()); assertEquals("process1.bpmn", resourceNames.get(0)); assertEquals("process2.bpmn", resourceNames.get(1)); Map<String, String> properties1 = archiveXml1.getProperties(); assertNotNull(properties1); assertEquals(2, properties1.size()); assertEquals("value1", properties1.get("prop1")); assertEquals("value2", properties1.get("prop2")); ProcessArchiveXml archiveXml2 = processesXml.getProcessArchives().get(1); assertEquals("pa2", archiveXml2.getName()); assertEquals("default", archiveXml2.getProcessEngineName()); List<String> resourceNames2 = archiveXml2.getProcessResourceNames(); assertEquals(2, resourceNames.size()); assertEquals("process1.bpmn", resourceNames2.get(0)); assertEquals("process2.bpmn", resourceNames2.get(1)); Map<String, String> properties2 = archiveXml2.getProperties(); assertNotNull(properties2); assertEquals(0, properties2.size()); // validate engines ProcessEngineXml engineXml1 = processesXml.getProcessEngines().get(0); assertEquals("engine1", engineXml1.getName()); assertEquals("configuration", engineXml1.getConfigurationClass()); assertEquals("datasource", engineXml1.getDatasource()); properties1 = engineXml1.getProperties(); assertNotNull(properties1); assertEquals(2, properties1.size()); assertEquals("value1", properties1.get("prop1")); assertEquals("value2", properties1.get("prop2")); ProcessEngineXml engineXml2 = processesXml.getProcessEngines().get(1); assertEquals("engine2", engineXml2.getName()); assertEquals("configuration", engineXml2.getConfigurationClass()); assertEquals("datasource", engineXml2.getDatasource()); // the second engine has no properties properties2 = engineXml2.getProperties(); assertNotNull(properties2); assertEquals(0, properties2.size()); } public void testParseProcessesXmlEngineNoName() { // this test is to make sure that XML Schema Validation works. try { parser.createParse() .sourceUrl(getStreamUrl("process_xml_engine_no_name.xml")) .execute(); fail("exceptoion expected"); } catch(ProcessEngineException e) { // expected } } public void testParseProcessesXmlNsPrefix() { ProcessesXml processesXml = parser.createParse() .sourceUrl(getStreamUrl("process_xml_ns_prefix.xml")) .execute() .getProcessesXml(); assertNotNull(processesXml); assertEquals(1, processesXml.getProcessEngines().size()); assertEquals(1, processesXml.getProcessArchives().size()); } }
apache-2.0
GunoH/intellij-community
platform/platform-api/src/com/intellij/ui/ComboboxWithBrowseButton.java
2124
/* * Copyright 2000-2009 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 com.intellij.ui; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.ui.TextComponentAccessor; import org.jetbrains.annotations.ApiStatus; import javax.swing.*; import java.awt.*; /** * @deprecated please use ComboBox with browse extension, see <a href="https://jetbrains.design/intellij/controls/built_in_button/#browse">UI guidelines</a> * for details */ @ApiStatus.ScheduledForRemoval(inVersion = "2022.3") @Deprecated public class ComboboxWithBrowseButton extends ComponentWithBrowseButton<JComboBox> { public ComboboxWithBrowseButton() { super(new JComboBox(), null); } public ComboboxWithBrowseButton(JComboBox comboBox) { super(comboBox, null); } public JComboBox getComboBox() { return getChildComponent(); } @Override public void setTextFieldPreferredWidth(final int charCount) { super.setTextFieldPreferredWidth(charCount); final Component comp = getChildComponent().getEditor().getEditorComponent(); Dimension size = comp.getPreferredSize(); FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont()); size.width = fontMetrics.charWidth('a') * charCount; comp.setPreferredSize(size); } public void addBrowseFolderListener(Project project, FileChooserDescriptor descriptor) { addBrowseFolderListener(null, null, project, descriptor, TextComponentAccessor.STRING_COMBOBOX_WHOLE_TEXT); } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-runtimeconfig/v1beta1/1.31.0/com/google/api/services/runtimeconfig/v1beta1/CloudRuntimeConfigRequestInitializer.java
3609
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.runtimeconfig.v1beta1; /** * CloudRuntimeConfig request initializer for setting properties like key and userIp. * * <p> * The simplest usage is to use it to set the key parameter: * </p> * * <pre> public static final GoogleClientRequestInitializer KEY_INITIALIZER = new CloudRuntimeConfigRequestInitializer(KEY); * </pre> * * <p> * There is also a constructor to set both the key and userIp parameters: * </p> * * <pre> public static final GoogleClientRequestInitializer INITIALIZER = new CloudRuntimeConfigRequestInitializer(KEY, USER_IP); * </pre> * * <p> * If you want to implement custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer extends CloudRuntimeConfigRequestInitializer { {@literal @}Override public void initializeCloudRuntimeConfigRequest(CloudRuntimeConfigRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer2 extends CloudRuntimeConfigRequestInitializer { public MyKeyRequestInitializer() { super(KEY, USER_IP); } {@literal @}Override public void initializeCloudRuntimeConfigRequest(CloudRuntimeConfigRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Subclasses should be thread-safe. * </p> * * @since 1.12 */ public class CloudRuntimeConfigRequestInitializer extends com.google.api.client.googleapis.services.json.CommonGoogleJsonClientRequestInitializer { public CloudRuntimeConfigRequestInitializer() { super(); } /** * @param key API key or {@code null} to leave it unchanged */ public CloudRuntimeConfigRequestInitializer(String key) { super(key); } /** * @param key API key or {@code null} to leave it unchanged * @param userIp user IP or {@code null} to leave it unchanged */ public CloudRuntimeConfigRequestInitializer(String key, String userIp) { super(key, userIp); } @Override public final void initializeJsonRequest(com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest<?> request) throws java.io.IOException { super.initializeJsonRequest(request); initializeCloudRuntimeConfigRequest((CloudRuntimeConfigRequest<?>) request); } /** * Initializes CloudRuntimeConfig request. * * <p> * Default implementation does nothing. Called from * {@link #initializeJsonRequest(com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest)}. * </p> * * @throws java.io.IOException I/O exception */ protected void initializeCloudRuntimeConfigRequest(CloudRuntimeConfigRequest<?> request) throws java.io.IOException { } }
apache-2.0
maxkondr/onos-porta
core/api/src/main/java/org/onosproject/core/DefaultApplication.java
4987
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.core; import java.net.URI; import java.util.Set; import java.util.Optional; import java.util.List; import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * Default implementation of network control/management application descriptor. */ public class DefaultApplication implements Application { private final ApplicationId appId; private final Version version; private final String description; private final String origin; private final ApplicationRole role; private final Set<Permission> permissions; private final Optional<URI> featuresRepo; private final List<String> features; /** * Creates a new application descriptor using the supplied data. * * @param appId application identifier * @param version application version * @param description application description * @param origin origin company * @param role application role * @param permissions requested permissions * @param featuresRepo optional features repo URI * @param features application features */ public DefaultApplication(ApplicationId appId, Version version, String description, String origin, ApplicationRole role, Set<Permission> permissions, Optional<URI> featuresRepo, List<String> features) { this.appId = checkNotNull(appId, "ID cannot be null"); this.version = checkNotNull(version, "Version cannot be null"); this.description = checkNotNull(description, "Description cannot be null"); this.origin = checkNotNull(origin, "Origin cannot be null"); this.role = checkNotNull(role, "Role cannot be null"); this.permissions = checkNotNull(permissions, "Permissions cannot be null"); this.featuresRepo = checkNotNull(featuresRepo, "Features repo cannot be null"); this.features = checkNotNull(features, "Features cannot be null"); checkArgument(!features.isEmpty(), "There must be at least one feature"); } @Override public ApplicationId id() { return appId; } @Override public Version version() { return version; } @Override public String description() { return description; } @Override public String origin() { return origin; } @Override public ApplicationRole role() { return role; } @Override public Set<Permission> permissions() { return permissions; } @Override public Optional<URI> featuresRepo() { return featuresRepo; } @Override public List<String> features() { return features; } @Override public int hashCode() { return Objects.hash(appId, version, description, origin, role, permissions, featuresRepo, features); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final DefaultApplication other = (DefaultApplication) obj; return Objects.equals(this.appId, other.appId) && Objects.equals(this.version, other.version) && Objects.equals(this.description, other.description) && Objects.equals(this.origin, other.origin) && Objects.equals(this.role, other.role) && Objects.equals(this.permissions, other.permissions) && Objects.equals(this.featuresRepo, other.featuresRepo) && Objects.equals(this.features, other.features); } @Override public String toString() { return toStringHelper(this) .add("appId", appId) .add("version", version) .add("description", description) .add("origin", origin) .add("role", role) .add("permissions", permissions) .add("featuresRepo", featuresRepo) .add("features", features) .toString(); } }
apache-2.0
topicusonderwijs/wicket
wicket-native-websocket/wicket-native-websocket-core/src/main/java/org/apache/wicket/protocol/ws/api/message/IWebSocketMessage.java
963
/* * 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.wicket.protocol.ws.api.message; /** * A marker interface for all message types * * @since 6.0 */ public interface IWebSocketMessage { }
apache-2.0
minifirocks/nifi-minifi-cpp
thirdparty/rocksdb/java/src/main/java/org/rocksdb/ReadTier.java
1219
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). package org.rocksdb; /** * RocksDB {@link ReadOptions} read tiers. */ public enum ReadTier { READ_ALL_TIER((byte)0), BLOCK_CACHE_TIER((byte)1), PERSISTED_TIER((byte)2); private final byte value; ReadTier(final byte value) { this.value = value; } /** * Returns the byte value of the enumerations value * * @return byte representation */ public byte getValue() { return value; } /** * Get ReadTier by byte value. * * @param value byte representation of ReadTier. * * @return {@link org.rocksdb.ReadTier} instance or null. * @throws java.lang.IllegalArgumentException if an invalid * value is provided. */ public static ReadTier getReadTier(final byte value) { for (final ReadTier readTier : ReadTier.values()) { if (readTier.getValue() == value){ return readTier; } } throw new IllegalArgumentException("Illegal value provided for ReadTier."); } }
apache-2.0
goodwinnk/intellij-community
java/java-tests/testData/inspection/streamApiCallChains/afterAllMatchContains.java
737
// "Fix all 'Simplify stream API call chains' problems in file" "true" import java.util.*; class Test { public void test(List<String> list, Set<String> set, Iterable<String> it) { if(set.containsAll(list)) { System.out.println("all matched"); } if(list.containsAll(set)) { System.out.println("all matched"); } /*one*/ if(((Collection<String>/*two*/) it).containsAll(set)) { System.out.println("all matched"); } } static class MyList extends ArrayList<String> { @Override public boolean containsAll(Collection<?> c) { // do not replace when this-reference is used as infinite recursion might be produced return c.stream().allMatch(this::contains); } } }
apache-2.0
ydai1124/gobblin-1
gobblin-utility/src/test/java/gobblin/util/io/StreamCopierTest.java
2754
/* * 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 gobblin.util.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import org.testng.Assert; import org.testng.annotations.Test; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import com.google.common.base.Charsets; import gobblin.util.limiter.CountBasedLimiter; public class StreamCopierTest { @Test public void testSimpleCopy() throws Exception { String testString = "This is a string"; ByteArrayInputStream inputStream = new ByteArrayInputStream(testString.getBytes(Charsets.UTF_8)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new StreamCopier(inputStream, outputStream).copy(); Assert.assertEquals(testString, new String(outputStream.toByteArray(), Charsets.UTF_8)); } @Test public void testLongCopy() throws Exception { StringBuilder builder = new StringBuilder(); for (int i = 0; i < 1000; i++) { builder.append("testString"); } String testString = builder.toString(); ByteArrayInputStream inputStream = new ByteArrayInputStream(testString.getBytes(Charsets.UTF_8)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new StreamCopier(inputStream, outputStream).withBufferSize(100).copy(); Assert.assertEquals(testString, new String(outputStream.toByteArray(), Charsets.UTF_8)); } @Test public void testCopyMeter() throws Exception { String testString = "This is a string"; Meter meter = new MetricRegistry().meter("my.meter"); ByteArrayInputStream inputStream = new ByteArrayInputStream(testString.getBytes(Charsets.UTF_8)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); new StreamCopier(inputStream, outputStream).withCopySpeedMeter(meter).copy(); Assert.assertEquals(testString, new String(outputStream.toByteArray(), Charsets.UTF_8)); Assert.assertEquals(meter.getCount(), testString.length()); } }
apache-2.0
flaminc/olingo-odata4
lib/client-api/src/main/java/org/apache/olingo/client/api/communication/request/cud/ODataEntityCreateRequest.java
1482
/* * 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.olingo.client.api.communication.request.cud; import org.apache.olingo.client.api.communication.request.ODataBasicRequest; import org.apache.olingo.client.api.communication.request.ODataBatchableRequest; import org.apache.olingo.client.api.communication.response.ODataEntityCreateResponse; import org.apache.olingo.client.api.domain.ClientEntity; /** * This interface describes an OData create request. * * @param <E> concrete ODataEntity implementation */ public interface ODataEntityCreateRequest<E extends ClientEntity> extends ODataBasicRequest<ODataEntityCreateResponse<E>>, ODataBatchableRequest { //No additional methods needed for now. }
apache-2.0
gstevey/gradle
subprojects/dependency-management/src/main/java/org/gradle/internal/resolve/result/DefaultResourceAwareResolveResult.java
1385
/* * Copyright 2014 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.gradle.internal.resolve.result; import org.gradle.internal.resource.ExternalResourceName; import java.util.ArrayList; import java.util.List; public class DefaultResourceAwareResolveResult implements ResourceAwareResolveResult { private final List<String> attempted = new ArrayList<String>(); public List<String> getAttempted() { return attempted; } public void attempted(String locationDescription) { attempted.add(locationDescription); } public void attempted(ExternalResourceName location) { attempted(location.getDisplayName()); } public void applyTo(ResourceAwareResolveResult target) { for (String location : attempted) { target.attempted(location); } } }
apache-2.0
KurtStam/syndesis-rest
credential/src/main/java/io/syndesis/credential/CredentialProvider.java
1031
/** * Copyright (C) 2016 Red Hat, 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.syndesis.credential; import java.net.URI; import io.syndesis.model.connection.Connection; public interface CredentialProvider { AcquisitionMethod acquisitionMethod(); Connection applyTo(Connection connection, CredentialFlowState flowState); CredentialFlowState finish(CredentialFlowState flowState, URI baseUrl); String id(); CredentialFlowState prepare(URI baseUrl, URI returnUrl); }
apache-2.0
ultratendency/hbase
hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAsyncTableBatchRetryImmediately.java
3883
/** * 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.client; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.testclassification.ClientTests; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; @Category({ MediumTests.class, ClientTests.class }) public class TestAsyncTableBatchRetryImmediately { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestAsyncTableBatchRetryImmediately.class); private static final HBaseTestingUtility UTIL = new HBaseTestingUtility(); private static TableName TABLE_NAME = TableName.valueOf("async"); private static byte[] FAMILY = Bytes.toBytes("cf"); private static byte[] QUAL = Bytes.toBytes("cq"); private static byte[] VALUE_PREFIX = new byte[768]; private static int COUNT = 1000; private static AsyncConnection CONN; @BeforeClass public static void setUp() throws Exception { // disable the debug log to avoid flooding the output LogManager.getLogger(AsyncRegionLocatorHelper.class).setLevel(Level.INFO); UTIL.getConfiguration().setLong(HConstants.HBASE_SERVER_SCANNER_MAX_RESULT_SIZE_KEY, 1024); UTIL.startMiniCluster(1); Table table = UTIL.createTable(TABLE_NAME, FAMILY); UTIL.waitTableAvailable(TABLE_NAME); ThreadLocalRandom.current().nextBytes(VALUE_PREFIX); for (int i = 0; i < COUNT; i++) { table.put(new Put(Bytes.toBytes(i)).addColumn(FAMILY, QUAL, Bytes.add(VALUE_PREFIX, Bytes.toBytes(i)))); } CONN = ConnectionFactory.createAsyncConnection(UTIL.getConfiguration()).get(); } @AfterClass public static void tearDown() throws Exception { CONN.close(); UTIL.shutdownMiniCluster(); } @Test public void test() { AsyncTable<?> table = CONN.getTable(TABLE_NAME); // if we do not deal with RetryImmediatelyException, we will timeout here since we need to retry // hundreds times. List<Get> gets = IntStream.range(0, COUNT).mapToObj(i -> new Get(Bytes.toBytes(i))) .collect(Collectors.toList()); List<Result> results = table.getAll(gets).join(); for (int i = 0; i < COUNT; i++) { byte[] value = results.get(i).getValue(FAMILY, QUAL); assertEquals(VALUE_PREFIX.length + 4, value.length); assertArrayEquals(VALUE_PREFIX, Arrays.copyOf(value, VALUE_PREFIX.length)); assertEquals(i, Bytes.toInt(value, VALUE_PREFIX.length)); } } }
apache-2.0
Darsstar/framework
shared/src/main/java/com/vaadin/shared/ui/grid/GridServerRpc.java
3291
/* * Copyright 2000-2016 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.shared.ui.grid; import java.util.List; import com.vaadin.shared.MouseEventDetails; import com.vaadin.shared.communication.ServerRpc; import com.vaadin.shared.data.sort.SortDirection; import com.vaadin.shared.ui.grid.GridConstants.Section; /** * Client-to-server RPC interface for the Grid component. * * @since 7.4 * @author Vaadin Ltd */ public interface GridServerRpc extends ServerRpc { void sort(String[] columnIds, SortDirection[] directions, boolean userOriginated); /** * Informs the server that an item has been clicked in Grid. * * @param rowKey * a key identifying the clicked item * @param columnInternalId * column internal id identifying the clicked property * @param details * mouse event details */ void itemClick(String rowKey, String columnInternalId, MouseEventDetails details); /** * Informs the server that a context click has happened inside of Grid. * * @since 7.6 * @param rowIndex * index of clicked row in Grid section * @param rowKey * a key identifying the clicked item * @param columnInternalId * column internal id identifying the clicked property * @param section * grid section (header, footer, body) * @param details * mouse event details */ void contextClick(int rowIndex, String rowKey, String columnInternalId, Section section, MouseEventDetails details); /** * Informs the server that the columns of the Grid have been reordered. * * @since 7.5.0 * @param newColumnOrder * a list of column internal ids in the new order * @param oldColumnOrder * a list of column internal ids in order before the change */ void columnsReordered(List<String> newColumnOrder, List<String> oldColumnOrder); /** * Informs the server that a column's visibility has been changed. * * @since 8.0 * @param columnInternalId * the internal id of the column * @param hidden * <code>true</code> if hidden, <code>false</code> if unhidden */ void columnVisibilityChanged(String columnInternalId, boolean hidden); /** * Informs the server that a column has been resized by the user. * * @since 7.6 * @param columnInternalId * the internal id of the column * @param pixels * the new width of the column in pixels */ void columnResized(String columnInternalId, double pixels); }
apache-2.0
jomarko/kie-wb-common
kie-wb-common-dmn/kie-wb-common-dmn-client/src/main/java/org/kie/workbench/common/dmn/client/marshaller/included/DMNMarshallerImportsClientHelper.java
26251
/* * Copyright 2020 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.workbench.common.dmn.client.marshaller.included; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.inject.Inject; import javax.xml.namespace.QName; import elemental2.promise.Promise; import jsinterop.base.Js; import org.kie.workbench.common.dmn.api.definition.model.DRGElement; import org.kie.workbench.common.dmn.api.definition.model.Definitions; import org.kie.workbench.common.dmn.api.definition.model.ItemDefinition; import org.kie.workbench.common.dmn.api.editors.included.DMNImportTypes; import org.kie.workbench.common.dmn.api.editors.included.DMNIncludedModel; import org.kie.workbench.common.dmn.api.editors.included.DMNIncludedNode; import org.kie.workbench.common.dmn.api.editors.included.IncludedModel; import org.kie.workbench.common.dmn.api.editors.included.PMMLDocumentMetadata; import org.kie.workbench.common.dmn.api.editors.included.PMMLIncludedModel; import org.kie.workbench.common.dmn.api.marshalling.DMNMarshallerImportsHelper; import org.kie.workbench.common.dmn.client.marshaller.converters.ImportedItemDefinitionPropertyConverter; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITDMNElement; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITDRGElement; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITDecision; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITDefinitions; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITImport; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITInformationItem; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITInputData; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITInvocable; import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITItemDefinition; import org.kie.workbench.common.stunner.core.client.service.ClientRuntimeError; import org.kie.workbench.common.stunner.core.client.service.ServiceCallback; import org.kie.workbench.common.stunner.core.diagram.Metadata; import org.kie.workbench.common.stunner.core.util.FileUtils; import org.uberfire.client.promise.Promises; import static org.kie.workbench.common.dmn.api.editors.types.BuiltInTypeUtils.isBuiltInType; import static org.kie.workbench.common.dmn.client.marshaller.converters.ImportedItemDefinitionPropertyConverter.withNamespace; import static org.kie.workbench.common.stunner.core.util.StringUtils.isEmpty; public class DMNMarshallerImportsClientHelper implements DMNMarshallerImportsHelper<JSITImport, JSITDefinitions, JSITDRGElement, JSITItemDefinition> { private final DMNMarshallerImportsService dmnImportsService; private final DMNMarshallerImportsContentService dmnImportsContentService; private final Promises promises; private final DMNIncludedNodeFactory includedModelFactory; private static final Logger LOGGER = Logger.getLogger(DMNMarshallerImportsClientHelper.class.getName()); @Inject public DMNMarshallerImportsClientHelper(final DMNMarshallerImportsService dmnImportsService, final DMNMarshallerImportsContentService dmnImportsContentService, final Promises promises, final DMNIncludedNodeFactory includedModelFactory) { this.dmnImportsService = dmnImportsService; this.dmnImportsContentService = dmnImportsContentService; this.promises = promises; this.includedModelFactory = includedModelFactory; } public Promise<Map<JSITImport, JSITDefinitions>> getImportDefinitionsAsync(final Metadata metadata, final List<JSITImport> imports) { if (!imports.isEmpty()) { return loadDMNDefinitions().then(otherDefinitions -> { final Map<JSITImport, JSITDefinitions> importDefinitions = new HashMap<>(); for (final Map.Entry<String, JSITDefinitions> entry : otherDefinitions.entrySet()) { final JSITDefinitions def = Js.uncheckedCast(entry.getValue()); findImportByDefinitions(def, imports).ifPresent(anImport -> { final JSITImport foundImported = Js.uncheckedCast(anImport); importDefinitions.put(foundImported, def); }); } return promises.resolve(importDefinitions); }); } return promises.resolve(Collections.emptyMap()); } private Promise<Map<String, JSITDefinitions>> loadDMNDefinitions() { return dmnImportsContentService.getModelsDMNFilesURIs() .then(list -> { if (list.length == 0) { return promises.resolve(Collections.emptyMap()); } else { final Map<String, JSITDefinitions> otherDefinitions = new ConcurrentHashMap<>(); return promises.all(Arrays.asList(list), (String file) -> loadDefinitionFromFile(file, otherDefinitions)) .then(v -> promises.resolve(otherDefinitions)); } }); } public void loadNodesFromModels(final List<DMNIncludedModel> includedModels, final ServiceCallback<List<DMNIncludedNode>> callback) { final List<DMNIncludedNode> result = new ArrayList<>(); if (includedModels.isEmpty()) { callback.onSuccess(result); } else { loadDMNDefinitions() .then(existingDefinitions -> promises.all(includedModels, model -> loadNodes(existingDefinitions, model, result)) .then(p -> { callback.onSuccess(result); return promises.resolve(); })); } } private Promise<List<DMNIncludedNode>> loadNodes(final Map<String, JSITDefinitions> existingDefinitions, final DMNIncludedModel model, final List<DMNIncludedNode> result) { String filePath = ""; for (final Map.Entry<String, JSITDefinitions> entry : existingDefinitions.entrySet()) { filePath = entry.getKey(); final JSITDefinitions definitions = Js.uncheckedCast(entry.getValue()); if (Objects.equals(model.getNamespace(), definitions.getNamespace())) { break; } } if (isEmpty(filePath)) { return promises.resolve(); } final String path = filePath; return dmnImportsContentService.loadFile(path) .then(content -> promises.create((success, fail) -> dmnImportsService.getDRGElements(content, new ServiceCallback<List<DRGElement>>() { @Override public void onSuccess(final List<DRGElement> drgElements) { final List<DMNIncludedNode> nodes = drgElements .stream() .map(node -> includedModelFactory.makeDMNIncludeNode(path, model, node)) .collect(Collectors.toList()); result.addAll(nodes); success.onInvoke(nodes); } @Override public void onError(final ClientRuntimeError error) { LOGGER.log(Level.SEVERE, error.getMessage()); fail.onInvoke(error); } }) )); } public void loadModels(final ServiceCallback<List<IncludedModel>> callback) { final List<IncludedModel> models = new ArrayList<>(); dmnImportsContentService.getModelsURIs() .then(items -> promises.all(Arrays.asList(items), file -> { final String fileName = FileUtils.getFileName(file); if (fileName.endsWith("." + DMNImportTypes.DMN.getFileExtension())) { return dmnImportsContentService.loadFile(file) .then(fileContent -> promises.create((success, failed) -> dmnImportsService.getWbDefinitions(fileContent, new ServiceCallback<Definitions>() { @Override public void onSuccess(final Definitions definitions) { final String modelPackage = ""; final String namespace = definitions.getNamespace().getValue(); final String importType = DMNImportTypes.DMN.getDefaultNamespace(); final int drgElementCount = definitions.getDrgElement().size(); final int itemDefinitionCount = definitions.getItemDefinition().size(); models.add(new DMNIncludedModel(fileName, modelPackage, fileName, namespace, importType, drgElementCount, itemDefinitionCount)); success.onInvoke(promises.resolve()); } @Override public void onError(final ClientRuntimeError error) { //Swallow. Since it must try to load other paths. success.onInvoke(promises.resolve()); } }))); } if (fileName.endsWith("." + DMNImportTypes.PMML.getFileExtension())) { return dmnImportsContentService.getPMMLDocumentMetadata(file) .then(pmmlDocumentMetadata -> { int modelCount = pmmlDocumentMetadata.getModels() != null ? pmmlDocumentMetadata.getModels().size() : 0; models.add(new PMMLIncludedModel(fileName, "", fileName, DMNImportTypes.PMML.getDefaultNamespace(), modelCount)); return promises.resolve(); }); } return promises.reject("Error: " + fileName + " is an invalid file. Only *.dmn and *.pmml are supported"); }).then(v -> { callback.onSuccess(models); return promises.resolve(); })); } private Promise<Void> loadDefinitionFromFile(final String file, final Map<String, JSITDefinitions> otherDefinitions) { return dmnImportsContentService.loadFile(file) .then(xml -> promises.create((success, failure) -> { if (!isEmpty(xml)) { final ServiceCallback<JSITDefinitions> callback = Js.uncheckedCast(getCallback(file, otherDefinitions, success)); dmnImportsService.getDMNDefinitions(xml, callback); } else { success.onInvoke(promises.resolve()); } })); } private ServiceCallback<Object> getCallback(final String filePath, final Map<String, JSITDefinitions> otherDefinitions, final Promise.PromiseExecutorCallbackFn.ResolveCallbackFn<Void> success) { return new ServiceCallback<Object>() { @Override public void onSuccess(final Object item) { final JSITDefinitions def = Js.uncheckedCast(item); otherDefinitions.put(filePath, def); success.onInvoke(promises.resolve()); } @Override public void onError(final ClientRuntimeError error) { LOGGER.log(Level.SEVERE, error.getMessage()); } }; } private Optional<JSITImport> findImportByDefinitions(final JSITDefinitions definitions, final List<JSITImport> imports) { for (int i = 0; i < imports.size(); i++) { final JSITImport anImport = Js.uncheckedCast(imports.get(i)); if (Objects.equals(anImport.getNamespace(), definitions.getNamespace())) { return Optional.of(anImport); } } return Optional.empty(); } private Optional<JSITImport> findImportByPMMLDocument(final String includedPMMLModelFile, final List<JSITImport> imports) { for (int i = 0; i < imports.size(); i++) { final JSITImport anImport = Js.uncheckedCast(imports.get(i)); if (Objects.equals(anImport.getLocationURI(), includedPMMLModelFile)) { return Optional.of(anImport); } } return Optional.empty(); } public Promise<Map<JSITImport, PMMLDocumentMetadata>> getPMMLDocumentsAsync(final Metadata metadata, final List<JSITImport> imports) { if (!imports.isEmpty()) { return loadPMMLDefinitions().then(otherDefinitions -> { final Map<JSITImport, PMMLDocumentMetadata> importDefinitions = new HashMap<>(); for (final Map.Entry<String, PMMLDocumentMetadata> entry : otherDefinitions.entrySet()) { final PMMLDocumentMetadata def = entry.getValue(); findImportByPMMLDocument(FileUtils.getFileName(def.getPath()), imports).ifPresent(anImport -> { final JSITImport foundImported = Js.uncheckedCast(anImport); importDefinitions.put(foundImported, def); }); } return promises.resolve(importDefinitions); }); } return promises.resolve(Collections.emptyMap()); } private Promise<Map<String, PMMLDocumentMetadata>> loadPMMLDefinitions() { return dmnImportsContentService.getModelsPMMLFilesURIs(). then(files -> { if (files.length == 0) { return promises.resolve(Collections.emptyMap()); } else { final Map<String, PMMLDocumentMetadata> definitions = new HashMap<>(); return promises.all(Arrays.asList(files), file -> loadPMMLDefinitionFromFile(file, definitions) .then(v -> promises.resolve(definitions))); } }); } private Promise<Void> loadPMMLDefinitionFromFile(final String file, final Map<String, PMMLDocumentMetadata> definitions) { return dmnImportsContentService.getPMMLDocumentMetadata(file) .then(pmmlDocumentMetadata -> { definitions.put(file, pmmlDocumentMetadata); return promises.resolve(); }); } @Override public Map<JSITImport, String> getImportXML(final Metadata metadata, final List<JSITImport> imports) { return Collections.emptyMap(); } @Override public List<JSITDRGElement> getImportedDRGElements(final Map<JSITImport, JSITDefinitions> importDefinitions) { final List<JSITDRGElement> importedNodes = new ArrayList<>(); for (final Map.Entry<JSITImport, JSITDefinitions> entry : importDefinitions.entrySet()) { final JSITImport anImport = Js.uncheckedCast(entry.getKey()); final JSITDefinitions definitions = Js.uncheckedCast(entry.getValue()); importedNodes.addAll(getDrgElementsWithNamespace(definitions, anImport)); } return importedNodes; } private List<JSITDRGElement> getDrgElementsWithNamespace(final JSITDefinitions definitions, final JSITImport anImport) { final List<JSITDRGElement> result = new ArrayList<>(); final List<JSITDRGElement> drgElements = definitions.getDrgElement(); for (int i = 0; i < drgElements.size(); i++) { final JSITDRGElement drgElement = Js.uncheckedCast(drgElements.get(i)); final JSITDRGElement element = Js.uncheckedCast(drgElementWithNamespace(drgElement, anImport)); result.add(element); } return result; } private JSITDRGElement drgElementWithNamespace(final JSITDRGElement drgElement, final JSITImport anImport) { final String namespace = anImport.getName(); final QName qname = QName.valueOf("Namespace"); final Map<QName, String> map = JSITDMNElement.getOtherAttributesMap(drgElement); map.put(qname, anImport.getNamespace()); drgElement.setOtherAttributes(map); drgElement.setName(namespace + "." + drgElement.getName()); updateInformationItem(namespace, drgElement); return drgElement; } private void updateInformationItem(final String namespace, final JSITDRGElement drgElement) { getInformationItem(drgElement).ifPresent(informationItem -> { final JSITInformationItem tInformationItem = new JSITInformationItem(); final String typeRef = informationItem.getTypeRef(); if (!isEmpty(typeRef) && !isBuiltInType(typeRef)) { tInformationItem.setTypeRef(namespace + "." + typeRef); setInformationItem(drgElement, tInformationItem); } }); } private void setInformationItem(final JSITDRGElement drgElement, final JSITInformationItem informationItem) { if (JSITDecision.instanceOf(drgElement)) { final JSITDecision decision = Js.uncheckedCast(drgElement); decision.setVariable(informationItem); } else if (JSITInputData.instanceOf(drgElement)) { final JSITInputData inputData = Js.uncheckedCast(drgElement); inputData.setVariable(informationItem); } else if (JSITInvocable.instanceOf(drgElement)) { final JSITInvocable invocable = Js.uncheckedCast(drgElement); invocable.setVariable(informationItem); } } private Optional<JSITInformationItem> getInformationItem(final JSITDRGElement drgElement) { final JSITInformationItem variable; if (JSITDecision.instanceOf(drgElement)) { final JSITDecision decision = Js.uncheckedCast(drgElement); variable = Js.uncheckedCast(decision.getVariable()); } else if (JSITInputData.instanceOf(drgElement)) { final JSITInputData inputData = Js.uncheckedCast(drgElement); variable = Js.uncheckedCast(inputData.getVariable()); } else if (JSITInvocable.instanceOf(drgElement)) { final JSITInvocable invocable = Js.uncheckedCast(drgElement); variable = Js.uncheckedCast(invocable.getVariable()); } else { return Optional.empty(); } return Optional.of(variable); } @Override public List<JSITItemDefinition> getImportedItemDefinitions(final Map<JSITImport, JSITDefinitions> importDefinitions) { final List<JSITItemDefinition> itemDefinitions = new ArrayList<>(); for (final Map.Entry<JSITImport, JSITDefinitions> entry : importDefinitions.entrySet()) { final JSITImport anImport = Js.uncheckedCast(entry.getKey()); final JSITDefinitions definitions = Js.uncheckedCast(entry.getValue()); final List<JSITItemDefinition> items = getItemDefinitionsWithNamespace(definitions, anImport); itemDefinitions.addAll(items); } return itemDefinitions; } private List<JSITItemDefinition> getItemDefinitionsWithNamespace(final JSITDefinitions definitions, final JSITImport anImport) { final List<JSITItemDefinition> itemDefinitions = definitions.getItemDefinition(); final String prefix = anImport.getName(); final List<JSITItemDefinition> result = new ArrayList<>(); for (int i = 0; i < itemDefinitions.size(); i++) { final JSITItemDefinition itemDefinition = Js.uncheckedCast(itemDefinitions.get(i)); final JSITItemDefinition item = Js.uncheckedCast(withNamespace(itemDefinition, prefix)); result.add(item); } return result; } public void getPMMLDocumentsMetadataFromFiles(final List<PMMLIncludedModel> includedModels, final ServiceCallback<List<PMMLDocumentMetadata>> callback) { if (includedModels == null || includedModels.isEmpty()) { callback.onSuccess(Collections.emptyList()); return; } loadPMMLDefinitions().then(allDefinitions -> { final Map<String, String> filesToNameMap = includedModels.stream().collect(Collectors.toMap(PMMLIncludedModel::getPath, PMMLIncludedModel::getModelName)); final List<PMMLDocumentMetadata> pmmlDocumentMetadata = allDefinitions.entrySet().stream() .filter(entry -> filesToNameMap.keySet().contains(FileUtils.getFileName(entry.getKey()))) .map(entry -> new PMMLDocumentMetadata(entry.getValue().getPath(), filesToNameMap.get(FileUtils.getFileName(entry.getKey())), entry.getValue().getImportType(), entry.getValue().getModels())) .collect(Collectors.toList()); pmmlDocumentMetadata.sort(Comparator.comparing(PMMLDocumentMetadata::getName)); callback.onSuccess(pmmlDocumentMetadata); return promises.resolve(); }); } public void getImportedItemDefinitionsByNamespaceAsync(final String modelName, final String namespace, final ServiceCallback<List<ItemDefinition>> callback) { loadDMNDefinitions().then(definitions -> { final List<ItemDefinition> result = new ArrayList<>(); for (final Map.Entry<String, JSITDefinitions> entry : definitions.entrySet()) { final JSITDefinitions definition = Js.uncheckedCast(entry.getValue()); if (Objects.equals(definition.getNamespace(), namespace)) { final List<JSITItemDefinition> items = definition.getItemDefinition(); for (int j = 0; j < items.size(); j++) { final JSITItemDefinition jsitItemDefinition = Js.uncheckedCast(items.get(j)); final ItemDefinition converted = ImportedItemDefinitionPropertyConverter.wbFromDMN(jsitItemDefinition, modelName); result.add(converted); } } } result.sort(Comparator.comparing(o -> o.getName().getValue())); callback.onSuccess(result); return promises.resolve(result); }); } }
apache-2.0
shyamalschandra/flex-sdk
modules/compiler/src/java/flex2/compiler/Assets.java
3635
/* * * 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 flex2.compiler; import flash.swf.tags.DefineTag; import flash.swf.tags.DefineFont; import flex2.compiler.io.VirtualFile; import java.util.*; import java.util.Map.Entry; /** * Value object used to contain a collection of AssetInfo objects. * @see flex2.compiler.AssetInfo * @see flex2.compiler.CompilationUnit */ public final class Assets { private Map<String, AssetInfo> assets; public void add(String className, AssetInfo assetInfo) { if (assets == null) { assets = new HashMap<String, AssetInfo>(4); } assets.put(className, assetInfo); } // FIXME - this is cheating, not sure what the best thing to do here is. // Used by CompilerSwcContext. public void add(String className, DefineTag tag) { if (assets == null) { assets = new HashMap<String, AssetInfo>(4); } assets.put(className, new AssetInfo(tag)); } public void addAll(Assets ass) { if (ass.assets == null) { return; } if (assets == null) { assets = new HashMap<String, AssetInfo>(4); } assets.putAll(ass.assets); } public int count() { return assets == null ? 0 : assets.size(); } public boolean contains(String className) { return assets == null ? false : assets.containsKey(className); } public AssetInfo get(String className) { return assets == null ? null : assets.get(className); } /** * This is used by the webtier compiler. */ public Iterator<Map.Entry<String, AssetInfo>> iterator() { return assets == null ? EMPTY_ITERATOR : assets.entrySet().iterator(); } public boolean isUpdated() { boolean result = false; if (assets != null) { for (AssetInfo assetInfo : assets.values()) { VirtualFile path = assetInfo.getPath(); // If the path is null, it's probably a system font // that doesn't get resolved by us, so just assume it // hasn't changed. if ((path != null) && (assetInfo.getCreationTime() != path.getLastModified())) { result = true; } } } return result; } public List<DefineFont> getFonts() { LinkedList<DefineFont> fonts = new LinkedList<DefineFont>(); if (assets != null) { for (AssetInfo assetInfo : assets.values()) { DefineTag defineTag = assetInfo.getDefineTag(); if (defineTag instanceof DefineFont) { fonts.add((DefineFont)defineTag); } } } return fonts; } public boolean exists(String name) { return assets != null && assets.containsValue(name); } public int size() { return assets == null ? 0 : assets.size(); } private static final Iterator<Entry<String, AssetInfo>> EMPTY_ITERATOR = new Iterator<Entry<String, AssetInfo>>() { public boolean hasNext() { return false; } public Entry<String, AssetInfo> next() { return null; } public void remove() { } }; }
apache-2.0
kurli/cocos2d-cordova-crosswalk-1
framework/src/org/apache/cordova/CordovaWebView.java
31273
/* 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.cordova; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import android.app.Activity; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; //import android.webkit.WebBackForwardList; //import android.webkit.WebHistoryItem; //import android.webkit.WebChromeClient; //import android.webkit.WebSettings; //import android.webkit.WebView; //import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebViewClient; import android.widget.FrameLayout; import org.xwalk.core.XWalkNavigationHistory; import org.xwalk.core.XWalkNavigationItem; import org.xwalk.core.XWalkPreferences; import org.xwalk.core.XWalkView; /* * This class is our web view. * * @see <a href="http://developer.android.com/guide/webapps/webview.html">WebView guide</a> * @see <a href="http://developer.android.com/reference/android/webkit/WebView.html">WebView</a> */ public class CordovaWebView extends XWalkView { public static final String TAG = "CordovaWebView"; public static final String CORDOVA_VERSION = "3.6.3"; private HashSet<Integer> boundKeyCodes = new HashSet<Integer>(); public PluginManager pluginManager; private boolean paused; private BroadcastReceiver receiver; /** Activities and other important classes **/ private CordovaInterface cordova; CordovaWebViewClient viewClient; private CordovaChromeClient chromeClient; // Flag to track that a loadUrl timeout occurred int loadUrlTimeout = 0; private long lastMenuEventTime = 0; CordovaBridge bridge; private CordovaResourceApi resourceApi; private Whitelist internalWhitelist; private Whitelist externalWhitelist; // The URL passed to loadUrl(), not necessarily the URL of the current page. String loadedUrl; private CordovaPreferences preferences; class ActivityResult { int request; int result; Intent incoming; public ActivityResult(int req, int res, Intent intent) { request = req; result = res; incoming = intent; } } static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER); public CordovaWebView(Context context) { this(context, null); } public CordovaWebView(Context context, AttributeSet attrs) { super(context, attrs); } @Deprecated public CordovaWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs); } @TargetApi(11) @Deprecated public CordovaWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) { super(context, attrs); } // Use two-phase init so that the control will work with XML layouts. public void init(CordovaInterface cordova, CordovaWebViewClient webViewClient, CordovaChromeClient webChromeClient, List<PluginEntry> pluginEntries, Whitelist internalWhitelist, Whitelist externalWhitelist, CordovaPreferences preferences) { if (this.cordova != null) { throw new IllegalStateException(); } this.cordova = cordova; this.viewClient = webViewClient; this.chromeClient = webChromeClient; this.internalWhitelist = internalWhitelist; this.externalWhitelist = externalWhitelist; this.preferences = preferences; // There are no super.setWebChromeClient and super.setWebViewClient function in Xwalk. // so align with Cordova upstream. // https://github.com/apache/cordova-android/commit/705991e5b037743e632934b3c6ee98976e18d3f8#diff-b97e89dfb7e195850e6e2d3b531487feR561 super.setResourceClient(webViewClient); super.setUIClient(webChromeClient); pluginManager = new PluginManager(this, this.cordova, pluginEntries); bridge = new CordovaBridge(pluginManager, new NativeToJsMessageQueue(this, cordova)); resourceApi = new CordovaResourceApi(this.getContext(), pluginManager); pluginManager.addService("App", "org.apache.cordova.App"); initWebViewSettings(); exposeJsInterface(); } @SuppressWarnings("deprecation") private void initIfNecessary() { if (pluginManager == null) { Log.w(TAG, "CordovaWebView.init() was not called. This will soon be required."); // Before the refactor to a two-phase init, the Context needed to implement CordovaInterface. CordovaInterface cdv = (CordovaInterface)getContext(); if (!Config.isInitialized()) { Config.init(cdv.getActivity()); } init(cdv, makeWebViewClient(cdv), makeWebChromeClient(cdv), Config.getPluginEntries(), Config.getWhitelist(), Config.getExternalWhitelist(), Config.getPreferences()); } } @SuppressLint("SetJavaScriptEnabled") @SuppressWarnings("deprecation") private void initWebViewSettings() { //this.setInitialScale(0); this.setVerticalScrollBarEnabled(false); // TODO: The Activity is the one that should call requestFocus(). if (shouldRequestFocusOnInit()) { this.requestFocusFromTouch(); } // Enable JavaScript //XWalkSettings settings = this.getSettings(); //if (settings == null) return; // wang16: covered by XWalkPreferences setting in static code. //settings.setJavaScriptEnabled(true); //settings.setJavaScriptCanOpenWindowsAutomatically(true); // nhu: N/A //settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); //We don't save any form data in the application // nhu: N/A //settings.setSaveFormData(false); //settings.setSavePassword(false); // wang16: covered by XWalkPreferences setting in static code. //settings.setAllowUniversalAccessFromFileURLs(true); // Enable database // We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16 String databasePath = getContext().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); //settings.setDatabaseEnabled(true); //TODO: bring it back when it's ready in the XWalk. //settings.setDatabasePath(databasePath); //Determine whether we're in debug or release mode, and turn on Debugging! ApplicationInfo appInfo = getContext().getApplicationContext().getApplicationInfo(); if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { enableRemoteDebugging(); } //settings.setGeolocationDatabasePath(databasePath); // Enable DOM storage // wang16: default value in xwalk is true. //settings.setDomStorageEnabled(true); // Enable built-in geolocation // wang16: default value in xwalk is true. //settings.setGeolocationEnabled(true); // Enable AppCache // Fix for CB-2282 // nhu: N/A //settings.setAppCacheMaxSize(5 * 1048576); // wang16: setAppCachePath is not implemented in xwalk indeed. //settings.setAppCachePath(pathToCache); // wang16: default value in xwalk is true. //settings.setAppCacheEnabled(true); } public CordovaChromeClient makeWebChromeClient(CordovaInterface cordova) { return new CordovaChromeClient(cordova, this); } public CordovaWebViewClient makeWebViewClient(CordovaInterface cordova) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { return new CordovaWebViewClient(cordova, this); } return new IceCreamCordovaWebViewClient(cordova, this); } public void enableRemoteDebugging() { XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true); } /** * Override this method to decide whether or not you need to request the * focus when your application start * * @return true unless this method is overriden to return a different value */ protected boolean shouldRequestFocusOnInit() { return true; } private void exposeJsInterface() { if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)) { Log.i(TAG, "Disabled addJavascriptInterface() bridge since Android version is old."); // Bug being that Java Strings do not get converted to JS strings automatically. // This isn't hard to work-around on the JS side, but it's easier to just // use the prompt bridge instead. return; } this.addJavascriptInterface(new ExposedJsApi(bridge), "_cordovaNative"); } /** * Set the WebViewClient. * There is no setWebViewClient in xwalk, so don't override setWebViewClient function * https://github.com/apache/cordova-android/commit/caeb86843ddca712b5bf1dfbdac9005edce98100 * * @param client */ public void setWebViewClient(CordovaWebViewClient client) { this.viewClient = client; super.setResourceClient(client); } /** * Set the WebChromeClient. * * @param client */ public void setWebChromeClient(CordovaChromeClient client) { this.chromeClient = client; super.setUIClient(client); } public CordovaChromeClient getWebChromeClient() { return this.chromeClient; } public Whitelist getWhitelist() { return this.internalWhitelist; } public Whitelist getExternalWhitelist() { return this.externalWhitelist; } /** * Load the url into the webview. * * @param url */ @Override public void load(String url, String content) { if (url.equals("about:blank") || url.startsWith("javascript:")) { this.loadUrlNow(url); } else { this.loadUrlIntoView(url); } } public void loadUrl(String url) { load(url, null); } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ @Deprecated public void loadUrl(final String url, int time) { if(url == null) { this.loadUrlIntoView(Config.getStartUrl()); } else { this.loadUrlIntoView(url); } } public void loadUrlIntoView(final String url) { loadUrlIntoView(url, true); } /** * Load the url into the webview. * * @param url */ public void loadUrlIntoView(final String url, boolean recreatePlugins) { LOG.d(TAG, ">>> loadUrl(" + url + ")"); initIfNecessary(); if (recreatePlugins) { this.loadedUrl = url; if (this.pluginManager != null) { this.pluginManager.init(); } } // Create a timeout timer for loadUrl final CordovaWebView me = this; final int currentLoadUrlTimeout = me.loadUrlTimeout; final int loadUrlTimeoutValue = Integer.parseInt(this.getProperty("LoadUrlTimeoutValue", "20000")); // Timeout error method final Runnable loadError = new Runnable() { public void run() { me.stopLoading(); LOG.e(TAG, "CordovaWebView: TIMEOUT ERROR!"); if (viewClient != null) { viewClient.onReceivedLoadError(me, -6, "The connection to the server was unsuccessful.", url); } } }; // Timeout timer method final Runnable timeoutCheck = new Runnable() { public void run() { try { synchronized (this) { wait(loadUrlTimeoutValue); } } catch (InterruptedException e) { e.printStackTrace(); } // If timeout, then stop loading and handle error if (me.loadUrlTimeout == currentLoadUrlTimeout) { me.cordova.getActivity().runOnUiThread(loadError); } } }; // Load url this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { cordova.getThreadPool().execute(timeoutCheck); me.loadUrlNow(url); } }); } /** * Load URL in webview. * * @param url */ void loadUrlNow(String url) { if (LOG.isLoggable(LOG.DEBUG) && !url.startsWith("javascript:")) { LOG.d(TAG, ">>> loadUrlNow()"); } if (url.startsWith("file://") || url.startsWith("javascript:") || internalWhitelist.isUrlWhiteListed(url)) { super.load(url, null); } } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ public void loadUrlIntoView(final String url, final int time) { // If not first page of app, then load immediately // Add support for browser history if we use it. if ((url.startsWith("javascript:")) || this.getNavigationHistory().canGoBack()) { } // If first page, then show splashscreen else { LOG.d(TAG, "loadUrlIntoView(%s, %d)", url, time); // Send message to show splashscreen now if desired this.postMessage("splashscreen", "show"); } // Load url this.loadUrlIntoView(url); } @Override public void stopLoading() { chromeClient.isCurrentlyLoading = false; super.stopLoading(); } public void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); //We should post a message that the scroll changed ScrollEvent myEvent = new ScrollEvent(l, t, oldl, oldt, this); this.postMessage("onScrollChanged", myEvent); } /** * Send JavaScript statement back to JavaScript. * Deprecated (https://issues.apache.org/jira/browse/CB-6851) * Instead of executing snippets of JS, you should use the exec bridge * to create a Java->JS communication channel. * To do this: * 1. Within plugin.xml (to have your JS run before deviceready): * <js-module><runs/></js-module> * 2. Within your .js (call exec on start-up): * require('cordova/channel').onCordovaReady.subscribe(function() { * require('cordova/exec')(win, null, 'Plugin', 'method', []); * function win(message) { * ... process message from java here ... * } * }); * 3. Within your .java: * PluginResult dataResult = new PluginResult(PluginResult.Status.OK, CODE); * dataResult.setKeepCallback(true); * savedCallbackContext.sendPluginResult(dataResult); */ @Deprecated public void sendJavascript(String statement) { this.bridge.getMessageQueue().addJavaScript(statement); } /** * Send a plugin result back to JavaScript. * (This is a convenience method) * * @param result * @param callbackId */ public void sendPluginResult(PluginResult result, String callbackId) { this.bridge.getMessageQueue().addPluginResult(result, callbackId); } /** * Send a message to all plugins. * * @param id The message id * @param data The message data */ public void postMessage(String id, Object data) { if (this.pluginManager != null) { this.pluginManager.postMessage(id, data); } } /** * Go to previous page in history. (We manage our own history) * * @return true if we went back, false if we are already at top */ public boolean backHistory() { // Check webview first to see if there is a history // This is needed to support curPage#diffLink, since they are added to appView's history, but not our history url array (JQMobile behavior) if (super.getNavigationHistory().canGoBack()) { super.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1); return true; } return false; } /** * Load the specified URL in the Cordova webview or a new browser instance. * * NOTE: If openExternal is false, only URLs listed in whitelist can be loaded. * * @param url The url to load. * @param openExternal Load url in browser instead of Cordova webview. * @param clearHistory Clear the history stack, so new page becomes top of history * @param params Parameters for new app */ public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.getNavigationHistory().clear(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || internalWhitelist.isUrlWhiteListed(url)) { // TODO: What about params? // Load new URL this.loadUrl(url); return; } // Load in default viewer if not LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL=" + url + ")"); } try { // Omitting the MIME type for file: URLs causes "No Activity found to handle Intent". // Adding the MIME type to http: URLs causes them to not be handled by the downloader. Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = Uri.parse(url); if ("file".equals(uri.getScheme())) { intent.setDataAndType(uri, resourceApi.getMimeType(uri)); } else { intent.setData(uri); } cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url " + url, e); } } /** * Get string property for activity. * * @param name * @param defaultValue * @return the String value for the named property */ public String getProperty(String name, String defaultValue) { Bundle bundle = this.cordova.getActivity().getIntent().getExtras(); if (bundle == null) { return defaultValue; } name = name.toLowerCase(Locale.getDefault()); Object p = bundle.get(name); if (p == null) { return defaultValue; } return p.toString(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(boundKeyCodes.contains(keyCode)) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { this.loadUrl("javascript:cordova.fireDocumentEvent('volumedownbutton');"); return true; } // If volumeup key else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { this.loadUrl("javascript:cordova.fireDocumentEvent('volumeupbutton');"); return true; } else { return super.onKeyDown(keyCode, event); } } else if(keyCode == KeyEvent.KEYCODE_BACK) { return !(this.startOfHistory()) || isButtonPlumbedToJs(KeyEvent.KEYCODE_BACK); } else if(keyCode == KeyEvent.KEYCODE_MENU) { //How did we get here? Is there a childView? View childView = this.getFocusedChild(); if(childView != null) { //Make sure we close the keyboard if it's present InputMethodManager imm = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(childView.getWindowToken(), 0); cordova.getActivity().openOptionsMenu(); return true; } else { return super.onKeyDown(keyCode, event); } } return super.onKeyDown(keyCode, event); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_UP) { return super.dispatchKeyEvent(event); } int keyCode = event.getKeyCode(); // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // A custom view is currently displayed (e.g. playing a video) if (this.hasEnteredFullscreen()) { this.leaveFullscreen(); return true; } else { // The webview is currently displayed // If back key is bound, then send event to JavaScript if (isButtonPlumbedToJs(KeyEvent.KEYCODE_BACK)) { this.loadUrl("javascript:cordova.fireDocumentEvent('backbutton');"); return true; } else { // If not bound // Go to previous page in webview if it is possible to go back if (this.backHistory()) { return true; } // If not, then invoke default behavior else { //this.activityState = ACTIVITY_EXITING; //return false; // If they hit back button when app is initializing, app should exit instead of hang until initialization (CB2-458) this.cordova.getActivity().finish(); return false; } } } } // Legacy else if (keyCode == KeyEvent.KEYCODE_MENU) { if (this.lastMenuEventTime < event.getEventTime()) { this.loadUrl("javascript:cordova.fireDocumentEvent('menubutton');"); } this.lastMenuEventTime = event.getEventTime(); return super.dispatchKeyEvent(event); } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.loadUrl("javascript:cordova.fireDocumentEvent('searchbutton');"); return true; } //Does webkit change this behavior? return super.dispatchKeyEvent(event); } public void setButtonPlumbedToJs(int keyCode, boolean override) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_BACK: // TODO: Why are search and menu buttons handled separately? if (override) { boundKeyCodes.add(keyCode); } else { boundKeyCodes.remove(keyCode); } return; default: throw new IllegalArgumentException("Unsupported keycode: " + keyCode); } } @Deprecated // Use setButtonPlumbedToJs() instead. public void bindButton(boolean override) { setButtonPlumbedToJs(KeyEvent.KEYCODE_BACK, override); } @Deprecated // Use setButtonPlumbedToJs() instead. public void bindButton(String button, boolean override) { if (button.compareTo("volumeup")==0) { setButtonPlumbedToJs(KeyEvent.KEYCODE_VOLUME_UP, override); } else if (button.compareTo("volumedown")==0) { setButtonPlumbedToJs(KeyEvent.KEYCODE_VOLUME_DOWN, override); } } @Deprecated // Use setButtonPlumbedToJs() instead. public void bindButton(int keyCode, boolean keyDown, boolean override) { setButtonPlumbedToJs(keyCode, override); } @Deprecated // Use isButtonPlumbedToJs public boolean isBackButtonBound() { return isButtonPlumbedToJs(KeyEvent.KEYCODE_BACK); } public boolean isButtonPlumbedToJs(int keyCode) { return boundKeyCodes.contains(keyCode); } @Override public void pauseTimers() { // This is called by XWalkViewInternal.onActivityStateChange(). // We don't want them paused by default though. } public void pauseTimersForReal() { super.pauseTimers(); } public void handlePause(boolean keepRunning) { LOG.d(TAG, "Handle the pause"); // Send pause event to JavaScript this.loadUrl("javascript:try{cordova.fireDocumentEvent('pause');}catch(e){console.log('exception firing pause event from native');};"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onPause(keepRunning); } // If app doesn't want to run in background if (!keepRunning) { // Pause JavaScript timers (including setInterval) this.pauseTimersForReal(); } paused = true; } public void handleResume(boolean keepRunning, boolean activityResultKeepRunning) { this.loadUrl("javascript:try{cordova.fireDocumentEvent('resume');}catch(e){console.log('exception firing resume event from native');};"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onResume(keepRunning); } // Resume JavaScript timers (including setInterval) this.resumeTimers(); paused = false; } public void handleDestroy() { // Send destroy event to JavaScript this.loadUrl("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};"); // Load blank page so that JavaScript onunload is called this.loadUrl("about:blank"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onDestroy(); } // unregister the receiver if (this.receiver != null) { try { getContext().unregisterReceiver(this.receiver); } catch (Exception e) { Log.e(TAG, "Error unregistering configuration receiver: " + e.getMessage(), e); } } this.onDestroy(); } @Override public boolean onNewIntent(Intent intent) { if (super.onNewIntent(intent)) return true; //Forward to plugins if (this.pluginManager != null) { this.pluginManager.onNewIntent(intent); } return false; } public boolean isPaused() { return paused; } @Deprecated // This never did anything. public boolean hadKeyEvent() { return false; } public void printBackForwardList() { XWalkNavigationHistory currentList = this.getNavigationHistory(); int currentSize = currentList.size(); for(int i = 0; i < currentSize; ++i) { XWalkNavigationItem item = currentList.getItemAt(i); String url = item.getUrl(); LOG.d(TAG, "The URL at index: " + Integer.toString(i) + " is " + url ); } } //Can Go Back is BROKEN! public boolean startOfHistory() { XWalkNavigationHistory currentList = this.getNavigationHistory(); XWalkNavigationItem item = currentList.getItemAt(0); if( item!=null){ // Null-fence in case they haven't called loadUrl yet (CB-2458) String url = item.getUrl(); String currentUrl = this.getUrl(); LOG.d(TAG, "The current URL is: " + currentUrl); LOG.d(TAG, "The URL at item 0 is: " + url); return currentUrl.equals(url); } return false; } @Override public boolean restoreState(Bundle savedInstanceState) { boolean result = super.restoreState(savedInstanceState); Log.d(TAG, "WebView restoration crew now restoring!"); //Initialize the plugin manager once more if (this.pluginManager != null) { this.pluginManager.init(); } return result; } @Deprecated // This never did anything public void storeResult(int requestCode, int resultCode, Intent intent) { } public CordovaResourceApi getResourceApi() { return resourceApi; } public CordovaPreferences getPreferences() { return preferences; } static { // XWalkPreferencesInternal.ENABLE_JAVASCRIPT XWalkPreferences.setValue("enable-javascript", true); // XWalkPreferencesInternal.JAVASCRIPT_CAN_OPEN_WINDOW XWalkPreferences.setValue("javascript-can-open-window", true); // XWalkPreferencesInternal.ALLOW_UNIVERSAL_ACCESS_FROM_FILE XWalkPreferences.setValue("allow-universal-access-from-file", true); // XWalkPreferencesInternal.SUPPORT_MULTIPLE_WINDOWS XWalkPreferences.setValue("support-multiple-windows", false); } }
apache-2.0
Darsstar/framework
uitest/src/main/java/com/vaadin/tests/components/grid/GridResizeAndScroll.java
2057
/* * Copyright 2000-2016 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.tests.components.grid; import java.util.stream.IntStream; import com.vaadin.server.VaadinRequest; import com.vaadin.tests.components.AbstractReindeerTestUI; import com.vaadin.tests.data.bean.Person; import com.vaadin.ui.Grid; import com.vaadin.ui.Grid.SelectionMode; import com.vaadin.ui.VerticalLayout; public class GridResizeAndScroll extends AbstractReindeerTestUI { @Override protected void setup(VaadinRequest request) { VerticalLayout content = new VerticalLayout(); addComponent(content); final Grid<Person> grid = new Grid<>(); content.setHeight("500px"); content.addComponent(grid); grid.addColumn(Person::getFirstName); grid.addColumn(Person::getLastName); grid.addColumn(Person::getEmail); grid.setItems(IntStream.range(0, 50).mapToObj(this::createPerson)); grid.setSizeFull(); grid.setSelectionMode(SelectionMode.MULTI); grid.addSelectionListener(event -> { if (event.getAllSelectedItems().isEmpty()) { grid.setHeight("100%"); } else { grid.setHeight("50%"); } }); } private Person createPerson(int index) { Person person = new Person(); person.setFirstName("cell " + index + " 0"); person.setLastName("cell " + index + " 1"); person.setEmail("cell " + index + " 2"); return person; } }
apache-2.0
christ66/stapler
core/src/main/java/org/kohsuke/stapler/EvaluationTrace.java
2624
/* * Copyright (c) 2004-2010, Kohsuke Kawaguchi * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.kohsuke.stapler; import java.util.List; import java.util.ArrayList; import java.io.PrintWriter; import static org.kohsuke.stapler.Stapler.escape; /** * Remebers the {@link Stapler#invoke(RequestImpl, ResponseImpl, Object)} * evaluation traces. * * @author Kohsuke Kawaguchi */ public class EvaluationTrace { private final List<String> traces = new ArrayList<String>(); public void trace(StaplerResponse rsp, String msg) { traces.add(msg); // Firefox Live HTTP header plugin cannot nicely render multiple headers // with the same name, so give each one unique name. rsp.addHeader(String.format("Stapler-Trace-%03d",traces.size()),msg.replace("\n","\\n").replace("\r","\\r")); } public void printHtml(PrintWriter w) { for (String trace : traces) w.println(escape(trace)); } public static EvaluationTrace get(StaplerRequest req) { EvaluationTrace et = (EvaluationTrace) req.getAttribute(KEY); if(et==null) req.setAttribute(KEY,et=new EvaluationTrace()); return et; } /** * Used for counting trace header. */ private static final String KEY = EvaluationTrace.class.getName(); }
bsd-2-clause
Noremac201/runelite
runescape-api/src/main/java/net/runelite/rs/api/RSKeyFocusListener.java
1618
/* * Copyright (c) 2018, Adam <Adam@sigterm.info> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.rs.api; import java.awt.event.FocusListener; import java.awt.event.KeyListener; import net.runelite.api.KeyFocusListener; public interface RSKeyFocusListener extends KeyListener, FocusListener, KeyFocusListener { }
bsd-2-clause
Alanyanbc/sharebook
src/com/external/activeandroid/ActiveAndroid.java
2129
package com.external.activeandroid; /* * Copyright (C) 2010 Michael Pardo * * 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. */ import android.app.Application; import android.database.sqlite.SQLiteDatabase; import com.external.activeandroid.util.Log; public final class ActiveAndroid { ////////////////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS ////////////////////////////////////////////////////////////////////////////////////// public synchronized static void initialize(Application application) { initialize(application, false); } public synchronized static void initialize(Application application, boolean loggingEnabled) { setLoggingEnabled(loggingEnabled); Cache.initialize(application); } public static void clearCache() { Cache.clear(); } public static void dispose() { Cache.dispose(); } public static void setLoggingEnabled(boolean enabled) { Log.setEnabled(enabled); } public synchronized static SQLiteDatabase getDatabase() { return Cache.openDatabase(); } public static void beginTransaction() { Cache.openDatabase().beginTransaction(); } public static void endTransaction() { Cache.openDatabase().endTransaction(); } public static void setTransactionSuccessful() { Cache.openDatabase().setTransactionSuccessful(); } public static boolean inTransaction() { return Cache.openDatabase().inTransaction(); } public static void execSQL(String sql) { Cache.openDatabase().execSQL(sql); } public static void execSQL(String sql, Object[] bindArgs) { Cache.openDatabase().execSQL(sql, bindArgs); } }
mit
Kiskae/SpongeAPI
src/main/java/org/spongepowered/api/data/manipulator/immutable/item/ImmutableStoredEnchantmentData.java
2400
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.data.manipulator.immutable.item; import org.spongepowered.api.data.manipulator.ImmutableDataManipulator; import org.spongepowered.api.data.manipulator.mutable.item.StoredEnchantmentData; import org.spongepowered.api.data.meta.ItemEnchantment; import org.spongepowered.api.data.value.immutable.ImmutableListValue; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.inventory.ItemStack; /** * An {@link ImmutableDataManipulator} handling "stored" * {@link ItemEnchantment}s. Usually, stored {@link ItemEnchantment}s can be * "transferred" to other {@link ItemStack}s. Examples include * {@link ItemTypes#ENCHANTED_BOOK}s storing enchantments to apply to weapons. */ public interface ImmutableStoredEnchantmentData extends ImmutableDataManipulator<ImmutableStoredEnchantmentData, StoredEnchantmentData> { /** * Gets the {@link ImmutableListValue} of {@link ItemEnchantment}s stored * such that it can be applied to an {@link ItemStack}. * * @return The immutable list value of item enchantments */ ImmutableListValue<ItemEnchantment> enchantments(); }
mit
Snickermicker/smarthome
bundles/core/org.eclipse.smarthome.core.test/src/test/java/org/eclipse/smarthome/core/internal/scheduler/DelegatedSchedulerTest.java
3140
/** * Copyright (c) 2014,2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.smarthome.core.internal.scheduler; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; import java.time.Duration; import java.time.Instant; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiFunction; import org.eclipse.smarthome.core.scheduler.ScheduledCompletableFuture; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; /** * Test class for {@link DelegatedSchedulerImpl}. * * @author Hilbrand Bouwkamp - initial contribution */ public class DelegatedSchedulerTest { private DelegatedSchedulerImpl delegatedscheduler = new DelegatedSchedulerImpl(); @Mock private SchedulerImpl scheduler; @Mock private ScheduledCompletableFuture<Instant> temporalScheduledFuture; @Mock private CompletableFuture<Instant> completableFuture; @Before public void setUp() { initMocks(this); when(scheduler.after(any())).thenReturn(temporalScheduledFuture); when(temporalScheduledFuture.getPromise()).thenReturn(completableFuture); delegatedscheduler.setDelegate(scheduler); } @Test public void testAddAndDeactivate() throws InterruptedException, ExecutionException { final AtomicBoolean check = new AtomicBoolean(); when(completableFuture.handle(any())).thenAnswer(a -> null); doAnswer(a -> { check.set(true); return null; }).when(temporalScheduledFuture).cancel(true); delegatedscheduler.after(Duration.ofMillis(100)); assertFalse("Check if cancel was not called", check.get()); delegatedscheduler.deactivate(); assertTrue("Cancel should be called on deactivation", check.get()); } @Test public void testAddRemoveAndDeactivate() throws InterruptedException, ExecutionException { final AtomicBoolean check = new AtomicBoolean(); doAnswer(a -> { check.set(true); return null; }).when(temporalScheduledFuture).cancel(true); when(completableFuture.handle(any())).thenAnswer(a -> { ((BiFunction<?, ?, ?>) a.getArgument(0)).apply(null, null); return null; }); delegatedscheduler.after(Duration.ofMillis(100)); assertFalse("Check if cancel was not called", check.get()); delegatedscheduler.deactivate(); assertFalse("When job handled, cancel should not be called on deactivation. Because is job already gone.", check.get()); } }
epl-1.0
gazarenkov/che-sketch
core/che-core-api-core/src/main/java/org/eclipse/che/api/core/rest/shared/Links.java
2065
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.core.rest.shared; import org.eclipse.che.api.core.rest.shared.dto.Hyperlinks; import org.eclipse.che.api.core.rest.shared.dto.Link; import java.util.LinkedList; import java.util.List; /** * Helper class for working with links. * * @author andrew00x */ public class Links { /** * Find first link in the specified list by its relation. * * @param rel * link's relation * @param links * list of links * @return found link or {@code null} */ public static Link getLink(String rel, List<Link> links) { for (Link link : links) { if (rel.equals(link.getRel())) { return link; } } return null; } /** * Find all links in the specified list by its relation. * * @param rel * link's relation * @param links * list of links * @return found link or {@code null} */ public static List<Link> getLinks(String rel, List<Link> links) { final List<Link> result = new LinkedList<>(); for (Link link : links) { if (rel.equals(link.getRel())) { result.add(link); } } return result; } public static Link getLink(Hyperlinks links, String rel) { return getLink(rel, links.getLinks()); } public static List<Link> getLinks(Hyperlinks links, String rel) { return getLinks(rel, links.getLinks()); } private Links() { } }
epl-1.0
jtux270/translate
ovirt/3.6_source/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/builders/BaseSyncBuilder.java
848
package org.ovirt.engine.ui.uicommonweb.builders; /** * Base synchronous implementation of the {@link Builder}. It takes care of the boilerplate invocation of the rest and lets it's descendants * to only take care of copying parameters. * <p> * Use this only when the the descendant class does not do any async call. Otherwise implement the {@link Builder} directly */ public abstract class BaseSyncBuilder<S, D> implements SyncBuilder<S, D> { @Override public void build(S source, D destination, BuilderList<S, D> rest) { build(source, destination); rest.head().build(source, destination, rest.tail()); } /** * Builds the backend model from frontend the one * * @param frontend source * @param backend destination */ protected abstract void build(S source, D destination); }
gpl-3.0
jtux270/translate
ovirt/3.6_source/backend/manager/modules/vdsbroker/src/test/java/org/ovirt/engine/core/vdsbroker/NetworkImplementationDetailsUtilsTestForBaseNic.java
1183
package org.ovirt.engine.core.vdsbroker; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface; @RunWith(MockitoJUnitRunner.class) public class NetworkImplementationDetailsUtilsTestForBaseNic extends BaseNetworkImplementationDetailsUtilsTest { @Override @Before public void setUpBefore() throws Exception { super.setUpBefore(); VdsNetworkInterface baseIface = createBaseInterface(qosA, networkName); testIface = baseIface; when(calculateBaseNic.getBaseNic(baseIface)).thenReturn(baseIface); } @Test public void calculateNetworkImplementationDetailsNetworkVlanOutOfSyncNicAndNicHasNoVlanId() throws Exception { Network network = createNetwork(testIface.isBridged(), testIface.getMtu(), testIface.getVlanId()); testIface.setVlanId(null); calculateNetworkImplementationDetailsAndAssertSync(testIface, false, qosA, network); } }
gpl-3.0
BTCTaras/Essentials
Essentials/src/com/earth2me/essentials/commands/Commandunban.java
1550
package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; import com.earth2me.essentials.User; import org.bukkit.BanList; import org.bukkit.OfflinePlayer; import org.bukkit.Server; import java.util.logging.Level; import static com.earth2me.essentials.I18n.tl; public class Commandunban extends EssentialsCommand { public Commandunban() { super("unban"); } @Override public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } String name; try { final User user = getPlayer(server, args, 0, true, true); name = user.getName(); ess.getServer().getBanList(BanList.Type.NAME).pardon(name); } catch (NoSuchFieldException e) { final OfflinePlayer player = server.getOfflinePlayer(args[0]); name = player.getName(); if (!player.isBanned()) { throw new Exception(tl("playerNotFound"), e); } ess.getServer().getBanList(BanList.Type.NAME).pardon(name); } final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; server.getLogger().log(Level.INFO, tl("playerUnbanned", senderName, name)); ess.broadcastMessage("essentials.ban.notify", tl("playerUnbanned", senderName, name)); } }
gpl-3.0
sebastianpacheco/jPOS
jpos/src/test/java/org/jpos/iso/SslChannelIntegrationTest.java
6469
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2015 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.iso; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.fail; import java.io.EOFException; import java.io.IOException; import java.util.Properties; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.jpos.core.Configuration; import org.jpos.core.SimpleConfiguration; import org.jpos.iso.channel.XMLChannel; import org.jpos.iso.packager.XMLPackager; import org.jpos.util.Logger; import org.jpos.util.SimpleLogListener; import org.jpos.util.ThreadPool; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * $Revision$ * $Date$ * $Author$ */ public class SslChannelIntegrationTest { private static final int PORT = 4000; private Logger logger; @Before public void setUp() throws Exception { logger = new Logger(); logger.addListener(new SimpleLogListener()); } @Test public void serverSideDisconnect() throws Exception { ISOServer isoServer = newIsoServer(); new Thread(isoServer).start(); XMLChannel clientChannel = newClientChannel(); clientChannel.connect(); // need to push some traffic through to complete the SSL handshake clientChannel.send(new ISOMsg("0800")); assertThat(clientChannel.receive(), hasMti("0810")); isoServer.shutdown(); try { clientChannel.receive(); fail("clientChannel should be closed"); } catch (Exception e) { assertThat(e, is(instanceOf(EOFException.class))); } } private XMLChannel newClientChannel() throws IOException, ISOException { XMLChannel clientChannel = new XMLChannel(new XMLPackager()); clientChannel.setSocketFactory(new SunJSSESocketFactory()); clientChannel.setConfiguration(clientConfiguration()); clientChannel.setLogger(logger, "client.channel"); clientChannel.setHost("localhost", PORT); return clientChannel; } private ISOServer newIsoServer() throws IOException, ISOException { XMLChannel clientSide = new XMLChannel(new XMLPackager()); clientSide.setLogger(logger, "server.channel"); ISOServer isoServer = new ISOServer(PORT, clientSide, new ThreadPool()); isoServer.setSocketFactory(new SunJSSESocketFactory()); isoServer.setConfiguration(serverConfiguration()); isoServer.setLogger(logger, "server"); isoServer.addISORequestListener(new TestListener()); return isoServer; } // keystore.jks created using the following command in a shell: // // [user@hostname]$ keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password // What is your first and last name? // [Unknown]: localhost // What is the name of your organizational unit? // [Unknown]: Dummy // What is the name of your organization? // [Unknown]: Dummy // What is the name of your City or Locality? // [Unknown]: Somewhere // What is the name of your State or Province? // [Unknown]: Somewhere // What is the two-letter country code for this unit? // [Unknown]: AU // Is CN=localhost, OU=Dummy, O=Dummy, L=Somewhere, ST=Somewhere, C=AU correct? // [no]: yes // // Enter key password for <selfsigned> // (RETURN if same as keystore password): private Configuration serverConfiguration() { Properties props = new Properties(); props.put("keystore", "src/test/resources/keystore.jks"); props.put("storepassword", "password"); props.put("keypassword", "password"); props.put("addEnabledCipherSuite", "SSL_RSA_WITH_3DES_EDE_CBC_SHA"); return new SimpleConfiguration(props); } private Configuration clientConfiguration() { Properties props = new Properties(); props.put("keystore", "src/test/resources/keystore.jks"); props.put("serverauth", "false"); props.put("storepassword", "password"); props.put("keypassword", "password"); props.put("addEnabledCipherSuite", "SSL_RSA_WITH_3DES_EDE_CBC_SHA"); props.put("timeout", "1000"); props.put("connect-timeout", "1000"); return new SimpleConfiguration(props); } private class TestListener implements ISORequestListener { public boolean process(ISOSource source, ISOMsg m) { try { source.send(new ISOMsg("0810")); } catch (Exception e) { e.printStackTrace(); } return true; } } private Matcher<ISOMsg> hasMti(final String mti) { return new TypeSafeMatcher<ISOMsg>() { @Override public boolean matchesSafely(ISOMsg isoMsg) { return mti.equals(isoMsg.getString(0)); } public void describeTo(Description description) { description.appendText("ISOMsg with mti ").appendValue(mti); } }; } @BeforeClass public static void avoidNeedingToMoveTheMouseToMakeTheTestRunRepeatablyOnLinux() { // See http://bugs.sun.com/view_bug.do?bug_id=6202721 for why this is not just /dev/urandom // Without setting this property running tests repeatedly without moving the mouse will result in SSL sockets // not being created until the mouse is moved (at least on Linux creating SecureRandom does a blocking read // from /dev/random by default). System.setProperty("java.security.egd", "file:/dev/./urandom"); } }
agpl-3.0
rdkgit/opennms
opennms-dao-api/src/main/java/org/opennms/netmgt/dao/util/LogMessage.java
2333
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2002-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.dao.util; import org.opennms.netmgt.events.api.EventDatabaseConstants; import org.opennms.netmgt.xml.event.Logmsg; /** * This is an utility class used to format the event log message info - to be * inserted into the 'events' table * * @author <A HREF="mailto:weave@oculan.com">Brian Weaver </A> * @author <A HREF="http://www.opennms.org/">OpenNMS </A> * @author <A HREF="mailto:weave@oculan.com">Brian Weaver </A> * @author <A HREF="http://www.opennms.org/">OpenNMS </A> * @version $Id: $ */ public abstract class LogMessage { /** * Format the logmsg entry * * @param msg * the logmsg * @return the formatted logmsg */ public static String format(Logmsg msg) { String txt = EventDatabaseConstants.escape(msg.getContent(), EventDatabaseConstants.DB_ATTRIB_DELIM); String log = msg.getDest(); String fmsg = txt + EventDatabaseConstants.DB_ATTRIB_DELIM + log; if (fmsg.length() >= 256) fmsg = fmsg.substring(0, 252) + EventDatabaseConstants.VALUE_TRUNCATE_INDICATOR; return fmsg; } }
agpl-3.0
anishalex/youlog
oauthComponents/google-oauth-java-client-dev/google-oauth-client/src/main/java/com/google/api/client/auth/oauth/OAuthGetTemporaryToken.java
1862
/* * Copyright (c) 2010 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 com.google.api.client.auth.oauth; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Generic OAuth 1.0a URL to request a temporary credentials token (or "request token") from an * authorization server. * <p> * Use {@link #execute()} to execute the request. The temporary token acquired with this request is * found in {@link OAuthCredentialsResponse#token}. This temporary token is used in * {@link OAuthAuthorizeTemporaryTokenUrl#temporaryToken} to direct the end user to an authorization * page to allow the end user to authorize the temporary token. * * @since 1.0 * @author Yaniv Inbar */ @Beta public class OAuthGetTemporaryToken extends AbstractOAuthGetToken { /** * Optional absolute URI back to which the server will redirect the resource owner when the * Resource Owner Authorization step is completed or {@code null} for none. */ public String callback; /** * @param authorizationServerUrl encoded authorization server URL */ public OAuthGetTemporaryToken(String authorizationServerUrl) { super(authorizationServerUrl); } @Override public OAuthParameters createParameters() { OAuthParameters result = super.createParameters(); result.callback = callback; return result; } }
apache-2.0
riezkykenzie/Mizuu
app/src/main/java/com/miz/mizuu/ActorPhotos.java
2276
/* * Copyright (C) 2014 Michell Bak * * 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.miz.mizuu; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.MenuItem; import com.miz.base.MizActivity; import com.miz.functions.IntentKeys; import com.miz.mizuu.fragments.ActorPhotosFragment; import com.miz.utils.ViewUtils; public class ActorPhotos extends MizActivity { private static String TAG = "ActorPhotosFragment"; private int mToolbarColor; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String actorId = getIntent().getExtras().getString("actorId"); String actorName = getIntent().getExtras().getString("actorName"); mToolbarColor = getIntent().getExtras().getInt(IntentKeys.TOOLBAR_COLOR); getSupportActionBar().setSubtitle(actorName); Fragment frag = getSupportFragmentManager().findFragmentByTag(TAG); if (frag == null && savedInstanceState == null) { final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content, ActorPhotosFragment.newInstance(actorId), TAG); ft.commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onStart() { super.onStart(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ViewUtils.setToolbarAndStatusBarColor(getSupportActionBar(), getWindow(), mToolbarColor); } @Override protected int getLayoutResource() { return R.layout.empty_layout_with_toolbar; } }
apache-2.0
ppalaga/hawkular-metrics
core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/UUIDGen.java
12246
/* * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.hawkular.metrics.core.service; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.UUID; import com.google.common.annotations.VisibleForTesting; /** * This class is copied directly from org.apache.cassandra.utils.UUIDGen which is available in the * cassandra-clientutil artifact. It pulls in some additional runtime dependencies like Jackson 1.9 that we rather * avoid. * * @author jsanda */ public class UUIDGen { // A grand day! millis at 00:00:00.000 15 Oct 1582. private static final long START_EPOCH = -12219292800000L; private static final long clockSeqAndNode = makeClockSeqAndNode(); /* * The min and max possible lsb for a UUID. * Note that his is not 0 and all 1's because Cassandra TimeUUIDType * compares the lsb parts as a signed byte array comparison. So the min * value is 8 times -128 and the max is 8 times +127. * * Note that we ignore the uuid variant (namely, MIN_CLOCK_SEQ_AND_NODE * have variant 2 as it should, but MAX_CLOCK_SEQ_AND_NODE have variant 0). * I don't think that has any practical consequence and is more robust in * case someone provides a UUID with a broken variant. */ private static final long MIN_CLOCK_SEQ_AND_NODE = 0x8080808080808080L; private static final long MAX_CLOCK_SEQ_AND_NODE = 0x7f7f7f7f7f7f7f7fL; // placement of this singleton is important. It needs to be instantiated *AFTER* the other statics. private static final UUIDGen instance = new UUIDGen(); private long lastNanos; private UUIDGen() { // make sure someone didn't whack the clockSeqAndNode by changing the order of instantiation. if (clockSeqAndNode == 0) throw new RuntimeException("singleton instantiation is misplaced."); } /** * Creates a type 1 UUID (time-based UUID). * * @return a UUID instance */ public static UUID getTimeUUID() { return new UUID(instance.createTimeSafe(), clockSeqAndNode); } /** * Creates a type 1 UUID (time-based UUID) with the timestamp of @param when, in milliseconds. * * @return a UUID instance */ public static UUID getTimeUUID(long when) { return new UUID(createTime(fromUnixTimestamp(when)), clockSeqAndNode); } public static UUID getTimeUUIDFromMicros(long whenInMicros) { long whenInMillis = whenInMicros / 1000; long nanos = (whenInMicros - (whenInMillis * 1000)) * 10; return getTimeUUID(whenInMillis, nanos); } public static UUID getTimeUUID(long when, long nanos) { return new UUID(createTime(fromUnixTimestamp(when, nanos)), clockSeqAndNode); } @VisibleForTesting public static UUID getTimeUUID(long when, long nanos, long clockSeqAndNode) { return new UUID(createTime(fromUnixTimestamp(when, nanos)), clockSeqAndNode); } /** * creates a type 1 uuid from raw bytes. */ public static UUID getUUID(ByteBuffer raw) { return new UUID(raw.getLong(raw.position()), raw.getLong(raw.position() + 8)); } /** * decomposes a uuid into raw bytes. */ public static byte[] decompose(UUID uuid) { long most = uuid.getMostSignificantBits(); long least = uuid.getLeastSignificantBits(); byte[] b = new byte[16]; for (int i = 0; i < 8; i++) { b[i] = (byte) (most >>> ((7 - i) * 8)); b[8 + i] = (byte) (least >>> ((7 - i) * 8)); } return b; } /** * Returns a 16 byte representation of a type 1 UUID (a time-based UUID), * based on the current system time. * * @return a type 1 UUID represented as a byte[] */ public static byte[] getTimeUUIDBytes() { return createTimeUUIDBytes(instance.createTimeSafe()); } /** * Returns the smaller possible type 1 UUID having the provided timestamp. * <p> * <b>Warning:</b> this method should only be used for querying as this * doesn't at all guarantee the uniqueness of the resulting UUID. */ public static UUID minTimeUUID(long timestamp) { return new UUID(createTime(fromUnixTimestamp(timestamp)), MIN_CLOCK_SEQ_AND_NODE); } /** * Returns the biggest possible type 1 UUID having the provided timestamp. * <p> * <b>Warning:</b> this method should only be used for querying as this * doesn't at all guarantee the uniqueness of the resulting UUID. */ public static UUID maxTimeUUID(long timestamp) { // unix timestamp are milliseconds precision, uuid timestamp are 100's // nanoseconds precision. If we ask for the biggest uuid have unix // timestamp 1ms, then we should not extend 100's nanoseconds // precision by taking 10000, but rather 19999. long uuidTstamp = fromUnixTimestamp(timestamp + 1) - 1; return new UUID(createTime(uuidTstamp), MAX_CLOCK_SEQ_AND_NODE); } /** * @param uuid * @return milliseconds since Unix epoch */ public static long unixTimestamp(UUID uuid) { return (uuid.timestamp() / 10000) + START_EPOCH; } /** * @param uuid * @return microseconds since Unix epoch */ public static long microsTimestamp(UUID uuid) { return (uuid.timestamp() / 10) + START_EPOCH * 1000; } /** * @param timestamp milliseconds since Unix epoch * @return */ private static long fromUnixTimestamp(long timestamp) { return fromUnixTimestamp(timestamp, 0L); } private static long fromUnixTimestamp(long timestamp, long nanos) { return ((timestamp - START_EPOCH) * 10000) + nanos; } /** * Converts a 100-nanoseconds precision timestamp into the 16 byte representation * of a type 1 UUID (a time-based UUID). * <p> * To specify a 100-nanoseconds precision timestamp, one should provide a milliseconds timestamp and * a number 0 <= n < 10000 such that n*100 is the number of nanoseconds within that millisecond. * <p> * <p><i><b>Warning:</b> This method is not guaranteed to return unique UUIDs; Multiple * invocations using identical timestamps will result in identical UUIDs.</i></p> * * @return a type 1 UUID represented as a byte[] */ public static byte[] getTimeUUIDBytes(long timeMillis, int nanos) { if (nanos >= 10000) throw new IllegalArgumentException(); return createTimeUUIDBytes(instance.createTimeUnsafe(timeMillis, nanos)); } private static byte[] createTimeUUIDBytes(long msb) { long lsb = clockSeqAndNode; byte[] uuidBytes = new byte[16]; for (int i = 0; i < 8; i++) uuidBytes[i] = (byte) (msb >>> 8 * (7 - i)); for (int i = 8; i < 16; i++) uuidBytes[i] = (byte) (lsb >>> 8 * (7 - i)); return uuidBytes; } /** * Returns a milliseconds-since-epoch value for a type-1 UUID. * * @param uuid a type-1 (time-based) UUID * @return the number of milliseconds since the unix epoch * @throws IllegalArgumentException if the UUID is not version 1 */ public static long getAdjustedTimestamp(UUID uuid) { if (uuid.version() != 1) throw new IllegalArgumentException("incompatible with uuid version: " + uuid.version()); return (uuid.timestamp() / 10000) + START_EPOCH; } private static long makeClockSeqAndNode() { long clock = new Random(System.currentTimeMillis()).nextLong(); long lsb = 0; lsb |= 0x8000000000000000L; // variant (2 bits) lsb |= (clock & 0x0000000000003FFFL) << 48; // clock sequence (14 bits) lsb |= makeNode(); // 6 bytes return lsb; } // needs to return two different values for the same when. // we can generate at most 10k UUIDs per ms. private synchronized long createTimeSafe() { long nanosSince = (System.currentTimeMillis() - START_EPOCH) * 10000; if (nanosSince > lastNanos) lastNanos = nanosSince; else nanosSince = ++lastNanos; return createTime(nanosSince); } private long createTimeUnsafe(long when, int nanos) { long nanosSince = ((when - START_EPOCH) * 10000) + nanos; return createTime(nanosSince); } private static long createTime(long nanosSince) { long msb = 0L; msb |= (0x00000000ffffffffL & nanosSince) << 32; msb |= (0x0000ffff00000000L & nanosSince) >>> 16; msb |= (0xffff000000000000L & nanosSince) >>> 48; msb |= 0x0000000000001000L; // sets the version to 1. return msb; } private static long makeNode() { /* * We don't have access to the MAC address but need to generate a node part * that identify this host as uniquely as possible. * The spec says that one option is to take as many source that identify * this node as possible and hash them together. That's what we do here by * gathering all the ip of this host. * Note that FBUtilities.getBroadcastAddress() should be enough to uniquely * identify the node *in the cluster* but it triggers DatabaseDescriptor * instanciation and the UUID generator is used in Stress for instance, * where we don't want to require the yaml. */ Collection<InetAddress> localAddresses = getAllLocalAddresses(); if (localAddresses.isEmpty()) throw new RuntimeException( "Cannot generate the node component of the UUID because cannot retrieve any IP addresses."); // ideally, we'd use the MAC address, but java doesn't expose that. byte[] hash = hash(localAddresses); long node = 0; for (int i = 0; i < Math.min(6, hash.length); i++) node |= (0x00000000000000ff & (long) hash[i]) << (5 - i) * 8; assert (0xff00000000000000L & node) == 0; // Since we don't use the mac address, the spec says that multicast // bit (least significant bit of the first octet of the node ID) must be 1. return node | 0x0000010000000000L; } private static Collection<InetAddress> getAllLocalAddresses() { Set<InetAddress> localAddresses = new HashSet<InetAddress>(); try { Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); if (nets != null) { while (nets.hasMoreElements()) localAddresses.addAll(Collections.list(nets.nextElement().getInetAddresses())); } } catch (SocketException e) { throw new AssertionError(e); } return localAddresses; } private static byte[] hash(Collection<InetAddress> data) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); for (InetAddress addr : data) messageDigest.update(addr.getAddress()); return messageDigest.digest(); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("MD5 digest algorithm is not available", nsae); } } }
apache-2.0
etirelli/kie-wb-distributions
kie-wb-tests/kie-wb-tests-rest/src/test/java/org/kie/wb/test/rest/functional/Utils.java
1082
/* * Copyright 2018 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.wb.test.rest.functional; import java.util.ArrayList; import java.util.Collection; import org.guvnor.rest.client.ProjectResponse; public class Utils { public static Collection<String> getProjectNames(Collection<ProjectResponse> projects) { final ArrayList<String> result = new ArrayList<>(); for (ProjectResponse project : projects) { result.add(project.getName()); } return result; } }
apache-2.0
GabrielBrascher/cloudstack
core/src/main/java/com/cloud/agent/api/CheckNetworkAnswer.java
1434
// // 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.cloud.agent.api; public class CheckNetworkAnswer extends Answer { // indicate if agent reconnect is needed after setupNetworkNames command private boolean _reconnect; public CheckNetworkAnswer() { } public CheckNetworkAnswer(CheckNetworkCommand cmd, boolean result, String details, boolean reconnect) { super(cmd, result, details); _reconnect = reconnect; } public CheckNetworkAnswer(CheckNetworkCommand cmd, boolean result, String details) { this(cmd, result, details, false); } public boolean needReconnect() { return _reconnect; } }
apache-2.0
ShailShah/alluxio
core/common/src/main/java/alluxio/thrift/BlockMasterClientService.java
144761
/** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package alluxio.thrift; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) @Generated(value = "Autogenerated by Thrift Compiler (0.9.3)") public class BlockMasterClientService { /** * This interface contains block master service endpoints for Alluxio clients. */ public interface Iface extends alluxio.thrift.AlluxioService.Iface { /** * Returns the block information for the given block id. * * @param blockId the id of the block * * @param options the method options */ public GetBlockInfoTResponse getBlockInfo(long blockId, GetBlockInfoTOptions options) throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException; /** * Returns the capacity (in bytes). * * @param options the method options */ public GetCapacityBytesTResponse getCapacityBytes(GetCapacityBytesTOptions options) throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException; /** * Returns the used storage (in bytes). * * @param options the method options */ public GetUsedBytesTResponse getUsedBytes(GetUsedBytesTOptions options) throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException; /** * Returns a list of workers information. * * @param options the method options */ public GetWorkerInfoListTResponse getWorkerInfoList(GetWorkerInfoListTOptions options) throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException; } public interface AsyncIface extends alluxio.thrift.AlluxioService .AsyncIface { public void getBlockInfo(long blockId, GetBlockInfoTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getCapacityBytes(GetCapacityBytesTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getUsedBytes(GetUsedBytesTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; public void getWorkerInfoList(GetWorkerInfoListTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; } public static class Client extends alluxio.thrift.AlluxioService.Client implements Iface { public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> { public Factory() {} public Client getClient(org.apache.thrift.protocol.TProtocol prot) { return new Client(prot); } public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { return new Client(iprot, oprot); } } public Client(org.apache.thrift.protocol.TProtocol prot) { super(prot, prot); } public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { super(iprot, oprot); } public GetBlockInfoTResponse getBlockInfo(long blockId, GetBlockInfoTOptions options) throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { send_getBlockInfo(blockId, options); return recv_getBlockInfo(); } public void send_getBlockInfo(long blockId, GetBlockInfoTOptions options) throws org.apache.thrift.TException { getBlockInfo_args args = new getBlockInfo_args(); args.setBlockId(blockId); args.setOptions(options); sendBase("getBlockInfo", args); } public GetBlockInfoTResponse recv_getBlockInfo() throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { getBlockInfo_result result = new getBlockInfo_result(); receiveBase(result, "getBlockInfo"); if (result.isSetSuccess()) { return result.success; } if (result.e != null) { throw result.e; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getBlockInfo failed: unknown result"); } public GetCapacityBytesTResponse getCapacityBytes(GetCapacityBytesTOptions options) throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { send_getCapacityBytes(options); return recv_getCapacityBytes(); } public void send_getCapacityBytes(GetCapacityBytesTOptions options) throws org.apache.thrift.TException { getCapacityBytes_args args = new getCapacityBytes_args(); args.setOptions(options); sendBase("getCapacityBytes", args); } public GetCapacityBytesTResponse recv_getCapacityBytes() throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { getCapacityBytes_result result = new getCapacityBytes_result(); receiveBase(result, "getCapacityBytes"); if (result.isSetSuccess()) { return result.success; } if (result.e != null) { throw result.e; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getCapacityBytes failed: unknown result"); } public GetUsedBytesTResponse getUsedBytes(GetUsedBytesTOptions options) throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { send_getUsedBytes(options); return recv_getUsedBytes(); } public void send_getUsedBytes(GetUsedBytesTOptions options) throws org.apache.thrift.TException { getUsedBytes_args args = new getUsedBytes_args(); args.setOptions(options); sendBase("getUsedBytes", args); } public GetUsedBytesTResponse recv_getUsedBytes() throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { getUsedBytes_result result = new getUsedBytes_result(); receiveBase(result, "getUsedBytes"); if (result.isSetSuccess()) { return result.success; } if (result.e != null) { throw result.e; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getUsedBytes failed: unknown result"); } public GetWorkerInfoListTResponse getWorkerInfoList(GetWorkerInfoListTOptions options) throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { send_getWorkerInfoList(options); return recv_getWorkerInfoList(); } public void send_getWorkerInfoList(GetWorkerInfoListTOptions options) throws org.apache.thrift.TException { getWorkerInfoList_args args = new getWorkerInfoList_args(); args.setOptions(options); sendBase("getWorkerInfoList", args); } public GetWorkerInfoListTResponse recv_getWorkerInfoList() throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { getWorkerInfoList_result result = new getWorkerInfoList_result(); receiveBase(result, "getWorkerInfoList"); if (result.isSetSuccess()) { return result.success; } if (result.e != null) { throw result.e; } throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getWorkerInfoList failed: unknown result"); } } public static class AsyncClient extends alluxio.thrift.AlluxioService.AsyncClient implements AsyncIface { public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> { private org.apache.thrift.async.TAsyncClientManager clientManager; private org.apache.thrift.protocol.TProtocolFactory protocolFactory; public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { this.clientManager = clientManager; this.protocolFactory = protocolFactory; } public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { return new AsyncClient(protocolFactory, clientManager, transport); } } public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { super(protocolFactory, clientManager, transport); } public void getBlockInfo(long blockId, GetBlockInfoTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getBlockInfo_call method_call = new getBlockInfo_call(blockId, options, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getBlockInfo_call extends org.apache.thrift.async.TAsyncMethodCall { private long blockId; private GetBlockInfoTOptions options; public getBlockInfo_call(long blockId, GetBlockInfoTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.blockId = blockId; this.options = options; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getBlockInfo", org.apache.thrift.protocol.TMessageType.CALL, 0)); getBlockInfo_args args = new getBlockInfo_args(); args.setBlockId(blockId); args.setOptions(options); args.write(prot); prot.writeMessageEnd(); } public GetBlockInfoTResponse getResult() throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getBlockInfo(); } } public void getCapacityBytes(GetCapacityBytesTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getCapacityBytes_call method_call = new getCapacityBytes_call(options, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getCapacityBytes_call extends org.apache.thrift.async.TAsyncMethodCall { private GetCapacityBytesTOptions options; public getCapacityBytes_call(GetCapacityBytesTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.options = options; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getCapacityBytes", org.apache.thrift.protocol.TMessageType.CALL, 0)); getCapacityBytes_args args = new getCapacityBytes_args(); args.setOptions(options); args.write(prot); prot.writeMessageEnd(); } public GetCapacityBytesTResponse getResult() throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getCapacityBytes(); } } public void getUsedBytes(GetUsedBytesTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getUsedBytes_call method_call = new getUsedBytes_call(options, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getUsedBytes_call extends org.apache.thrift.async.TAsyncMethodCall { private GetUsedBytesTOptions options; public getUsedBytes_call(GetUsedBytesTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.options = options; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getUsedBytes", org.apache.thrift.protocol.TMessageType.CALL, 0)); getUsedBytes_args args = new getUsedBytes_args(); args.setOptions(options); args.write(prot); prot.writeMessageEnd(); } public GetUsedBytesTResponse getResult() throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getUsedBytes(); } } public void getWorkerInfoList(GetWorkerInfoListTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { checkReady(); getWorkerInfoList_call method_call = new getWorkerInfoList_call(options, resultHandler, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class getWorkerInfoList_call extends org.apache.thrift.async.TAsyncMethodCall { private GetWorkerInfoListTOptions options; public getWorkerInfoList_call(GetWorkerInfoListTOptions options, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { super(client, protocolFactory, transport, resultHandler, false); this.options = options; } public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getWorkerInfoList", org.apache.thrift.protocol.TMessageType.CALL, 0)); getWorkerInfoList_args args = new getWorkerInfoList_args(); args.setOptions(options); args.write(prot); prot.writeMessageEnd(); } public GetWorkerInfoListTResponse getResult() throws alluxio.thrift.AlluxioTException, org.apache.thrift.TException { if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); return (new Client(prot)).recv_getWorkerInfoList(); } } } public static class Processor<I extends Iface> extends alluxio.thrift.AlluxioService.Processor<I> implements org.apache.thrift.TProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); public Processor(I iface) { super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>())); } protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) { super(iface, getProcessMap(processMap)); } private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) { processMap.put("getBlockInfo", new getBlockInfo()); processMap.put("getCapacityBytes", new getCapacityBytes()); processMap.put("getUsedBytes", new getUsedBytes()); processMap.put("getWorkerInfoList", new getWorkerInfoList()); return processMap; } public static class getBlockInfo<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getBlockInfo_args> { public getBlockInfo() { super("getBlockInfo"); } public getBlockInfo_args getEmptyArgsInstance() { return new getBlockInfo_args(); } protected boolean isOneway() { return false; } public getBlockInfo_result getResult(I iface, getBlockInfo_args args) throws org.apache.thrift.TException { getBlockInfo_result result = new getBlockInfo_result(); try { result.success = iface.getBlockInfo(args.blockId, args.options); } catch (alluxio.thrift.AlluxioTException e) { result.e = e; } return result; } } public static class getCapacityBytes<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getCapacityBytes_args> { public getCapacityBytes() { super("getCapacityBytes"); } public getCapacityBytes_args getEmptyArgsInstance() { return new getCapacityBytes_args(); } protected boolean isOneway() { return false; } public getCapacityBytes_result getResult(I iface, getCapacityBytes_args args) throws org.apache.thrift.TException { getCapacityBytes_result result = new getCapacityBytes_result(); try { result.success = iface.getCapacityBytes(args.options); } catch (alluxio.thrift.AlluxioTException e) { result.e = e; } return result; } } public static class getUsedBytes<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getUsedBytes_args> { public getUsedBytes() { super("getUsedBytes"); } public getUsedBytes_args getEmptyArgsInstance() { return new getUsedBytes_args(); } protected boolean isOneway() { return false; } public getUsedBytes_result getResult(I iface, getUsedBytes_args args) throws org.apache.thrift.TException { getUsedBytes_result result = new getUsedBytes_result(); try { result.success = iface.getUsedBytes(args.options); } catch (alluxio.thrift.AlluxioTException e) { result.e = e; } return result; } } public static class getWorkerInfoList<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getWorkerInfoList_args> { public getWorkerInfoList() { super("getWorkerInfoList"); } public getWorkerInfoList_args getEmptyArgsInstance() { return new getWorkerInfoList_args(); } protected boolean isOneway() { return false; } public getWorkerInfoList_result getResult(I iface, getWorkerInfoList_args args) throws org.apache.thrift.TException { getWorkerInfoList_result result = new getWorkerInfoList_result(); try { result.success = iface.getWorkerInfoList(args.options); } catch (alluxio.thrift.AlluxioTException e) { result.e = e; } return result; } } } public static class AsyncProcessor<I extends AsyncIface> extends alluxio.thrift.AlluxioService.AsyncProcessor<I> { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName()); public AsyncProcessor(I iface) { super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>())); } protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) { super(iface, getProcessMap(processMap)); } private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) { processMap.put("getBlockInfo", new getBlockInfo()); processMap.put("getCapacityBytes", new getCapacityBytes()); processMap.put("getUsedBytes", new getUsedBytes()); processMap.put("getWorkerInfoList", new getWorkerInfoList()); return processMap; } public static class getBlockInfo<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getBlockInfo_args, GetBlockInfoTResponse> { public getBlockInfo() { super("getBlockInfo"); } public getBlockInfo_args getEmptyArgsInstance() { return new getBlockInfo_args(); } public AsyncMethodCallback<GetBlockInfoTResponse> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback<GetBlockInfoTResponse>() { public void onComplete(GetBlockInfoTResponse o) { getBlockInfo_result result = new getBlockInfo_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getBlockInfo_result result = new getBlockInfo_result(); if (e instanceof alluxio.thrift.AlluxioTException) { result.e = (alluxio.thrift.AlluxioTException) e; result.setEIsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getBlockInfo_args args, org.apache.thrift.async.AsyncMethodCallback<GetBlockInfoTResponse> resultHandler) throws TException { iface.getBlockInfo(args.blockId, args.options,resultHandler); } } public static class getCapacityBytes<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getCapacityBytes_args, GetCapacityBytesTResponse> { public getCapacityBytes() { super("getCapacityBytes"); } public getCapacityBytes_args getEmptyArgsInstance() { return new getCapacityBytes_args(); } public AsyncMethodCallback<GetCapacityBytesTResponse> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback<GetCapacityBytesTResponse>() { public void onComplete(GetCapacityBytesTResponse o) { getCapacityBytes_result result = new getCapacityBytes_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getCapacityBytes_result result = new getCapacityBytes_result(); if (e instanceof alluxio.thrift.AlluxioTException) { result.e = (alluxio.thrift.AlluxioTException) e; result.setEIsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getCapacityBytes_args args, org.apache.thrift.async.AsyncMethodCallback<GetCapacityBytesTResponse> resultHandler) throws TException { iface.getCapacityBytes(args.options,resultHandler); } } public static class getUsedBytes<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getUsedBytes_args, GetUsedBytesTResponse> { public getUsedBytes() { super("getUsedBytes"); } public getUsedBytes_args getEmptyArgsInstance() { return new getUsedBytes_args(); } public AsyncMethodCallback<GetUsedBytesTResponse> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback<GetUsedBytesTResponse>() { public void onComplete(GetUsedBytesTResponse o) { getUsedBytes_result result = new getUsedBytes_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getUsedBytes_result result = new getUsedBytes_result(); if (e instanceof alluxio.thrift.AlluxioTException) { result.e = (alluxio.thrift.AlluxioTException) e; result.setEIsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getUsedBytes_args args, org.apache.thrift.async.AsyncMethodCallback<GetUsedBytesTResponse> resultHandler) throws TException { iface.getUsedBytes(args.options,resultHandler); } } public static class getWorkerInfoList<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getWorkerInfoList_args, GetWorkerInfoListTResponse> { public getWorkerInfoList() { super("getWorkerInfoList"); } public getWorkerInfoList_args getEmptyArgsInstance() { return new getWorkerInfoList_args(); } public AsyncMethodCallback<GetWorkerInfoListTResponse> getResultHandler(final AsyncFrameBuffer fb, final int seqid) { final org.apache.thrift.AsyncProcessFunction fcall = this; return new AsyncMethodCallback<GetWorkerInfoListTResponse>() { public void onComplete(GetWorkerInfoListTResponse o) { getWorkerInfoList_result result = new getWorkerInfoList_result(); result.success = o; try { fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); return; } catch (Exception e) { LOGGER.error("Exception writing to internal frame buffer", e); } fb.close(); } public void onError(Exception e) { byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; org.apache.thrift.TBase msg; getWorkerInfoList_result result = new getWorkerInfoList_result(); if (e instanceof alluxio.thrift.AlluxioTException) { result.e = (alluxio.thrift.AlluxioTException) e; result.setEIsSet(true); msg = result; } else { msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); } try { fcall.sendResponse(fb,msg,msgType,seqid); return; } catch (Exception ex) { LOGGER.error("Exception writing to internal frame buffer", ex); } fb.close(); } }; } protected boolean isOneway() { return false; } public void start(I iface, getWorkerInfoList_args args, org.apache.thrift.async.AsyncMethodCallback<GetWorkerInfoListTResponse> resultHandler) throws TException { iface.getWorkerInfoList(args.options,resultHandler); } } } public static class getBlockInfo_args implements org.apache.thrift.TBase<getBlockInfo_args, getBlockInfo_args._Fields>, java.io.Serializable, Cloneable, Comparable<getBlockInfo_args> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getBlockInfo_args"); private static final org.apache.thrift.protocol.TField BLOCK_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("blockId", org.apache.thrift.protocol.TType.I64, (short)1); private static final org.apache.thrift.protocol.TField OPTIONS_FIELD_DESC = new org.apache.thrift.protocol.TField("options", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getBlockInfo_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getBlockInfo_argsTupleSchemeFactory()); } private long blockId; // required private GetBlockInfoTOptions options; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { /** * the id of the block */ BLOCK_ID((short)1, "blockId"), /** * the method options */ OPTIONS((short)2, "options"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // BLOCK_ID return BLOCK_ID; case 2: // OPTIONS return OPTIONS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __BLOCKID_ISSET_ID = 0; private byte __isset_bitfield = 0; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.BLOCK_ID, new org.apache.thrift.meta_data.FieldMetaData("blockId", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); tmpMap.put(_Fields.OPTIONS, new org.apache.thrift.meta_data.FieldMetaData("options", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetBlockInfoTOptions.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getBlockInfo_args.class, metaDataMap); } public getBlockInfo_args() { } public getBlockInfo_args( long blockId, GetBlockInfoTOptions options) { this(); this.blockId = blockId; setBlockIdIsSet(true); this.options = options; } /** * Performs a deep copy on <i>other</i>. */ public getBlockInfo_args(getBlockInfo_args other) { __isset_bitfield = other.__isset_bitfield; this.blockId = other.blockId; if (other.isSetOptions()) { this.options = new GetBlockInfoTOptions(other.options); } } public getBlockInfo_args deepCopy() { return new getBlockInfo_args(this); } @Override public void clear() { setBlockIdIsSet(false); this.blockId = 0; this.options = null; } /** * the id of the block */ public long getBlockId() { return this.blockId; } /** * the id of the block */ public getBlockInfo_args setBlockId(long blockId) { this.blockId = blockId; setBlockIdIsSet(true); return this; } public void unsetBlockId() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __BLOCKID_ISSET_ID); } /** Returns true if field blockId is set (has been assigned a value) and false otherwise */ public boolean isSetBlockId() { return EncodingUtils.testBit(__isset_bitfield, __BLOCKID_ISSET_ID); } public void setBlockIdIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __BLOCKID_ISSET_ID, value); } /** * the method options */ public GetBlockInfoTOptions getOptions() { return this.options; } /** * the method options */ public getBlockInfo_args setOptions(GetBlockInfoTOptions options) { this.options = options; return this; } public void unsetOptions() { this.options = null; } /** Returns true if field options is set (has been assigned a value) and false otherwise */ public boolean isSetOptions() { return this.options != null; } public void setOptionsIsSet(boolean value) { if (!value) { this.options = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case BLOCK_ID: if (value == null) { unsetBlockId(); } else { setBlockId((Long)value); } break; case OPTIONS: if (value == null) { unsetOptions(); } else { setOptions((GetBlockInfoTOptions)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case BLOCK_ID: return getBlockId(); case OPTIONS: return getOptions(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case BLOCK_ID: return isSetBlockId(); case OPTIONS: return isSetOptions(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getBlockInfo_args) return this.equals((getBlockInfo_args)that); return false; } public boolean equals(getBlockInfo_args that) { if (that == null) return false; boolean this_present_blockId = true; boolean that_present_blockId = true; if (this_present_blockId || that_present_blockId) { if (!(this_present_blockId && that_present_blockId)) return false; if (this.blockId != that.blockId) return false; } boolean this_present_options = true && this.isSetOptions(); boolean that_present_options = true && that.isSetOptions(); if (this_present_options || that_present_options) { if (!(this_present_options && that_present_options)) return false; if (!this.options.equals(that.options)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_blockId = true; list.add(present_blockId); if (present_blockId) list.add(blockId); boolean present_options = true && (isSetOptions()); list.add(present_options); if (present_options) list.add(options); return list.hashCode(); } @Override public int compareTo(getBlockInfo_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetBlockId()).compareTo(other.isSetBlockId()); if (lastComparison != 0) { return lastComparison; } if (isSetBlockId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.blockId, other.blockId); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetOptions()).compareTo(other.isSetOptions()); if (lastComparison != 0) { return lastComparison; } if (isSetOptions()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.options, other.options); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getBlockInfo_args("); boolean first = true; sb.append("blockId:"); sb.append(this.blockId); first = false; if (!first) sb.append(", "); sb.append("options:"); if (this.options == null) { sb.append("null"); } else { sb.append(this.options); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (options != null) { options.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getBlockInfo_argsStandardSchemeFactory implements SchemeFactory { public getBlockInfo_argsStandardScheme getScheme() { return new getBlockInfo_argsStandardScheme(); } } private static class getBlockInfo_argsStandardScheme extends StandardScheme<getBlockInfo_args> { public void read(org.apache.thrift.protocol.TProtocol iprot, getBlockInfo_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // BLOCK_ID if (schemeField.type == org.apache.thrift.protocol.TType.I64) { struct.blockId = iprot.readI64(); struct.setBlockIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // OPTIONS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.options = new GetBlockInfoTOptions(); struct.options.read(iprot); struct.setOptionsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getBlockInfo_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldBegin(BLOCK_ID_FIELD_DESC); oprot.writeI64(struct.blockId); oprot.writeFieldEnd(); if (struct.options != null) { oprot.writeFieldBegin(OPTIONS_FIELD_DESC); struct.options.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getBlockInfo_argsTupleSchemeFactory implements SchemeFactory { public getBlockInfo_argsTupleScheme getScheme() { return new getBlockInfo_argsTupleScheme(); } } private static class getBlockInfo_argsTupleScheme extends TupleScheme<getBlockInfo_args> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getBlockInfo_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetBlockId()) { optionals.set(0); } if (struct.isSetOptions()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetBlockId()) { oprot.writeI64(struct.blockId); } if (struct.isSetOptions()) { struct.options.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getBlockInfo_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.blockId = iprot.readI64(); struct.setBlockIdIsSet(true); } if (incoming.get(1)) { struct.options = new GetBlockInfoTOptions(); struct.options.read(iprot); struct.setOptionsIsSet(true); } } } } public static class getBlockInfo_result implements org.apache.thrift.TBase<getBlockInfo_result, getBlockInfo_result._Fields>, java.io.Serializable, Cloneable, Comparable<getBlockInfo_result> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getBlockInfo_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getBlockInfo_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getBlockInfo_resultTupleSchemeFactory()); } private GetBlockInfoTResponse success; // required private alluxio.thrift.AlluxioTException e; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), E((short)1, "e"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // E return E; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetBlockInfoTResponse.class))); tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getBlockInfo_result.class, metaDataMap); } public getBlockInfo_result() { } public getBlockInfo_result( GetBlockInfoTResponse success, alluxio.thrift.AlluxioTException e) { this(); this.success = success; this.e = e; } /** * Performs a deep copy on <i>other</i>. */ public getBlockInfo_result(getBlockInfo_result other) { if (other.isSetSuccess()) { this.success = new GetBlockInfoTResponse(other.success); } if (other.isSetE()) { this.e = new alluxio.thrift.AlluxioTException(other.e); } } public getBlockInfo_result deepCopy() { return new getBlockInfo_result(this); } @Override public void clear() { this.success = null; this.e = null; } public GetBlockInfoTResponse getSuccess() { return this.success; } public getBlockInfo_result setSuccess(GetBlockInfoTResponse success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public alluxio.thrift.AlluxioTException getE() { return this.e; } public getBlockInfo_result setE(alluxio.thrift.AlluxioTException e) { this.e = e; return this; } public void unsetE() { this.e = null; } /** Returns true if field e is set (has been assigned a value) and false otherwise */ public boolean isSetE() { return this.e != null; } public void setEIsSet(boolean value) { if (!value) { this.e = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((GetBlockInfoTResponse)value); } break; case E: if (value == null) { unsetE(); } else { setE((alluxio.thrift.AlluxioTException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case E: return getE(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case E: return isSetE(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getBlockInfo_result) return this.equals((getBlockInfo_result)that); return false; } public boolean equals(getBlockInfo_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_e = true && this.isSetE(); boolean that_present_e = true && that.isSetE(); if (this_present_e || that_present_e) { if (!(this_present_e && that_present_e)) return false; if (!this.e.equals(that.e)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_success = true && (isSetSuccess()); list.add(present_success); if (present_success) list.add(success); boolean present_e = true && (isSetE()); list.add(present_e); if (present_e) list.add(e); return list.hashCode(); } @Override public int compareTo(getBlockInfo_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetE()).compareTo(other.isSetE()); if (lastComparison != 0) { return lastComparison; } if (isSetE()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getBlockInfo_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("e:"); if (this.e == null) { sb.append("null"); } else { sb.append(this.e); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getBlockInfo_resultStandardSchemeFactory implements SchemeFactory { public getBlockInfo_resultStandardScheme getScheme() { return new getBlockInfo_resultStandardScheme(); } } private static class getBlockInfo_resultStandardScheme extends StandardScheme<getBlockInfo_result> { public void read(org.apache.thrift.protocol.TProtocol iprot, getBlockInfo_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new GetBlockInfoTResponse(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // E if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.e = new alluxio.thrift.AlluxioTException(); struct.e.read(iprot); struct.setEIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getBlockInfo_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.e != null) { oprot.writeFieldBegin(E_FIELD_DESC); struct.e.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getBlockInfo_resultTupleSchemeFactory implements SchemeFactory { public getBlockInfo_resultTupleScheme getScheme() { return new getBlockInfo_resultTupleScheme(); } } private static class getBlockInfo_resultTupleScheme extends TupleScheme<getBlockInfo_result> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getBlockInfo_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetE()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetE()) { struct.e.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getBlockInfo_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new GetBlockInfoTResponse(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.e = new alluxio.thrift.AlluxioTException(); struct.e.read(iprot); struct.setEIsSet(true); } } } } public static class getCapacityBytes_args implements org.apache.thrift.TBase<getCapacityBytes_args, getCapacityBytes_args._Fields>, java.io.Serializable, Cloneable, Comparable<getCapacityBytes_args> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getCapacityBytes_args"); private static final org.apache.thrift.protocol.TField OPTIONS_FIELD_DESC = new org.apache.thrift.protocol.TField("options", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getCapacityBytes_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getCapacityBytes_argsTupleSchemeFactory()); } private GetCapacityBytesTOptions options; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { /** * the method options */ OPTIONS((short)1, "options"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // OPTIONS return OPTIONS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.OPTIONS, new org.apache.thrift.meta_data.FieldMetaData("options", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetCapacityBytesTOptions.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getCapacityBytes_args.class, metaDataMap); } public getCapacityBytes_args() { } public getCapacityBytes_args( GetCapacityBytesTOptions options) { this(); this.options = options; } /** * Performs a deep copy on <i>other</i>. */ public getCapacityBytes_args(getCapacityBytes_args other) { if (other.isSetOptions()) { this.options = new GetCapacityBytesTOptions(other.options); } } public getCapacityBytes_args deepCopy() { return new getCapacityBytes_args(this); } @Override public void clear() { this.options = null; } /** * the method options */ public GetCapacityBytesTOptions getOptions() { return this.options; } /** * the method options */ public getCapacityBytes_args setOptions(GetCapacityBytesTOptions options) { this.options = options; return this; } public void unsetOptions() { this.options = null; } /** Returns true if field options is set (has been assigned a value) and false otherwise */ public boolean isSetOptions() { return this.options != null; } public void setOptionsIsSet(boolean value) { if (!value) { this.options = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case OPTIONS: if (value == null) { unsetOptions(); } else { setOptions((GetCapacityBytesTOptions)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case OPTIONS: return getOptions(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case OPTIONS: return isSetOptions(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getCapacityBytes_args) return this.equals((getCapacityBytes_args)that); return false; } public boolean equals(getCapacityBytes_args that) { if (that == null) return false; boolean this_present_options = true && this.isSetOptions(); boolean that_present_options = true && that.isSetOptions(); if (this_present_options || that_present_options) { if (!(this_present_options && that_present_options)) return false; if (!this.options.equals(that.options)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_options = true && (isSetOptions()); list.add(present_options); if (present_options) list.add(options); return list.hashCode(); } @Override public int compareTo(getCapacityBytes_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetOptions()).compareTo(other.isSetOptions()); if (lastComparison != 0) { return lastComparison; } if (isSetOptions()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.options, other.options); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getCapacityBytes_args("); boolean first = true; sb.append("options:"); if (this.options == null) { sb.append("null"); } else { sb.append(this.options); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (options != null) { options.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getCapacityBytes_argsStandardSchemeFactory implements SchemeFactory { public getCapacityBytes_argsStandardScheme getScheme() { return new getCapacityBytes_argsStandardScheme(); } } private static class getCapacityBytes_argsStandardScheme extends StandardScheme<getCapacityBytes_args> { public void read(org.apache.thrift.protocol.TProtocol iprot, getCapacityBytes_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // OPTIONS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.options = new GetCapacityBytesTOptions(); struct.options.read(iprot); struct.setOptionsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getCapacityBytes_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.options != null) { oprot.writeFieldBegin(OPTIONS_FIELD_DESC); struct.options.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getCapacityBytes_argsTupleSchemeFactory implements SchemeFactory { public getCapacityBytes_argsTupleScheme getScheme() { return new getCapacityBytes_argsTupleScheme(); } } private static class getCapacityBytes_argsTupleScheme extends TupleScheme<getCapacityBytes_args> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getCapacityBytes_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetOptions()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetOptions()) { struct.options.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getCapacityBytes_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.options = new GetCapacityBytesTOptions(); struct.options.read(iprot); struct.setOptionsIsSet(true); } } } } public static class getCapacityBytes_result implements org.apache.thrift.TBase<getCapacityBytes_result, getCapacityBytes_result._Fields>, java.io.Serializable, Cloneable, Comparable<getCapacityBytes_result> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getCapacityBytes_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getCapacityBytes_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getCapacityBytes_resultTupleSchemeFactory()); } private GetCapacityBytesTResponse success; // required private alluxio.thrift.AlluxioTException e; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), E((short)1, "e"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // E return E; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetCapacityBytesTResponse.class))); tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getCapacityBytes_result.class, metaDataMap); } public getCapacityBytes_result() { } public getCapacityBytes_result( GetCapacityBytesTResponse success, alluxio.thrift.AlluxioTException e) { this(); this.success = success; this.e = e; } /** * Performs a deep copy on <i>other</i>. */ public getCapacityBytes_result(getCapacityBytes_result other) { if (other.isSetSuccess()) { this.success = new GetCapacityBytesTResponse(other.success); } if (other.isSetE()) { this.e = new alluxio.thrift.AlluxioTException(other.e); } } public getCapacityBytes_result deepCopy() { return new getCapacityBytes_result(this); } @Override public void clear() { this.success = null; this.e = null; } public GetCapacityBytesTResponse getSuccess() { return this.success; } public getCapacityBytes_result setSuccess(GetCapacityBytesTResponse success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public alluxio.thrift.AlluxioTException getE() { return this.e; } public getCapacityBytes_result setE(alluxio.thrift.AlluxioTException e) { this.e = e; return this; } public void unsetE() { this.e = null; } /** Returns true if field e is set (has been assigned a value) and false otherwise */ public boolean isSetE() { return this.e != null; } public void setEIsSet(boolean value) { if (!value) { this.e = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((GetCapacityBytesTResponse)value); } break; case E: if (value == null) { unsetE(); } else { setE((alluxio.thrift.AlluxioTException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case E: return getE(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case E: return isSetE(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getCapacityBytes_result) return this.equals((getCapacityBytes_result)that); return false; } public boolean equals(getCapacityBytes_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_e = true && this.isSetE(); boolean that_present_e = true && that.isSetE(); if (this_present_e || that_present_e) { if (!(this_present_e && that_present_e)) return false; if (!this.e.equals(that.e)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_success = true && (isSetSuccess()); list.add(present_success); if (present_success) list.add(success); boolean present_e = true && (isSetE()); list.add(present_e); if (present_e) list.add(e); return list.hashCode(); } @Override public int compareTo(getCapacityBytes_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetE()).compareTo(other.isSetE()); if (lastComparison != 0) { return lastComparison; } if (isSetE()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getCapacityBytes_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("e:"); if (this.e == null) { sb.append("null"); } else { sb.append(this.e); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getCapacityBytes_resultStandardSchemeFactory implements SchemeFactory { public getCapacityBytes_resultStandardScheme getScheme() { return new getCapacityBytes_resultStandardScheme(); } } private static class getCapacityBytes_resultStandardScheme extends StandardScheme<getCapacityBytes_result> { public void read(org.apache.thrift.protocol.TProtocol iprot, getCapacityBytes_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new GetCapacityBytesTResponse(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // E if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.e = new alluxio.thrift.AlluxioTException(); struct.e.read(iprot); struct.setEIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getCapacityBytes_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.e != null) { oprot.writeFieldBegin(E_FIELD_DESC); struct.e.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getCapacityBytes_resultTupleSchemeFactory implements SchemeFactory { public getCapacityBytes_resultTupleScheme getScheme() { return new getCapacityBytes_resultTupleScheme(); } } private static class getCapacityBytes_resultTupleScheme extends TupleScheme<getCapacityBytes_result> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getCapacityBytes_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetE()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetE()) { struct.e.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getCapacityBytes_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new GetCapacityBytesTResponse(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.e = new alluxio.thrift.AlluxioTException(); struct.e.read(iprot); struct.setEIsSet(true); } } } } public static class getUsedBytes_args implements org.apache.thrift.TBase<getUsedBytes_args, getUsedBytes_args._Fields>, java.io.Serializable, Cloneable, Comparable<getUsedBytes_args> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getUsedBytes_args"); private static final org.apache.thrift.protocol.TField OPTIONS_FIELD_DESC = new org.apache.thrift.protocol.TField("options", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getUsedBytes_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getUsedBytes_argsTupleSchemeFactory()); } private GetUsedBytesTOptions options; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { /** * the method options */ OPTIONS((short)1, "options"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // OPTIONS return OPTIONS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.OPTIONS, new org.apache.thrift.meta_data.FieldMetaData("options", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetUsedBytesTOptions.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getUsedBytes_args.class, metaDataMap); } public getUsedBytes_args() { } public getUsedBytes_args( GetUsedBytesTOptions options) { this(); this.options = options; } /** * Performs a deep copy on <i>other</i>. */ public getUsedBytes_args(getUsedBytes_args other) { if (other.isSetOptions()) { this.options = new GetUsedBytesTOptions(other.options); } } public getUsedBytes_args deepCopy() { return new getUsedBytes_args(this); } @Override public void clear() { this.options = null; } /** * the method options */ public GetUsedBytesTOptions getOptions() { return this.options; } /** * the method options */ public getUsedBytes_args setOptions(GetUsedBytesTOptions options) { this.options = options; return this; } public void unsetOptions() { this.options = null; } /** Returns true if field options is set (has been assigned a value) and false otherwise */ public boolean isSetOptions() { return this.options != null; } public void setOptionsIsSet(boolean value) { if (!value) { this.options = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case OPTIONS: if (value == null) { unsetOptions(); } else { setOptions((GetUsedBytesTOptions)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case OPTIONS: return getOptions(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case OPTIONS: return isSetOptions(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getUsedBytes_args) return this.equals((getUsedBytes_args)that); return false; } public boolean equals(getUsedBytes_args that) { if (that == null) return false; boolean this_present_options = true && this.isSetOptions(); boolean that_present_options = true && that.isSetOptions(); if (this_present_options || that_present_options) { if (!(this_present_options && that_present_options)) return false; if (!this.options.equals(that.options)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_options = true && (isSetOptions()); list.add(present_options); if (present_options) list.add(options); return list.hashCode(); } @Override public int compareTo(getUsedBytes_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetOptions()).compareTo(other.isSetOptions()); if (lastComparison != 0) { return lastComparison; } if (isSetOptions()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.options, other.options); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getUsedBytes_args("); boolean first = true; sb.append("options:"); if (this.options == null) { sb.append("null"); } else { sb.append(this.options); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (options != null) { options.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getUsedBytes_argsStandardSchemeFactory implements SchemeFactory { public getUsedBytes_argsStandardScheme getScheme() { return new getUsedBytes_argsStandardScheme(); } } private static class getUsedBytes_argsStandardScheme extends StandardScheme<getUsedBytes_args> { public void read(org.apache.thrift.protocol.TProtocol iprot, getUsedBytes_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // OPTIONS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.options = new GetUsedBytesTOptions(); struct.options.read(iprot); struct.setOptionsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getUsedBytes_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.options != null) { oprot.writeFieldBegin(OPTIONS_FIELD_DESC); struct.options.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getUsedBytes_argsTupleSchemeFactory implements SchemeFactory { public getUsedBytes_argsTupleScheme getScheme() { return new getUsedBytes_argsTupleScheme(); } } private static class getUsedBytes_argsTupleScheme extends TupleScheme<getUsedBytes_args> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getUsedBytes_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetOptions()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetOptions()) { struct.options.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getUsedBytes_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.options = new GetUsedBytesTOptions(); struct.options.read(iprot); struct.setOptionsIsSet(true); } } } } public static class getUsedBytes_result implements org.apache.thrift.TBase<getUsedBytes_result, getUsedBytes_result._Fields>, java.io.Serializable, Cloneable, Comparable<getUsedBytes_result> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getUsedBytes_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getUsedBytes_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getUsedBytes_resultTupleSchemeFactory()); } private GetUsedBytesTResponse success; // required private alluxio.thrift.AlluxioTException e; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), E((short)1, "e"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // E return E; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetUsedBytesTResponse.class))); tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getUsedBytes_result.class, metaDataMap); } public getUsedBytes_result() { } public getUsedBytes_result( GetUsedBytesTResponse success, alluxio.thrift.AlluxioTException e) { this(); this.success = success; this.e = e; } /** * Performs a deep copy on <i>other</i>. */ public getUsedBytes_result(getUsedBytes_result other) { if (other.isSetSuccess()) { this.success = new GetUsedBytesTResponse(other.success); } if (other.isSetE()) { this.e = new alluxio.thrift.AlluxioTException(other.e); } } public getUsedBytes_result deepCopy() { return new getUsedBytes_result(this); } @Override public void clear() { this.success = null; this.e = null; } public GetUsedBytesTResponse getSuccess() { return this.success; } public getUsedBytes_result setSuccess(GetUsedBytesTResponse success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public alluxio.thrift.AlluxioTException getE() { return this.e; } public getUsedBytes_result setE(alluxio.thrift.AlluxioTException e) { this.e = e; return this; } public void unsetE() { this.e = null; } /** Returns true if field e is set (has been assigned a value) and false otherwise */ public boolean isSetE() { return this.e != null; } public void setEIsSet(boolean value) { if (!value) { this.e = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((GetUsedBytesTResponse)value); } break; case E: if (value == null) { unsetE(); } else { setE((alluxio.thrift.AlluxioTException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case E: return getE(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case E: return isSetE(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getUsedBytes_result) return this.equals((getUsedBytes_result)that); return false; } public boolean equals(getUsedBytes_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_e = true && this.isSetE(); boolean that_present_e = true && that.isSetE(); if (this_present_e || that_present_e) { if (!(this_present_e && that_present_e)) return false; if (!this.e.equals(that.e)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_success = true && (isSetSuccess()); list.add(present_success); if (present_success) list.add(success); boolean present_e = true && (isSetE()); list.add(present_e); if (present_e) list.add(e); return list.hashCode(); } @Override public int compareTo(getUsedBytes_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetE()).compareTo(other.isSetE()); if (lastComparison != 0) { return lastComparison; } if (isSetE()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getUsedBytes_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("e:"); if (this.e == null) { sb.append("null"); } else { sb.append(this.e); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getUsedBytes_resultStandardSchemeFactory implements SchemeFactory { public getUsedBytes_resultStandardScheme getScheme() { return new getUsedBytes_resultStandardScheme(); } } private static class getUsedBytes_resultStandardScheme extends StandardScheme<getUsedBytes_result> { public void read(org.apache.thrift.protocol.TProtocol iprot, getUsedBytes_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new GetUsedBytesTResponse(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // E if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.e = new alluxio.thrift.AlluxioTException(); struct.e.read(iprot); struct.setEIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getUsedBytes_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.e != null) { oprot.writeFieldBegin(E_FIELD_DESC); struct.e.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getUsedBytes_resultTupleSchemeFactory implements SchemeFactory { public getUsedBytes_resultTupleScheme getScheme() { return new getUsedBytes_resultTupleScheme(); } } private static class getUsedBytes_resultTupleScheme extends TupleScheme<getUsedBytes_result> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getUsedBytes_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetE()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetE()) { struct.e.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getUsedBytes_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new GetUsedBytesTResponse(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.e = new alluxio.thrift.AlluxioTException(); struct.e.read(iprot); struct.setEIsSet(true); } } } } public static class getWorkerInfoList_args implements org.apache.thrift.TBase<getWorkerInfoList_args, getWorkerInfoList_args._Fields>, java.io.Serializable, Cloneable, Comparable<getWorkerInfoList_args> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getWorkerInfoList_args"); private static final org.apache.thrift.protocol.TField OPTIONS_FIELD_DESC = new org.apache.thrift.protocol.TField("options", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getWorkerInfoList_argsStandardSchemeFactory()); schemes.put(TupleScheme.class, new getWorkerInfoList_argsTupleSchemeFactory()); } private GetWorkerInfoListTOptions options; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { /** * the method options */ OPTIONS((short)1, "options"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // OPTIONS return OPTIONS; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.OPTIONS, new org.apache.thrift.meta_data.FieldMetaData("options", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetWorkerInfoListTOptions.class))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getWorkerInfoList_args.class, metaDataMap); } public getWorkerInfoList_args() { } public getWorkerInfoList_args( GetWorkerInfoListTOptions options) { this(); this.options = options; } /** * Performs a deep copy on <i>other</i>. */ public getWorkerInfoList_args(getWorkerInfoList_args other) { if (other.isSetOptions()) { this.options = new GetWorkerInfoListTOptions(other.options); } } public getWorkerInfoList_args deepCopy() { return new getWorkerInfoList_args(this); } @Override public void clear() { this.options = null; } /** * the method options */ public GetWorkerInfoListTOptions getOptions() { return this.options; } /** * the method options */ public getWorkerInfoList_args setOptions(GetWorkerInfoListTOptions options) { this.options = options; return this; } public void unsetOptions() { this.options = null; } /** Returns true if field options is set (has been assigned a value) and false otherwise */ public boolean isSetOptions() { return this.options != null; } public void setOptionsIsSet(boolean value) { if (!value) { this.options = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case OPTIONS: if (value == null) { unsetOptions(); } else { setOptions((GetWorkerInfoListTOptions)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case OPTIONS: return getOptions(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case OPTIONS: return isSetOptions(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getWorkerInfoList_args) return this.equals((getWorkerInfoList_args)that); return false; } public boolean equals(getWorkerInfoList_args that) { if (that == null) return false; boolean this_present_options = true && this.isSetOptions(); boolean that_present_options = true && that.isSetOptions(); if (this_present_options || that_present_options) { if (!(this_present_options && that_present_options)) return false; if (!this.options.equals(that.options)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_options = true && (isSetOptions()); list.add(present_options); if (present_options) list.add(options); return list.hashCode(); } @Override public int compareTo(getWorkerInfoList_args other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetOptions()).compareTo(other.isSetOptions()); if (lastComparison != 0) { return lastComparison; } if (isSetOptions()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.options, other.options); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getWorkerInfoList_args("); boolean first = true; sb.append("options:"); if (this.options == null) { sb.append("null"); } else { sb.append(this.options); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (options != null) { options.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getWorkerInfoList_argsStandardSchemeFactory implements SchemeFactory { public getWorkerInfoList_argsStandardScheme getScheme() { return new getWorkerInfoList_argsStandardScheme(); } } private static class getWorkerInfoList_argsStandardScheme extends StandardScheme<getWorkerInfoList_args> { public void read(org.apache.thrift.protocol.TProtocol iprot, getWorkerInfoList_args struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // OPTIONS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.options = new GetWorkerInfoListTOptions(); struct.options.read(iprot); struct.setOptionsIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getWorkerInfoList_args struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.options != null) { oprot.writeFieldBegin(OPTIONS_FIELD_DESC); struct.options.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getWorkerInfoList_argsTupleSchemeFactory implements SchemeFactory { public getWorkerInfoList_argsTupleScheme getScheme() { return new getWorkerInfoList_argsTupleScheme(); } } private static class getWorkerInfoList_argsTupleScheme extends TupleScheme<getWorkerInfoList_args> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getWorkerInfoList_args struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetOptions()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetOptions()) { struct.options.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getWorkerInfoList_args struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.options = new GetWorkerInfoListTOptions(); struct.options.read(iprot); struct.setOptionsIsSet(true); } } } } public static class getWorkerInfoList_result implements org.apache.thrift.TBase<getWorkerInfoList_result, getWorkerInfoList_result._Fields>, java.io.Serializable, Cloneable, Comparable<getWorkerInfoList_result> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getWorkerInfoList_result"); private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0); private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new getWorkerInfoList_resultStandardSchemeFactory()); schemes.put(TupleScheme.class, new getWorkerInfoList_resultTupleSchemeFactory()); } private GetWorkerInfoListTResponse success; // required private alluxio.thrift.AlluxioTException e; // required /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { SUCCESS((short)0, "success"), E((short)1, "e"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 0: // SUCCESS return SUCCESS; case 1: // E return E; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, GetWorkerInfoListTResponse.class))); tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getWorkerInfoList_result.class, metaDataMap); } public getWorkerInfoList_result() { } public getWorkerInfoList_result( GetWorkerInfoListTResponse success, alluxio.thrift.AlluxioTException e) { this(); this.success = success; this.e = e; } /** * Performs a deep copy on <i>other</i>. */ public getWorkerInfoList_result(getWorkerInfoList_result other) { if (other.isSetSuccess()) { this.success = new GetWorkerInfoListTResponse(other.success); } if (other.isSetE()) { this.e = new alluxio.thrift.AlluxioTException(other.e); } } public getWorkerInfoList_result deepCopy() { return new getWorkerInfoList_result(this); } @Override public void clear() { this.success = null; this.e = null; } public GetWorkerInfoListTResponse getSuccess() { return this.success; } public getWorkerInfoList_result setSuccess(GetWorkerInfoListTResponse success) { this.success = success; return this; } public void unsetSuccess() { this.success = null; } /** Returns true if field success is set (has been assigned a value) and false otherwise */ public boolean isSetSuccess() { return this.success != null; } public void setSuccessIsSet(boolean value) { if (!value) { this.success = null; } } public alluxio.thrift.AlluxioTException getE() { return this.e; } public getWorkerInfoList_result setE(alluxio.thrift.AlluxioTException e) { this.e = e; return this; } public void unsetE() { this.e = null; } /** Returns true if field e is set (has been assigned a value) and false otherwise */ public boolean isSetE() { return this.e != null; } public void setEIsSet(boolean value) { if (!value) { this.e = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case SUCCESS: if (value == null) { unsetSuccess(); } else { setSuccess((GetWorkerInfoListTResponse)value); } break; case E: if (value == null) { unsetE(); } else { setE((alluxio.thrift.AlluxioTException)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case SUCCESS: return getSuccess(); case E: return getE(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case SUCCESS: return isSetSuccess(); case E: return isSetE(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof getWorkerInfoList_result) return this.equals((getWorkerInfoList_result)that); return false; } public boolean equals(getWorkerInfoList_result that) { if (that == null) return false; boolean this_present_success = true && this.isSetSuccess(); boolean that_present_success = true && that.isSetSuccess(); if (this_present_success || that_present_success) { if (!(this_present_success && that_present_success)) return false; if (!this.success.equals(that.success)) return false; } boolean this_present_e = true && this.isSetE(); boolean that_present_e = true && that.isSetE(); if (this_present_e || that_present_e) { if (!(this_present_e && that_present_e)) return false; if (!this.e.equals(that.e)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_success = true && (isSetSuccess()); list.add(present_success); if (present_success) list.add(success); boolean present_e = true && (isSetE()); list.add(present_e); if (present_e) list.add(e); return list.hashCode(); } @Override public int compareTo(getWorkerInfoList_result other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); if (lastComparison != 0) { return lastComparison; } if (isSetSuccess()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetE()).compareTo(other.isSetE()); if (lastComparison != 0) { return lastComparison; } if (isSetE()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("getWorkerInfoList_result("); boolean first = true; sb.append("success:"); if (this.success == null) { sb.append("null"); } else { sb.append(this.success); } first = false; if (!first) sb.append(", "); sb.append("e:"); if (this.e == null) { sb.append("null"); } else { sb.append(this.e); } first = false; sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity if (success != null) { success.validate(); } } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class getWorkerInfoList_resultStandardSchemeFactory implements SchemeFactory { public getWorkerInfoList_resultStandardScheme getScheme() { return new getWorkerInfoList_resultStandardScheme(); } } private static class getWorkerInfoList_resultStandardScheme extends StandardScheme<getWorkerInfoList_result> { public void read(org.apache.thrift.protocol.TProtocol iprot, getWorkerInfoList_result struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 0: // SUCCESS if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.success = new GetWorkerInfoListTResponse(); struct.success.read(iprot); struct.setSuccessIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 1: // E if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.e = new alluxio.thrift.AlluxioTException(); struct.e.read(iprot); struct.setEIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, getWorkerInfoList_result struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.success != null) { oprot.writeFieldBegin(SUCCESS_FIELD_DESC); struct.success.write(oprot); oprot.writeFieldEnd(); } if (struct.e != null) { oprot.writeFieldBegin(E_FIELD_DESC); struct.e.write(oprot); oprot.writeFieldEnd(); } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class getWorkerInfoList_resultTupleSchemeFactory implements SchemeFactory { public getWorkerInfoList_resultTupleScheme getScheme() { return new getWorkerInfoList_resultTupleScheme(); } } private static class getWorkerInfoList_resultTupleScheme extends TupleScheme<getWorkerInfoList_result> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, getWorkerInfoList_result struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetSuccess()) { optionals.set(0); } if (struct.isSetE()) { optionals.set(1); } oprot.writeBitSet(optionals, 2); if (struct.isSetSuccess()) { struct.success.write(oprot); } if (struct.isSetE()) { struct.e.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, getWorkerInfoList_result struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(2); if (incoming.get(0)) { struct.success = new GetWorkerInfoListTResponse(); struct.success.read(iprot); struct.setSuccessIsSet(true); } if (incoming.get(1)) { struct.e = new alluxio.thrift.AlluxioTException(); struct.e.read(iprot); struct.setEIsSet(true); } } } } }
apache-2.0
OpenConext/incubator-openaz-openconext
openaz-pep/src/test/java/org/apache/openaz/pepapi/std/test/TestAnnotatedHandlerRegistration.java
2929
/* * 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.openaz.pepapi.std.test; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.openaz.pepapi.*; import org.apache.openaz.pepapi.std.StdPepAgentFactory; import org.apache.openaz.pepapi.std.test.obligation.AnnotatedCatchAllObligationHandler; import org.apache.openaz.pepapi.std.test.obligation.AnnotatedFilteringObligationHandler; import org.apache.openaz.pepapi.std.test.obligation.AnnotatedRedactionObligationHandler; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class TestAnnotatedHandlerRegistration { @SuppressWarnings("unused") private static Log log = LogFactory.getLog(TestAnnotatedHandlerRegistration.class); private PepAgentFactory pepAgentFactory; // TODO: Need to wire private AnnotatedFilteringObligationHandler filterHandler; // TODO: Need to wire private AnnotatedRedactionObligationHandler redactionHandler; // TODO: Need to wire private AnnotatedCatchAllObligationHandler catchAllHandler; @Before public void setup() { pepAgentFactory = new StdPepAgentFactory("xacml.properties"); } /** * */ @Ignore @Test public void testPepAgent() { Assert.assertNotNull(getPepAgent()); } /** * */ @Ignore @Test public void testRegistration() { Subject subject = Subject.newInstance("John Smith"); subject.addAttribute("urn:oasis:names:tc:xacml:1.0:subject:age", "45"); PepResponse response = getPepAgent().decide(subject, Action.newInstance("view"), Resource.newInstance("resource1")); Assert.assertNotNull(response); Assert.assertEquals(true, response.allowed()); filterHandler.enforce(); redactionHandler.enforce(); catchAllHandler.enforce(); } public PepAgent getPepAgent() { return pepAgentFactory.getPepAgent(); } }
apache-2.0
alvin319/CarnotKE
jyhton/src/org/python/core/PyFunction.java
19253
// Copyright (c) Corporation for National Research Initiatives package org.python.core; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedSet; import org.python.expose.ExposedType; /** * A Python function. */ @ExposedType(name = "function", isBaseType = false, doc = BuiltinDocs.function_doc) public class PyFunction extends PyObject implements InvocationHandler, Traverseproc { public static final PyType TYPE = PyType.fromClass(PyFunction.class); /** The writable name, also available via func_name. */ @ExposedGet public String __name__; /** The writable doc string, also available via func_doc. */ @ExposedGet @ExposedSet public PyObject __doc__; /** The read only namespace; a dict (PyStringMap). */ @ExposedGet public PyObject __globals__; /** * Default argument values for associated kwargs. Exposed as a * tuple to Python. Writable. */ public PyObject[] __defaults__; /** The actual function's code, writable. */ @ExposedGet public PyCode __code__; /** * A function's lazily created __dict__; allows arbitrary * attributes to be tacked on. Read only. */ public PyObject __dict__; /** A read only closure tuple for nested scopes. */ @ExposedGet public PyObject __closure__; /** Writable object describing what module this function belongs to. */ @ExposedGet @ExposedSet public PyObject __module__; public PyFunction(PyObject globals, PyObject[] defaults, PyCode code, PyObject doc, PyObject[] closure_cells) { super(TYPE); __globals__ = globals; __name__ = code.co_name; __doc__ = doc != null ? doc : Py.None; // XXX: workaround the compiler passing Py.EmptyObjects // instead of null for defaults, whereas we want __defaults__ // to be None (null) in that situation __defaults__ = (defaults != null && defaults.length == 0) ? null : defaults; __code__ = code; __closure__ = closure_cells != null ? new PyTuple(closure_cells) : null; PyObject moduleName = globals.__finditem__("__name__"); __module__ = moduleName != null ? moduleName : Py.None; } public PyFunction(PyObject globals, PyObject[] defaults, PyCode code, PyObject doc) { this(globals, defaults, code, doc, null); } public PyFunction(PyObject globals, PyObject[] defaults, PyCode code) { this(globals, defaults, code, null, null); } public PyFunction(PyObject globals, PyObject[] defaults, PyCode code, PyObject[] closure_cells) { this(globals, defaults, code, null, closure_cells); } @ExposedNew static final PyObject function___new__(PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("function", args, keywords, new String[] {"code", "globals", "name", "argdefs", "closure"}, 0); PyObject code = ap.getPyObject(0); PyObject globals = ap.getPyObject(1); PyObject name = ap.getPyObject(2, Py.None); PyObject defaults = ap.getPyObject(3, Py.None); PyObject closure = ap.getPyObject(4, Py.None); if (!(code instanceof PyBaseCode)) { throw Py.TypeError("function() argument 1 must be code, not " + code.getType().fastGetName()); } if (name != Py.None && !Py.isInstance(name, PyString.TYPE)) { throw Py.TypeError("arg 3 (name) must be None or string"); } if (defaults != Py.None && !(defaults instanceof PyTuple)) { throw Py.TypeError("arg 4 (defaults) must be None or tuple"); } PyBaseCode tcode = (PyBaseCode)code; int nfree = tcode.co_freevars == null ? 0 : tcode.co_freevars.length; if (!(closure instanceof PyTuple)) { if (nfree > 0 && closure == Py.None) { throw Py.TypeError("arg 5 (closure) must be tuple"); } else if (closure != Py.None) { throw Py.TypeError("arg 5 (closure) must be None or tuple"); } } int nclosure = closure == Py.None ? 0 : closure.__len__(); if (nfree != nclosure) { throw Py.ValueError(String.format("%s requires closure of length %d, not %d", tcode.co_name, nfree, nclosure)); } if (nclosure > 0) { for (PyObject o : ((PyTuple)closure).asIterable()) { if (!(o instanceof PyCell)) { throw Py.TypeError(String.format("arg 5 (closure) expected cell, found %s", o.getType().fastGetName())); } } } PyFunction function = new PyFunction(globals, defaults == Py.None ? null : ((PyTuple)defaults).getArray(), tcode, null, closure == Py.None ? null : ((PyTuple)closure).getArray()); if (name != Py.None) { function.__name__ = name.toString(); } return function; } @ExposedSet(name = "__name__") public void setName(String func_name) { __name__ = func_name; } @ExposedDelete(name = "__name__") public void delName() { throw Py.TypeError("__name__ must be set to a string object"); } @Deprecated @ExposedGet(name = "func_name") public String getFuncName() { return __name__; } @Deprecated @ExposedSet(name = "func_name") public void setFuncName(String func_name) { setName(func_name); } @Deprecated @ExposedDelete(name = "func_name") public void delFuncName() { delName(); } @Deprecated @ExposedGet(name = "func_doc") public PyObject getFuncDoc() { return __doc__; } @Deprecated @ExposedSet(name = "func_doc") public void setFuncDoc(PyObject func_doc) { __doc__ = func_doc; } @Deprecated @ExposedDelete(name = "func_doc") public void delFuncDoc() { delDoc(); } @ExposedDelete(name = "__doc__") public void delDoc() { __doc__ = Py.None; } @ExposedGet(name = "__defaults__") public PyObject getDefaults() { if (__defaults__ == null) { return Py.None; } return new PyTuple(__defaults__); } @ExposedSet(name = "__defaults__") public void setDefaults(PyObject func_defaults) { if (func_defaults != Py.None && !(func_defaults instanceof PyTuple)) { throw Py.TypeError("func_defaults must be set to a tuple object"); } this.__defaults__ = func_defaults == Py.None ? null : ((PyTuple)func_defaults).getArray(); } @ExposedDelete(name = "__defaults__") public void delDefaults() { __defaults__ = null; } @Deprecated @ExposedGet(name = "func_defaults") public PyObject getFuncDefaults() { return getDefaults(); } @Deprecated @ExposedSet(name = "func_defaults") public void setFuncDefaults(PyObject func_defaults) { setDefaults(func_defaults); } @Deprecated @ExposedDelete(name = "func_defaults") public void delFuncDefaults( ) { delDefaults(); } @Deprecated @ExposedGet(name = "func_code") public PyCode getFuncCode() { return __code__; } @Deprecated @ExposedSet(name = "func_code") public void setFuncCode(PyCode code) { setCode(code); } @ExposedSet(name = "__code__") public void setCode(PyCode code) { if (__code__ == null || !(code instanceof PyBaseCode)) { throw Py.TypeError("__code__ must be set to a code object"); } PyBaseCode tcode = (PyBaseCode)code; int nfree = tcode.co_freevars == null ? 0 : tcode.co_freevars.length; int nclosure = __closure__ != null ? __closure__.__len__() : 0; if (nclosure != nfree) { throw Py.ValueError(String.format("%s() requires a code object with %d free vars," + " not %d", __name__, nclosure, nfree)); } this.__code__ = code; } @ExposedDelete(name = "__module__") public void delModule() { __module__ = Py.None; } @Override public PyObject fastGetDict() { return __dict__; } @ExposedGet(name = "__dict__") public PyObject getDict() { ensureDict(); return __dict__; } @ExposedSet(name = "__dict__") public void setDict(PyObject value) { if (!(value instanceof PyDictionary) && !(value instanceof PyStringMap)) { throw Py.TypeError("setting function's dictionary to a non-dict"); } __dict__ = value; } @ExposedDelete(name = "__dict__") public void delDict() { throw Py.TypeError("function's dictionary may not be deleted"); } @Deprecated @ExposedGet(name = "func_dict") public PyObject getFuncDict() { return getDict(); } @Deprecated @ExposedSet(name = "func_dict") public void setFuncDict(PyObject value) { setDict(value); } @Deprecated @ExposedDelete(name = "func_dict") public void delFuncDict() { delDict(); } @ExposedSet(name = "__globals__") public void setGlobals(PyObject value) { throw Py.TypeError("readonly attribute"); } @ExposedDelete(name = "__globals__") public void delGlobals() { throw Py.TypeError("readonly attribute"); } @Deprecated @ExposedGet(name = "func_globals") public PyObject getFuncGlobals() { return __globals__; } @Deprecated @ExposedSet(name = "func_globals") public void setFuncGlobals(PyObject value) { setGlobals(value); } @Deprecated @ExposedDelete(name = "func_globals") public void delFuncGlobals() { delGlobals(); } @ExposedSet(name = "__closure__") public void setClosure(PyObject value) { throw Py.TypeError("readonly attribute"); } @ExposedDelete(name = "__closure__") public void delClosure() { throw Py.TypeError("readonly attribute"); } @Deprecated @ExposedGet(name = "func_closure") public PyObject getFuncClosure() { return __closure__; } @Deprecated @ExposedSet(name = "func_closure") public void setFuncClosure(PyObject value) { setClosure(value); } @Deprecated @ExposedDelete(name = "func_closure") public void delFuncClosure() { delClosure(); } private void ensureDict() { if (__dict__ == null) { __dict__ = new PyStringMap(); } } @Override public void __setattr__(String name, PyObject value) { function___setattr__(name, value); } @ExposedMethod(doc = BuiltinDocs.function___setattr___doc) final void function___setattr__(String name, PyObject value) { ensureDict(); super.__setattr__(name, value); } @Override public PyObject __get__(PyObject obj, PyObject type) { return function___get__(obj, type); } @ExposedMethod(defaults = "null", doc = BuiltinDocs.function___get___doc) final PyObject function___get__(PyObject obj, PyObject type) { return new PyMethod(this, obj, type); } @Override public PyObject __call__() { return __call__(Py.getThreadState()); } @Override public PyObject __call__(ThreadState state) { return __code__.call(state, __globals__, __defaults__, __closure__); } @Override public PyObject __call__(PyObject arg) { return __call__(Py.getThreadState(), arg); } @Override public PyObject __call__(ThreadState state, PyObject arg0) { return __code__.call(state, arg0, __globals__, __defaults__, __closure__); } @Override public PyObject __call__(PyObject arg1, PyObject arg2) { return __call__(Py.getThreadState(), arg1, arg2); } @Override public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1) { return __code__.call(state, arg0, arg1, __globals__, __defaults__, __closure__); } @Override public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { return __call__(Py.getThreadState(), arg1, arg2, arg3); } @Override public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, PyObject arg2) { return __code__.call(state, arg0, arg1, arg2, __globals__, __defaults__, __closure__); } @Override public PyObject __call__(PyObject arg0, PyObject arg1, PyObject arg2, PyObject arg3) { return __call__(Py.getThreadState(), arg0, arg1, arg2, arg3); } @Override public PyObject __call__(ThreadState state, PyObject arg0, PyObject arg1, PyObject arg2, PyObject arg3) { return __code__.call(state, arg0, arg1, arg2, arg3, __globals__, __defaults__, __closure__); } @Override public PyObject __call__(PyObject[] args) { return __call__(Py.getThreadState(), args); } @Override public PyObject __call__(ThreadState state, PyObject[] args) { return __call__(state, args, Py.NoKeywords); } @Override public PyObject __call__(PyObject[] args, String[] keywords) { return __call__(Py.getThreadState(), args, keywords); } @Override public PyObject __call__(ThreadState state, PyObject[] args, String[] keywords) { return function___call__(state, args, keywords); } @ExposedMethod(doc = BuiltinDocs.function___call___doc) final PyObject function___call__(ThreadState state, PyObject[] args, String[] keywords) { return __code__.call(state, args, keywords, __globals__, __defaults__, __closure__); } @Override public PyObject __call__(PyObject arg1, PyObject[] args, String[] keywords) { return __call__(Py.getThreadState(), arg1, args, keywords); } @Override public PyObject __call__(ThreadState state, PyObject arg1, PyObject[] args, String[] keywords) { return __code__.call(state, arg1, args, keywords, __globals__, __defaults__, __closure__); } @Override public String toString() { return String.format("<function %s at %s>", __name__, Py.idstr(this)); } @Override public Object __tojava__(Class<?> c) { // Automatically coerce to single method interfaces if (c.isInstance(this) && c != InvocationHandler.class) { // for base types, conversion is simple - so don't wrap! // InvocationHandler is special, since it's a single method interface // that we implement, but if we coerce to it we want the arguments return c.cast( this ); } else if (c.isInterface()) { if (c.getDeclaredMethods().length == 1 && c.getInterfaces().length == 0) { // Proper single method interface return proxy(c); } else { // Try coerce to interface with multiple overloaded versions of // the same method (name) String name = null; for (Method method : c.getMethods()) { if (method.getDeclaringClass() != Object.class) { if (name == null || name.equals(method.getName())) { name = method.getName(); } else { name = null; break; } } } if (name != null) { // single unique method name return proxy(c); } } } return super.__tojava__(c); } private Object proxy( Class<?> c ) { return Proxy.newProxyInstance(c.getClassLoader(), new Class[]{c}, this); } public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { // Handle invocation when invoked through Proxy (as coerced to single method interface) if (method.getDeclaringClass() == Object.class) { return method.invoke( this, args ); } else if (args == null || args.length == 0) { return __call__().__tojava__(method.getReturnType()); } else { return __call__(Py.javas2pys(args)).__tojava__(method.getReturnType()); } } @Override public boolean isMappingType() { return false; } @Override public boolean isNumberType() { return false; } @Override public boolean isSequenceType() { return false; } /* Traverseproc implementation */ @Override public int traverse(Visitproc visit, Object arg) { //globals cannot be null int retVal = visit.visit(__globals__, arg); if (retVal != 0) { return retVal; } if (__code__ != null) { retVal = visit.visit(__code__, arg); if (retVal != 0) { return retVal; } } //__module__ cannot be null retVal = visit.visit(__module__, arg); if (retVal != 0) { return retVal; } if (__defaults__ != null) { for (PyObject ob: __defaults__) { if (ob != null) { retVal = visit.visit(ob, arg); if (retVal != 0) { return retVal; } } } } //__doc__ cannot be null retVal = visit.visit(__doc__, arg); if (retVal != 0) { return retVal; } // CPython also traverses the name, which is not stored // as a PyObject in Jython: // Py_VISIT(f->func_name); if (__dict__ != null) { retVal = visit.visit(__dict__, arg); if (retVal != 0) { return retVal; } } return __closure__ != null ? visit.visit(__closure__, arg) : 0; } @Override public boolean refersDirectlyTo(PyObject ob) { if (ob == null) { return false; } if (__defaults__ != null) { for (PyObject obj: __defaults__) { if (obj == ob) { return true; } } } return ob == __doc__ || ob == __globals__ || ob == __code__ || ob == __dict__ || ob == __closure__ || ob == __module__; } }
apache-2.0
thiliniish/developer-studio
esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/ValidationContextSelector.java
945
/* * Copyright 2009-2010 WSO2, Inc. (http://wso2.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.wso2.developerstudio.eclipse.esb; import org.eclipse.emf.validation.model.IClientSelector; /** * Validation context selector. */ public class ValidationContextSelector implements IClientSelector { /** * {@inheritDoc} */ public boolean selects(Object object) { return (object instanceof ModelObject); } }
apache-2.0
AlexMinsk/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/cmd/CreateTenantUserMembershipCmd.java
1501
/* 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.camunda.bpm.engine.impl.cmd; import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull; import java.io.Serializable; import org.camunda.bpm.engine.impl.interceptor.Command; import org.camunda.bpm.engine.impl.interceptor.CommandContext; public class CreateTenantUserMembershipCmd extends AbstractWritableIdentityServiceCmd<Void> implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected final String tenantId; protected final String userId; public CreateTenantUserMembershipCmd(String tenantId, String userId) { this.tenantId = tenantId; this.userId = userId; } @Override protected Void executeCmd(CommandContext commandContext) { ensureNotNull("tenantId", tenantId); ensureNotNull("userId", userId); commandContext .getWritableIdentityProvider() .createTenantUserMembership(tenantId, userId); return null; } }
apache-2.0
drewr/elasticsearch
core/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryBuilder.java
13789
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.query; import org.apache.lucene.search.Query; import org.elasticsearch.Version; import org.elasticsearch.common.Numbers; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.fielddata.IndexGeoPointFieldData; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.geo.GeoPointFieldMapper; import org.elasticsearch.index.search.geo.InMemoryGeoBoundingBoxQuery; import org.elasticsearch.index.search.geo.IndexedGeoBoundingBoxQuery; import java.io.IOException; import java.util.Objects; /** * Creates a Lucene query that will filter for all documents that lie within the specified * bounding box. * * This query can only operate on fields of type geo_point that have latitude and longitude * enabled. * */ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBoundingBoxQueryBuilder> { /** Name of the query. */ public static final String NAME = "geo_bbox"; /** Default type for executing this query (memory as of this writing). */ public static final GeoExecType DEFAULT_TYPE = GeoExecType.MEMORY; /** Needed for serialization. */ static final GeoBoundingBoxQueryBuilder PROTOTYPE = new GeoBoundingBoxQueryBuilder(""); /** Name of field holding geo coordinates to compute the bounding box on.*/ private final String fieldName; /** Top left corner coordinates of bounding box. */ private GeoPoint topLeft = new GeoPoint(Double.NaN, Double.NaN); /** Bottom right corner coordinates of bounding box.*/ private GeoPoint bottomRight = new GeoPoint(Double.NaN, Double.NaN); /** How to deal with incorrect coordinates.*/ private GeoValidationMethod validationMethod = GeoValidationMethod.DEFAULT; /** How the query should be run. */ private GeoExecType type = DEFAULT_TYPE; /** * Create new bounding box query. * @param fieldName name of index field containing geo coordinates to operate on. * */ public GeoBoundingBoxQueryBuilder(String fieldName) { if (fieldName == null) { throw new IllegalArgumentException("Field name must not be empty."); } this.fieldName = fieldName; } /** * Adds top left point. * @param top The top latitude * @param left The left longitude * @param bottom The bottom latitude * @param right The right longitude */ public GeoBoundingBoxQueryBuilder setCorners(double top, double left, double bottom, double right) { if (GeoValidationMethod.isIgnoreMalformed(validationMethod) == false) { if (Numbers.isValidDouble(top) == false) { throw new IllegalArgumentException("top latitude is invalid: " + top); } if (Numbers.isValidDouble(left) == false) { throw new IllegalArgumentException("left longitude is invalid: " + left); } if (Numbers.isValidDouble(bottom) == false) { throw new IllegalArgumentException("bottom latitude is invalid: " + bottom); } if (Numbers.isValidDouble(right) == false) { throw new IllegalArgumentException("right longitude is invalid: " + right); } // all corners are valid after above checks - make sure they are in the right relation if (top < bottom) { throw new IllegalArgumentException("top is below bottom corner: " + top + " vs. " + bottom); } // we do not check longitudes as the query generation code can deal with flipped left/right values } topLeft.reset(top, left); bottomRight.reset(bottom, right); return this; } /** * Adds points. * @param topLeft topLeft point to add. * @param bottomRight bottomRight point to add. * */ public GeoBoundingBoxQueryBuilder setCorners(GeoPoint topLeft, GeoPoint bottomRight) { return setCorners(topLeft.getLat(), topLeft.getLon(), bottomRight.getLat(), bottomRight.getLon()); } /** * Adds points. * @param topLeft topLeft point to add as geohash. * @param bottomRight bottomRight point to add as geohash. * */ public GeoBoundingBoxQueryBuilder setCorners(String topLeft, String bottomRight) { return setCorners(GeoPoint.fromGeohash(topLeft), GeoPoint.fromGeohash(bottomRight)); } /** Returns the top left corner of the bounding box. */ public GeoPoint topLeft() { return topLeft; } /** Returns the bottom right corner of the bounding box. */ public GeoPoint bottomRight() { return bottomRight; } /** * Adds corners in OGC standard bbox/ envelop format. * * @param bottomLeft bottom left corner of bounding box. * @param topRight top right corner of bounding box. */ public GeoBoundingBoxQueryBuilder setCornersOGC(GeoPoint bottomLeft, GeoPoint topRight) { return setCorners(topRight.getLat(), bottomLeft.getLon(), bottomLeft.getLat(), topRight.getLon()); } /** * Adds corners in OGC standard bbox/ envelop format. * * @param bottomLeft bottom left corner geohash. * @param topRight top right corner geohash. */ public GeoBoundingBoxQueryBuilder setCornersOGC(String bottomLeft, String topRight) { return setCornersOGC(GeoPoint.fromGeohash(bottomLeft), GeoPoint.fromGeohash(topRight)); } /** * Specify whether or not to ignore validation errors of bounding boxes. * Can only be set if coerce set to false, otherwise calling this * method has no effect. **/ public GeoBoundingBoxQueryBuilder setValidationMethod(GeoValidationMethod method) { this.validationMethod = method; return this; } /** * Returns geo coordinate validation method to use. * */ public GeoValidationMethod getValidationMethod() { return this.validationMethod; } /** * Sets the type of executing of the geo bounding box. Can be either `memory` or `indexed`. Defaults * to `memory`. */ public GeoBoundingBoxQueryBuilder type(GeoExecType type) { if (type == null) { throw new IllegalArgumentException("Type is not allowed to be null."); } this.type = type; return this; } /** * For BWC: Parse type from type name. * */ public GeoBoundingBoxQueryBuilder type(String type) { this.type = GeoExecType.fromString(type); return this; } /** Returns the execution type of the geo bounding box.*/ public GeoExecType type() { return type; } /** Returns the name of the field to base the bounding box computation on. */ public String fieldName() { return this.fieldName; } QueryValidationException checkLatLon(boolean indexCreatedBeforeV2_0) { // validation was not available prior to 2.x, so to support bwc percolation queries we only ignore_malformed on 2.x created indexes if (GeoValidationMethod.isIgnoreMalformed(validationMethod) == true || indexCreatedBeforeV2_0) { return null; } QueryValidationException validationException = null; // For everything post 2.0 validate latitude and longitude unless validation was explicitly turned off if (GeoUtils.isValidLatitude(topLeft.getLat()) == false) { validationException = addValidationError("top latitude is invalid: " + topLeft.getLat(), validationException); } if (GeoUtils.isValidLongitude(topLeft.getLon()) == false) { validationException = addValidationError("left longitude is invalid: " + topLeft.getLon(), validationException); } if (GeoUtils.isValidLatitude(bottomRight.getLat()) == false) { validationException = addValidationError("bottom latitude is invalid: " + bottomRight.getLat(), validationException); } if (GeoUtils.isValidLongitude(bottomRight.getLon()) == false) { validationException = addValidationError("right longitude is invalid: " + bottomRight.getLon(), validationException); } return validationException; } @Override public Query doToQuery(QueryShardContext context) { QueryValidationException exception = checkLatLon(context.indexVersionCreated().before(Version.V_2_0_0)); if (exception != null) { throw new QueryShardException(context, "couldn't validate latitude/ longitude values", exception); } GeoPoint luceneTopLeft = new GeoPoint(topLeft); GeoPoint luceneBottomRight = new GeoPoint(bottomRight); if (GeoValidationMethod.isCoerce(validationMethod)) { // Special case: if the difference between the left and right is 360 and the right is greater than the left, we are asking for // the complete longitude range so need to set longitude to the complete longditude range double right = luceneBottomRight.getLon(); double left = luceneTopLeft.getLon(); boolean completeLonRange = ((right - left) % 360 == 0 && right > left); GeoUtils.normalizePoint(luceneTopLeft, true, !completeLonRange); GeoUtils.normalizePoint(luceneBottomRight, true, !completeLonRange); if (completeLonRange) { luceneTopLeft.resetLon(-180); luceneBottomRight.resetLon(180); } } MappedFieldType fieldType = context.fieldMapper(fieldName); if (fieldType == null) { throw new QueryShardException(context, "failed to find geo_point field [" + fieldName + "]"); } if (!(fieldType instanceof GeoPointFieldMapper.GeoPointFieldType)) { throw new QueryShardException(context, "field [" + fieldName + "] is not a geo_point field"); } GeoPointFieldMapper.GeoPointFieldType geoFieldType = ((GeoPointFieldMapper.GeoPointFieldType) fieldType); Query result; switch(type) { case INDEXED: result = IndexedGeoBoundingBoxQuery.create(luceneTopLeft, luceneBottomRight, geoFieldType); break; case MEMORY: IndexGeoPointFieldData indexFieldData = context.getForField(fieldType); result = new InMemoryGeoBoundingBoxQuery(luceneTopLeft, luceneBottomRight, indexFieldData); break; default: // Someone extended the type enum w/o adjusting this switch statement. throw new IllegalStateException("geo bounding box type [" + type + "] not supported."); } return result; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(NAME); builder.startObject(fieldName); builder.array(GeoBoundingBoxQueryParser.TOP_LEFT, topLeft.getLon(), topLeft.getLat()); builder.array(GeoBoundingBoxQueryParser.BOTTOM_RIGHT, bottomRight.getLon(), bottomRight.getLat()); builder.endObject(); builder.field("validation_method", validationMethod); builder.field("type", type); printBoostAndQueryName(builder); builder.endObject(); } @Override public boolean doEquals(GeoBoundingBoxQueryBuilder other) { return Objects.equals(topLeft, other.topLeft) && Objects.equals(bottomRight, other.bottomRight) && Objects.equals(type, other.type) && Objects.equals(validationMethod, other.validationMethod) && Objects.equals(fieldName, other.fieldName); } @Override public int doHashCode() { return Objects.hash(topLeft, bottomRight, type, validationMethod, fieldName); } @Override public GeoBoundingBoxQueryBuilder doReadFrom(StreamInput in) throws IOException { String fieldName = in.readString(); GeoBoundingBoxQueryBuilder geo = new GeoBoundingBoxQueryBuilder(fieldName); geo.topLeft = in.readGeoPoint(); geo.bottomRight = in.readGeoPoint(); geo.type = GeoExecType.readTypeFrom(in); geo.validationMethod = GeoValidationMethod.readGeoValidationMethodFrom(in); return geo; } @Override public void doWriteTo(StreamOutput out) throws IOException { out.writeString(fieldName); out.writeGeoPoint(topLeft); out.writeGeoPoint(bottomRight); type.writeTo(out); validationMethod.writeTo(out); } @Override public String getWriteableName() { return NAME; } }
apache-2.0
Cloudyle/hapi-fhir
hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/ResourceFactory.java
11865
package org.hl7.fhir.instance.model; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Wed, Nov 11, 2015 10:54-0500 for FHIR v1.0.2 public class ResourceFactory extends Factory { public static Resource createReference(String name) throws Exception { if ("Appointment".equals(name)) return new Appointment(); if ("ReferralRequest".equals(name)) return new ReferralRequest(); if ("Account".equals(name)) return new Account(); if ("Provenance".equals(name)) return new Provenance(); if ("Questionnaire".equals(name)) return new Questionnaire(); if ("ExplanationOfBenefit".equals(name)) return new ExplanationOfBenefit(); if ("DocumentManifest".equals(name)) return new DocumentManifest(); if ("Specimen".equals(name)) return new Specimen(); if ("AllergyIntolerance".equals(name)) return new AllergyIntolerance(); if ("CarePlan".equals(name)) return new CarePlan(); if ("Goal".equals(name)) return new Goal(); if ("StructureDefinition".equals(name)) return new StructureDefinition(); if ("EnrollmentRequest".equals(name)) return new EnrollmentRequest(); if ("EpisodeOfCare".equals(name)) return new EpisodeOfCare(); if ("OperationOutcome".equals(name)) return new OperationOutcome(); if ("Medication".equals(name)) return new Medication(); if ("Procedure".equals(name)) return new Procedure(); if ("List".equals(name)) return new List_(); if ("ConceptMap".equals(name)) return new ConceptMap(); if ("Subscription".equals(name)) return new Subscription(); if ("ValueSet".equals(name)) return new ValueSet(); if ("OperationDefinition".equals(name)) return new OperationDefinition(); if ("DocumentReference".equals(name)) return new DocumentReference(); if ("Order".equals(name)) return new Order(); if ("Immunization".equals(name)) return new Immunization(); if ("Parameters".equals(name)) return new Parameters(); if ("Device".equals(name)) return new Device(); if ("VisionPrescription".equals(name)) return new VisionPrescription(); if ("Media".equals(name)) return new Media(); if ("Conformance".equals(name)) return new Conformance(); if ("ProcedureRequest".equals(name)) return new ProcedureRequest(); if ("EligibilityResponse".equals(name)) return new EligibilityResponse(); if ("DeviceUseRequest".equals(name)) return new DeviceUseRequest(); if ("DeviceMetric".equals(name)) return new DeviceMetric(); if ("Flag".equals(name)) return new Flag(); if ("RelatedPerson".equals(name)) return new RelatedPerson(); if ("SupplyRequest".equals(name)) return new SupplyRequest(); if ("Practitioner".equals(name)) return new Practitioner(); if ("AppointmentResponse".equals(name)) return new AppointmentResponse(); if ("Observation".equals(name)) return new Observation(); if ("MedicationAdministration".equals(name)) return new MedicationAdministration(); if ("Slot".equals(name)) return new Slot(); if ("EnrollmentResponse".equals(name)) return new EnrollmentResponse(); if ("Binary".equals(name)) return new Binary(); if ("MedicationStatement".equals(name)) return new MedicationStatement(); if ("Person".equals(name)) return new Person(); if ("Contract".equals(name)) return new Contract(); if ("CommunicationRequest".equals(name)) return new CommunicationRequest(); if ("RiskAssessment".equals(name)) return new RiskAssessment(); if ("TestScript".equals(name)) return new TestScript(); if ("Basic".equals(name)) return new Basic(); if ("Group".equals(name)) return new Group(); if ("PaymentNotice".equals(name)) return new PaymentNotice(); if ("Organization".equals(name)) return new Organization(); if ("ImplementationGuide".equals(name)) return new ImplementationGuide(); if ("ClaimResponse".equals(name)) return new ClaimResponse(); if ("EligibilityRequest".equals(name)) return new EligibilityRequest(); if ("ProcessRequest".equals(name)) return new ProcessRequest(); if ("MedicationDispense".equals(name)) return new MedicationDispense(); if ("DiagnosticReport".equals(name)) return new DiagnosticReport(); if ("ImagingStudy".equals(name)) return new ImagingStudy(); if ("ImagingObjectSelection".equals(name)) return new ImagingObjectSelection(); if ("HealthcareService".equals(name)) return new HealthcareService(); if ("DataElement".equals(name)) return new DataElement(); if ("DeviceComponent".equals(name)) return new DeviceComponent(); if ("FamilyMemberHistory".equals(name)) return new FamilyMemberHistory(); if ("NutritionOrder".equals(name)) return new NutritionOrder(); if ("Encounter".equals(name)) return new Encounter(); if ("Substance".equals(name)) return new Substance(); if ("AuditEvent".equals(name)) return new AuditEvent(); if ("MedicationOrder".equals(name)) return new MedicationOrder(); if ("SearchParameter".equals(name)) return new SearchParameter(); if ("PaymentReconciliation".equals(name)) return new PaymentReconciliation(); if ("Communication".equals(name)) return new Communication(); if ("Condition".equals(name)) return new Condition(); if ("Composition".equals(name)) return new Composition(); if ("DetectedIssue".equals(name)) return new DetectedIssue(); if ("Bundle".equals(name)) return new Bundle(); if ("DiagnosticOrder".equals(name)) return new DiagnosticOrder(); if ("Patient".equals(name)) return new Patient(); if ("OrderResponse".equals(name)) return new OrderResponse(); if ("Coverage".equals(name)) return new Coverage(); if ("QuestionnaireResponse".equals(name)) return new QuestionnaireResponse(); if ("DeviceUseStatement".equals(name)) return new DeviceUseStatement(); if ("ProcessResponse".equals(name)) return new ProcessResponse(); if ("NamingSystem".equals(name)) return new NamingSystem(); if ("Schedule".equals(name)) return new Schedule(); if ("SupplyDelivery".equals(name)) return new SupplyDelivery(); if ("ClinicalImpression".equals(name)) return new ClinicalImpression(); if ("MessageHeader".equals(name)) return new MessageHeader(); if ("Claim".equals(name)) return new Claim(); if ("ImmunizationRecommendation".equals(name)) return new ImmunizationRecommendation(); if ("Location".equals(name)) return new Location(); if ("BodySite".equals(name)) return new BodySite(); else throw new Exception("Unknown Resource Name '"+name+"'"); } public static Element createType(String name) throws Exception { if ("Meta".equals(name)) return new Meta(); if ("Address".equals(name)) return new Address(); if ("Attachment".equals(name)) return new Attachment(); if ("Count".equals(name)) return new Count(); if ("Money".equals(name)) return new Money(); if ("HumanName".equals(name)) return new HumanName(); if ("ContactPoint".equals(name)) return new ContactPoint(); if ("Identifier".equals(name)) return new Identifier(); if ("Narrative".equals(name)) return new Narrative(); if ("Coding".equals(name)) return new Coding(); if ("SampledData".equals(name)) return new SampledData(); if ("Ratio".equals(name)) return new Ratio(); if ("ElementDefinition".equals(name)) return new ElementDefinition(); if ("Distance".equals(name)) return new Distance(); if ("Age".equals(name)) return new Age(); if ("Reference".equals(name)) return new Reference(); if ("SimpleQuantity".equals(name)) return new SimpleQuantity(); if ("Quantity".equals(name)) return new Quantity(); if ("Period".equals(name)) return new Period(); if ("Duration".equals(name)) return new Duration(); if ("Range".equals(name)) return new Range(); if ("Annotation".equals(name)) return new Annotation(); if ("Extension".equals(name)) return new Extension(); if ("Signature".equals(name)) return new Signature(); if ("Timing".equals(name)) return new Timing(); if ("CodeableConcept".equals(name)) return new CodeableConcept(); else throw new Exception("Unknown Type Name '"+name+"'"); } }
apache-2.0
alvin319/CarnotKE
jyhton/installer/src/java/org/apache/commons/cli/CommandLineParser.java
4112
/* * $Header$ * $Revision: 2662 $ * $Date: 2006-02-18 06:20:33 -0800 (Sat, 18 Feb 2006) $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.commons.cli; /** * A class that implements the <code>CommandLineParser</code> interface * can parse a String array according to the {@link Options} specified * and return a {@link CommandLine}. * * @author John Keyes (john at integralsource.com) */ public interface CommandLineParser { /** * Parse the arguments according to the specified options. * * @param options the specified Options * @param arguments the command line arguments * @return the list of atomic option and value tokens * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ public CommandLine parse( Options options, String[] arguments ) throws ParseException; /** * Parse the arguments according to the specified options. * * @param options the specified Options * @param arguments the command line arguments * @param stopAtNonOption specifies whether to continue parsing the * arguments if a non option is encountered. * @return the list of atomic option and value tokens * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ public CommandLine parse( Options options, String[] arguments, boolean stopAtNonOption ) throws ParseException; }
apache-2.0
MicheleGuerriero/SeaCloudsPlatform
sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/helpers/AgreementHelperE.java
14117
/** * Copyright 2014 Atos * Contact: Atos <roman.sosa@atos.net> * * 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 eu.atos.sla.service.rest.helpers; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import eu.atos.sla.dao.IAgreementDAO; import eu.atos.sla.dao.IEnforcementJobDAO; import eu.atos.sla.dao.IGuaranteeTermDAO; import eu.atos.sla.dao.IProviderDAO; import eu.atos.sla.dao.ITemplateDAO; import eu.atos.sla.datamodel.IAgreement; import eu.atos.sla.datamodel.IEnforcementJob; import eu.atos.sla.datamodel.IGuaranteeTerm; import eu.atos.sla.datamodel.IGuaranteeTerm.GuaranteeTermStatusEnum; import eu.atos.sla.datamodel.IProvider; import eu.atos.sla.datamodel.ITemplate; import eu.atos.sla.enforcement.IEnforcementService; import eu.atos.sla.parser.data.GuaranteeTermStatus; import eu.atos.sla.parser.data.GuaranteeTermsStatus; import eu.atos.sla.parser.data.wsag.Agreement; import eu.atos.sla.parser.data.wsag.Context; import eu.atos.sla.service.rest.helpers.exception.DBExistsHelperException; import eu.atos.sla.service.rest.helpers.exception.DBMissingHelperException; import eu.atos.sla.service.rest.helpers.exception.InternalHelperException; import eu.atos.sla.service.rest.helpers.exception.ParserHelperException; import eu.atos.sla.util.IModelConverter; import eu.atos.sla.util.ModelConversionException; /** * */ @Service @Transactional public class AgreementHelperE{ private static Logger logger = LoggerFactory.getLogger(AgreementHelperE.class); @Autowired private IAgreementDAO agreementDAO; @Autowired private IGuaranteeTermDAO guaranteeTermDAO; @Autowired private IProviderDAO providerDAO; @Autowired private ITemplateDAO templateDAO; @Autowired private IModelConverter modelConverter; @Autowired private IEnforcementJobDAO enforcementJobDAO; @Autowired private IEnforcementService enforcementService; public AgreementHelperE() { } private boolean doesAgreementIdExistInRepository(String agreementId) { return agreementDAO.getByAgreementId(agreementId) != null; } private boolean doesEnforcementExistInRepository(String agreementId) { return enforcementJobDAO.getByAgreementId(agreementId) != null; } private IProvider providerFromRepository(String providerUUID) { if (providerUUID==null) return null; return providerDAO.getByUUID(providerUUID) ; } private ITemplate templateFromRepository(String templateUUID) { if (templateUUID==null) return null; return templateDAO.getByUuid(templateUUID); } public String createAgreement(Agreement agreementXML, String originalSerializedAgreement) throws DBMissingHelperException, DBExistsHelperException, InternalHelperException, ParserHelperException { return createAgreement(agreementXML, originalSerializedAgreement, ""); } public String createAgreement(Agreement agreementXML, String originalSerializedAgreement, String agreementId) throws DBMissingHelperException, DBExistsHelperException, InternalHelperException, ParserHelperException { logger.debug("StartOf createAgreement payload:{}", originalSerializedAgreement); try{ IAgreement agreementStored = null; String serializedAgreement = Utils.removeXmlHeader(originalSerializedAgreement); if (agreementXML != null) { boolean setId = agreementId != null && !"".equals(agreementId); // add field AggrementId if it doesn't exist or agreement must have wsag:AgreementId=agreementId if (agreementXML.getAgreementId() == null || setId) { if (!setId) { agreementId = UUID.randomUUID().toString(); } logger.debug("createAgreement agreement has no uuid, {} will be assigned", agreementId); serializedAgreement = setAgreementIdInSerializedAgreement(serializedAgreement, agreementId); agreementXML.setAgreementId(agreementId); } if (!doesAgreementIdExistInRepository(agreementXML.getAgreementId())) { IAgreement agreement = modelConverter.getAgreementFromAgreementXML(agreementXML, serializedAgreement); String providerUuid = agreement.getProvider().getUuid(); IProvider provider = providerFromRepository(providerUuid); if (provider == null) { throw new DBMissingHelperException("Provider with id:"+ providerUuid+ " doesn't exist SLA Repository Database"); } agreement.setProvider(provider); if (agreement.getTemplate() != null) { String templateUuid = agreement.getTemplate().getUuid(); ITemplate template = templateFromRepository(templateUuid); if (template == null) { throw new DBMissingHelperException("Template with id:"+ templateUuid+ " doesn't exist SLA Repository Database"); } agreement.setTemplate(template); } agreementStored = this.agreementDAO.save(agreement); /* create an stopped enforcement job */ if (!doesEnforcementExistInRepository(agreementStored.getAgreementId())) { // the enforcement doesn't eist IEnforcementJob ejob = enforcementService.createEnforcementJob(agreementStored.getAgreementId()); logger.debug("EnforcementJob {} created", ejob.getId()); } else { throw new DBExistsHelperException("Enforcement with id:" + agreementStored.getAgreementId() + " already exists in the SLA Repository Database"); } } else { throw new DBExistsHelperException("Agreement with id:"+ agreementXML.getAgreementId()+ " already exists in the SLA Repository Database"); } } if (agreementStored != null) { logger.debug("EndOf createAgreement"); return agreementStored.getAgreementId(); } else{ logger.debug("EndOf createAgreement"); throw new InternalHelperException("Error when creating agreement the SLA Repository Database"); } } catch (ModelConversionException e) { logger.error("Error in createAgreement " , e); throw new ParserHelperException("Error when creating:" + e.getMessage() ); } } private GuaranteeTermsStatus getGuaranteeStatus(String agreementId, List<IGuaranteeTerm> guaranteeTerms) { // Pojo GuaranteeTermsStatus GuaranteeTermsStatus guaranteeTermsStatus = new GuaranteeTermsStatus(); List<GuaranteeTermStatus> guaranteeTermStatusList = new ArrayList<GuaranteeTermStatus>(); // Status GuaranteTerm GuaranteeTermStatusEnum agreementStatus = AgreementStatusCalculator.getStatus(guaranteeTerms); guaranteeTermsStatus.setAgreementId(agreementId); guaranteeTermsStatus.setValue(agreementStatus.toString()); // Fill GuaranteeTermsStatus pojo for (IGuaranteeTerm guaranteeTerm : guaranteeTerms) { GuaranteeTermStatus guaranteeTermStatus = new GuaranteeTermStatus(); guaranteeTermStatus.setName(guaranteeTerm.getName()); guaranteeTermStatus.setValue(guaranteeTerm.getStatus().toString()); guaranteeTermStatusList.add(guaranteeTermStatus); } guaranteeTermsStatus.setGuaranteeTermsStatus(guaranteeTermStatusList); return guaranteeTermsStatus; } public List<IAgreement> getAgreements(String consumerId, String providerId, String templateId, Boolean active) { logger.debug("StartOf getAgreements consumerId:{} - providerId:{} - templateId:{} - active:{}", consumerId, providerId, templateId, active); List<IAgreement> agreements = agreementDAO.search(consumerId, providerId, templateId, active); logger.debug("EndOf getAgreements"); return agreements; } public IAgreement getAgreementByID(String id) { logger.debug("StartOf getAgreementByID id:{}", id); IAgreement agreement = agreementDAO.getByAgreementId(id); logger.debug("EndOf getAgreementByID"); return agreement; } public Context getAgreementContextByID(String id) throws InternalHelperException { logger.debug("StartOf getAgreementContextByID id:{}", id); IAgreement agreement = agreementDAO.getByAgreementId(id); Context context = null; try { if (agreement!= null) context = modelConverter.getContextFromAgreement(agreement); } catch (ModelConversionException e) { logger.error("Error getAgreementContextByID ",e); throw new InternalHelperException(e.getMessage()); } logger.debug("EndOf getAgreementContextByID"); return context; } public List<IAgreement> getActiveAgreements(long actualDate) { logger.debug("StartOf getActiveAgreements actualDate:{}", actualDate); List<IAgreement> agreements = agreementDAO.getByActiveAgreements(actualDate); logger.debug("EndOf getActiveAgreements"); return agreements; } public boolean deleteByAgreementId(String agreementId) { logger.debug("StartOf deleteByAgreementId agreementId:{}", agreementId); boolean deleted = false; IEnforcementJob enforcementJob = enforcementJobDAO.getByAgreementId(agreementId); if (enforcementJob!=null){ logger.debug("EnforcementJob exists associated to agreementId {} it will be stopped and removed", agreementId); enforcementJobDAO.delete(enforcementJob); } IAgreement agreement = agreementDAO.getByAgreementId(agreementId); if (agreement != null) { deleted = this.agreementDAO.delete(agreement); } logger.debug("EndOf deleteByAgreementId"); return deleted; } public GuaranteeTermsStatus getAgreementStatus(String id) throws DBMissingHelperException{ logger.debug("StartOf getAgreementStatus id:{}", id); IAgreement agreement = agreementDAO.getByAgreementId(id); if (agreement == null) throw new DBMissingHelperException("The agreementId " + id + " doesn't exist"); List<IGuaranteeTerm> guaranteeTerms = agreement.getGuaranteeTerms(); GuaranteeTermsStatus guaranteeTermsStatus = getGuaranteeStatus(id, guaranteeTerms); logger.debug("EndOf getAgreementStatus"); return guaranteeTermsStatus; } private String setAgreementIdInSerializedAgreement(String serializedAgreement, String agreementId){ return AgreementIdModifier.run(serializedAgreement, agreementId); } public List<IAgreement> getAgreementsPerTemplateAndConsumer(String consumerId, String templateUUID) { logger.debug("StartOf getAgreementsPerTemplateAndConsumer consumerId:"+consumerId+ " - templateUUID:"+templateUUID); List<IAgreement> agreements = agreementDAO.searchPerTemplateAndConsumer(consumerId, templateUUID); logger.debug("EndOf getAgreementsPerTemplateAndConsumer"); return agreements; } public static class AgreementIdModifier { public static String run(String serializedAgreement, String agreementId) { return serializedAgreement.replaceFirst( "<wsag:Agreement[^>]*>", "<wsag:Agreement xmlns:wsag=\"http://www.ggf.org/namespaces/ws-agreement\" xmlns:sla=\"http://sla.atos.eu\" wsag:AgreementId=\""+ agreementId + "\">"); } } public static class AgreementStatusCalculator { public static GuaranteeTermStatusEnum getStatus(List<IGuaranteeTerm> guaranteeTerms) { GuaranteeTermStatusEnum result = GuaranteeTermStatusEnum.FULFILLED; if (guaranteeTerms.size() == 0) { result = GuaranteeTermStatusEnum.NON_DETERMINED; } else { result = GuaranteeTermStatusEnum.FULFILLED; for (IGuaranteeTerm guaranteeTerm : guaranteeTerms) { GuaranteeTermStatusEnum termStatus = guaranteeTerm.getStatus(); if (termStatus == null || termStatus == GuaranteeTermStatusEnum.NON_DETERMINED) { result = GuaranteeTermStatusEnum.NON_DETERMINED; } else if (termStatus == GuaranteeTermStatusEnum.VIOLATED) { result = GuaranteeTermStatusEnum.VIOLATED; break; } } } return result; } } }
apache-2.0
bpdavis-scratch/cipango
modules/examples/cipango-example-sipapp/src/main/java/org/cipango/example/Binding.java
2150
// ======================================================================== // Copyright 2007-2009 NEXCOM Systems // ------------------------------------------------------------------------ // 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.cipango.example; import javax.servlet.sip.URI; public class Binding implements Cloneable, Comparable<Binding> { private String _aor; private URI _contact; private String _callId; private int _cseq; private long _absoluteExpires; private float _q; public Binding(String aor, URI contact) { _aor = aor; _contact = contact; } public String getAor() { return _aor; } public String getCallId() { return _callId; } public int getCseq() { return _cseq; } public URI getContact() { return _contact; } public void setCallId(String callId) { _callId = callId; } public void setCseq(int cseq) { _cseq = cseq; } public void setExpires(int expires) { _absoluteExpires = expires * 1000 + System.currentTimeMillis(); } public int getExpires() { return (int) (_absoluteExpires - System.currentTimeMillis()) / 1000; } public long getAbsoluteExpires() { return _absoluteExpires; } public boolean isExpired() { return (_absoluteExpires - System.currentTimeMillis()) <= 0; } public int compareTo(Binding b) { float f = b.getQ() - _q; if (f == 0) return b.hashCode() - hashCode(); else return (int) (f * 1000); } public float getQ() { return _q; } public void setQ(float q) { _q = q; } }
apache-2.0
jomarko/drools
drools-verifier/drools-verifier-core/src/test/java/org/drools/verifier/core/cache/inspectors/ConditionsInspectorTest.java
12025
/* * Copyright 2018 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.drools.verifier.core.cache.inspectors; import org.drools.verifier.core.cache.inspectors.condition.ComparableConditionInspector; import org.drools.verifier.core.cache.inspectors.condition.ConditionInspector; import org.drools.verifier.core.cache.inspectors.condition.ConditionsInspectorMultiMap; import org.drools.verifier.core.AnalyzerConfigurationMock; import org.drools.verifier.core.index.keys.Values; import org.drools.verifier.core.index.model.Column; import org.drools.verifier.core.index.model.Field; import org.drools.verifier.core.index.model.FieldCondition; import org.drools.verifier.core.index.model.ObjectField; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @RunWith(MockitoJUnitRunner.class) public class ConditionsInspectorTest { Field field; private AnalyzerConfigurationMock configurationMock; @Before public void setUp() throws Exception { configurationMock = new AnalyzerConfigurationMock(); field = new Field(new ObjectField("Person", "Integer", "age", configurationMock), "Person", "Integer", "age", configurationMock); } @Test public void testSubsume001() throws Exception { final ConditionsInspectorMultiMap a = getConditions(new ComparableConditionInspector<Integer>(new FieldCondition(field, mock(Column.class), "==", new Values<>(1), configurationMock), configurationMock)); final ConditionsInspectorMultiMap b = getConditions(new ComparableConditionInspector<Integer>(new FieldCondition(field, mock(Column.class), "==", new Values<>(1), configurationMock), configurationMock)); assertTrue(a.subsumes(b)); assertTrue(b.subsumes(a)); } @Test public void testSubsume002() throws Exception { final ConditionsInspectorMultiMap a = getConditions(new ComparableConditionInspector<Integer>(new FieldCondition(field, mock(Column.class), "==", new Values<>(1), configurationMock), configurationMock)); final ConditionsInspectorMultiMap b = getConditions(new ComparableConditionInspector<Integer>(new FieldCondition(field, mock(Column.class), "==", new Values<>(1), configurationMock), configurationMock), new ComparableConditionInspector<Integer>(new FieldCondition(new Field(mock(ObjectField.class), "Person", "Integer", "balance", configurationMock), mock(Column.class), "==", new Values<>(111111111), configurationMock), configurationMock)); assertFalse(a.subsumes(b)); assertTrue(b.subsumes(a)); } @Test public void testSubsume003() throws Exception { final Field nameField = new Field(new ObjectField("Person", "String", "name", configurationMock), "Person", "String", "name", configurationMock); final Field lastNameField = new Field(new ObjectField("Person", "String", "lastName", configurationMock), "Person", "String", "lastName", configurationMock); final ConditionsInspectorMultiMap a = getConditions(new ComparableConditionInspector<String>(new FieldCondition(nameField, mock(Column.class), "==", new Values<>("Toni"), configurationMock), configurationMock)); final ConditionsInspectorMultiMap b = getConditions(new ComparableConditionInspector<Integer>(new FieldCondition(field, mock(Column.class), "==", new Values<>(12), configurationMock), configurationMock), new ComparableConditionInspector<String>(new FieldCondition(nameField, mock(Column.class), "==", new Values<>("Toni"), configurationMock), configurationMock), new ComparableConditionInspector<String>(new FieldCondition(lastNameField, mock(Column.class), "==", new Values<>("Rikkola"), configurationMock), configurationMock)); assertFalse(a.subsumes(b)); assertTrue(b.subsumes(a)); } private ConditionsInspectorMultiMap getConditions(final ConditionInspector... numericIntegerConditions) { final ConditionsInspectorMultiMap conditionsInspector = new ConditionsInspectorMultiMap(configurationMock); for (final ConditionInspector inspector : numericIntegerConditions) { conditionsInspector.put(((ComparableConditionInspector) inspector).getField() .getObjectField(), inspector); } return conditionsInspector; } }
apache-2.0
Ali-Razmjoo/zaproxy
zap/src/main/java/org/zaproxy/zap/view/messagelocation/MessageLocationProducer.java
2121
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2015 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.view.messagelocation; import org.zaproxy.zap.model.MessageLocation; /** * A component capable of producing {@code MessageLocation}s, normally through the UI. * * @since 2.4.0 * @see MessageLocation * @see MessageLocationProducerFocusListener */ public interface MessageLocationProducer { /** * The type of {@code MessageLocation} that it can produce. * * @return the message location */ Class<? extends MessageLocation> getMessageLocationClass(); /** * Obtains the current selected location. * * @return the selected location */ MessageLocation getSelection(); /** * Adds the focus listener, starting to be notified of changes in the focus. * * @param focusListener the focus listener that will be removed */ void addFocusListener(MessageLocationProducerFocusListener focusListener); /** * Removes the focus listener. * * @param focusListener the focus listener that will be removed */ void removeFocusListener(MessageLocationProducerFocusListener focusListener); /** * Creates a {@code MessageLocationHighlightsManager} responsible to manage the highlights of * the message locations produced. * * @return the {@code MessageLocationHighlightsManager} */ MessageLocationHighlightsManager create(); }
apache-2.0
zzsoszz/springbootsearch
src/main/java/dinamica/util/StringUtil.java
23768
package dinamica.util; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.Map; import java.net.*; /** * Core-level framework class: String and Date basic utility methods. * <br><br> * Encapsulates utility methods for everyday programming tasks * with Strings, Dates and other common stuff. * <br> * Creation date: 18/09/2003<br> * Last Update: 18/09/2003<br> * (c) 2003 Martin Cordova<br> * This code is released under the LGPL license<br> * @author Martin Cordova (some code written by Carlos Pineda) */ public class StringUtil { /** * 字符串转换unicode */ public static String string2Unicode(String string) { StringBuffer unicode = new StringBuffer(); for (int i = 0; i < string.length(); i++) { // 取出每一个字符 char c = string.charAt(i); // 转换为unicode unicode.append("\\u" + Integer.toHexString(c)); } return unicode.toString(); } /** * unicode 转字符串 */ public static String unicode2String(String unicode) { StringBuffer string = new StringBuffer(); String[] hex = unicode.split("\\\\u"); for (int i = 1; i < hex.length; i++) { // 转换出每一个代码点 int data = Integer.parseInt(hex[i], 16); // 追加成string string.append((char) data); } return string.toString(); } /** * Replace ALL occurrences of [old value] with [new value]<br> * This method was written by Carlos Pineda. * @param source String to manipulate * @param pattern Old value * @param newText New value * @return String with replaced text */ public static String replace(String source, String pattern, String newText) { if (pattern == null || pattern.length() == 0 ) return source; StringBuffer buf = new StringBuffer(2*source.length()); int previndex=0; int index=0; int flen = pattern.length(); while (true) { index = source.indexOf(pattern, previndex); if (index == -1) { buf.append(source.substring(previndex)); break; } buf.append( source.substring(previndex, index)).append( newText ); previndex = index + flen; } return buf.toString(); } /** * Format date using a mask and the default locale * @param d Date object * @param format Date mask, like yyyy-MM-dd or any valid java format * @return String representing the formatted string * @throws Throwable */ public static String formatDate(java.util.Date d, String format) throws Throwable { SimpleDateFormat f = new SimpleDateFormat(); f.applyPattern(format); return f.format(d); } /** * Format date using a mask and locale * @param d Date object * @param format Date mask, like yyyy-MM-dd or any valid java format * @param loc Custom Locale * @return String representing the formatted string * @throws Throwable */ public static String formatDate(java.util.Date d, String format, Locale loc) throws Throwable { SimpleDateFormat f = new SimpleDateFormat(format, loc); return f.format(d); } /** * Create a java.util.Date object from a String value and a format mask.<br> * The java date formats are supported, for more information please consult the * reference guide for the class <a href="http://java.sun.com/j2se/1.4.1/docs/api/java/text/SimpleDateFormat.html">SimpleDateFormat</a>.<br> * <br> * Sample code:<br> * <pre> * java.util.Date d = StringUtil.getDateObject("2003-12-07 17:00:00","yyyy-MM-dd HH:mm:ss"); * </pre> * @param dateValue A String containg a valid date corresponding to dateFormat mask * @param dateFormat The date format used to represent the date in dateValue * @return A java.util.Date object representing the dateValue parameter * @throws Throwable if dateValue is not represented in dateFormat */ public static java.util.Date getDateObject(String dateValue, String dateFormat) throws Throwable { SimpleDateFormat x = new SimpleDateFormat(dateFormat); x.setLenient(false); return x.parse(dateValue); } /** * Format a number using a valid Java format mask and the default Locale * @param value Double, Integer or another numeric value * @param numberFormat Java numeric format mask like #,##0.00 * @return String representing a formatted number acording to the numberFormat * @throws Throwable */ public static String formatNumber(Object value, String numberFormat) throws Throwable { DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(); fmt.applyPattern(numberFormat); return fmt.format(value); } /** * Format a number using a valid Java format mask and a custom Locale * @param value Double, Integer or another numeric value * @param numberFormat Java numeric format mask like #,##0.00 * @param loc Custom Locale to use when formatting the number * @return String representing a formatted number acording to the numberFormat * @throws Throwable */ public static String formatNumber(Object value, String numberFormat, Locale loc) throws Throwable { DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(loc); fmt.applyPattern(numberFormat); return fmt.format(value); } /** * Create an array of items from a string with delimiters to separate the items. * This is a very simple wrapper around the native String.split method * @param s String to split or separate in its parts * @param separator Delimiter string, like a pipe or a tabulator * @return Array of strings containing the separated items */ public static String[] split(String s, String separator) { separator = "\\" + separator; return s.split(separator); } /** * Loads a text resource stored into the Web Application context paths * @param path Path to the resource * @return String containing the resource contents * @throws Exception */ public static String getResource(javax.servlet.ServletContext ctx, String path) throws Throwable { return getResource(ctx, path, System.getProperty("file.encoding", "ISO8859_1")); } /** * Append message to file, this method is usually * used to save log messages * @param path File name * @param message String to append to file */ public static synchronized void saveMessage(String path, String message) { FileOutputStream fos = null; PrintWriter pw = null; try { fos = new FileOutputStream(new File(path), true); pw = new PrintWriter(fos, false); pw.println(message); } catch (IOException e) { try { String d = StringUtil.formatDate(new java.util.Date(), "yyyy-MM-dd HH:mm:ss"); System.err.println("ERROR [dinamica.StringUtil.saveMessage@" + d + "]: " + e.getMessage()); } catch (Throwable e1) { } } finally { try { if (pw != null) pw.close(); if (fos != null) fos.close(); } catch (IOException e) { } } } /** * Retrieve a text-based document using HTTP GET method.<br> * May be used to retrieve XML documents, news feeds, etc. * @param url A valid URL * @param logStdout if TRUE then this method will print * a tracelog via STDOUT * @return a String containing the whole document * @throws Throwable */ public static String httpGet(String url, boolean logStdout) throws Throwable { final int bufferSize = 4096; BufferedReader br = null; HttpURLConnection urlc = null; StringBuffer buffer = new StringBuffer(); URL page = new URL(url); try { if (logStdout) System.err.println("Waiting for reply...:" + url); urlc = (HttpURLConnection)page.openConnection(); urlc.setUseCaches(false); if (logStdout) { System.err.println("Content-type = " + urlc.getContentType()); System.err.println("Content-length = " + urlc.getContentLength()); System.err.println("Response-code = " + urlc.getResponseCode()); System.err.println("Response-message = " + urlc.getResponseMessage()); } int retCode = urlc.getResponseCode(); String retMsg = urlc.getResponseMessage(); if (retCode>=400) throw new Throwable("HTTP Error: " + retCode + " - " + retMsg + " - URL:" + url); br = new BufferedReader(new InputStreamReader(urlc.getInputStream()), bufferSize); char buf[] = new char[bufferSize]; int bytesRead = 0; while (bytesRead!=-1) { bytesRead = br.read(buf); if (bytesRead>0) buffer.append(buf,0,bytesRead); } if (logStdout) { System.err.println("Document received."); } return buffer.toString(); } catch (Throwable e) { throw e; } finally { if (br != null) br.close(); if (urlc!=null) urlc.disconnect(); } } /** * Loads a text resource stored into the Web Application context paths * <br> * PATCH 2005-02-17 (v2.0.3) - encoding support * @param ctx Servlet context * @param path Path to the resource * @param encoding Canonical name of the encoding to be used to read the resource * @return String containing the resource contents * @throws Exception */ public static String getResource(javax.servlet.ServletContext ctx, String path, String encoding) throws Throwable { StringBuffer buf = new StringBuffer(5000); byte[] data = new byte[5000]; InputStream in = null; in = ctx.getResourceAsStream(path); try { if (in!=null) { while (true) { int len = in.read(data); if (len!=-1) { buf.append( new String(data, 0, len, encoding) ); } else { break; } } return buf.toString(); } else { throw new Throwable("Invalid path to resource: " + path); } } catch (Throwable e) { throw e; } finally { if (in!=null) { try{ in.close(); } catch (Exception e){} } } } /** * 检测字符串是否为空 * * @param str * 需要检测的字符组 * @return true/false */ public final static boolean isEmptyOrWhitespace(String str) { if (str == null || str.trim().length() == 0) { return true; } else { return false; } } /** * MD5加密 * * @param 传入需要加密的字符串 * @return */ public final static String md5(String str) { if (str == null || str.length() == 0) { return ""; } else { StringBuffer sb = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(str.getBytes()); byte[] md5 = algorithm.digest(); String singleByteHex = ""; for (int i = 0; i < md5.length; i++) { singleByteHex = Integer.toHexString(0xFF & md5[i]); if (singleByteHex.length() == 1) { sb.append("0"); } sb.append(singleByteHex.toUpperCase()); } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return sb.toString(); } } /** * 过滤注入字符 * * @param str * 需要过滤的字符串 * @return */ public final static String inSql(String str) { return str.replaceAll(".*([';]+|(--)+).*", ""); } /** * 字符串转换到时间格式 * @param dateValue 需要转换的字符串 * @param strFormat 需要格式的目标字符串 举例 yyyy-MM-dd * @return 返回转换后的时间 */ public static Date parseDate(String dateValue, String strFormat) { if (dateValue == null) return null; if (strFormat == null) strFormat = "yyyy-MM-dd"; SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat); Date newDate = null; try { newDate = dateFormat.parse(dateValue); } catch (ParseException pe) { newDate = null; } return newDate; } public static Date strToDate(String date) { if (date == null) { return null; } Date realDate = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date newDate = sdf.parse(date); String str = sdf.format(newDate); realDate = sdf.parse(str); } catch (ParseException e) { e.printStackTrace(); } return realDate; } public static String getDateStr(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); Date date1 = new Date(); String date = sdf.format(date1); return date; } public static String warpDataForValue(String field) { if(field==null) { return " null "; } return field.toString(); } public static String warpData(String field) { if(field==null) { return " null "; } return field.toString(); } public static String warpData(Float field) { if(field==null) { return " null "; } return field.toString(); } public static String warpData(Double field) { if(field==null) { return " null "; } return field.toString(); } public static String warpData(Integer field) { if(field==null) { return " null "; } return field.toString(); } public static String warpData(Date field) { if(field==null) { return " null "; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date1 = new Date(); String date = sdf.format(date1); return " to_date('"+date+"','yyyy-MM-dd HH:mm:ss') "; } public static String nullToEmpty(Object field) { return field==null?"":field.toString(); } public static void warpDataForWhere(StringBuffer sql,String fieldname,String field) { if(field!=null) { sql.append("and "+fieldname+"='"+field+"'"); } } public static void warpDataForQuery(StringBuffer sql,String fieldname,Float field) { if(field!=null) { sql.append("and "+fieldname+"="+field); } } public static void warpDataForQuery(StringBuffer sql,String fieldname,Long field) { if(field!=null) { sql.append("and "+fieldname+"="+field); } } public static void warpDataForQuery(StringBuffer sql,String fieldname,Double field) { if(field!=null) { sql.append("and "+fieldname+"="+field); } } public static void warpDataForQuery(StringBuffer sql,String fieldname,Integer field) { if(field!=null) { sql.append("and "+fieldname+"="+field); } } public static void warpDataForQuery(StringBuffer sql,String fieldname,Date field) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date1 = new Date(); String date = sdf.format(date1); if(field!=null) { sql.append("and "+fieldname+"="+" to_date('"+date+"','yyyy-MM-dd HH:mm:ss') "); } } /* public static String warpData(Float field) { return field.toString(); } public static String warpData(Long field) { return field.toString(); } public static String warpData(Double field) { return field.toString(); } public static String warpData(Integer field) { return field.toString(); } public static String warpData(Date field) { if(field==null) { return " null "; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date1 = new Date(); String date = sdf.format(date1); return " to_date('"+field+"','yyyy-MM-dd HH:mm:ss') "; } */ public static String cutString(String s,int len) { String t = s.length() > len ? s.substring(1,len-1) : s; return t; } /** * 日期格式化 * @param strMat 格式化后的格式 yyyy-MM-dd HH:mm:ss 或者yyyy-MM-dd * @param strDate 需要格式化的日期 * @return */ public static Date getFormatDate(String strMat,String strDate){ if("yyyy-MM-dd HH:mm:ss".equalsIgnoreCase(strMat) && strDate.length() == 10){ strDate = strDate+" 00:00:00"; } SimpleDateFormat sdf = new SimpleDateFormat(strMat); try { return sdf.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 日期格式化 默认格式化为 yyyy-MM-dd HH:mm:ss * @param strDate 需要格式化的日期 * @return */ public static Date getFormatDate(String strDate){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return sdf.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 日期格式化为字符串 * @param strMat 格式化后的字符串格式 * @param strDate 日期 * @return */ public static String getFormatDate(String strMat,Date strDate){ if(strDate == null){ return null; }else{ SimpleDateFormat sdf = new SimpleDateFormat(strMat); return sdf.format(strDate); } } /** * 直接获取"yyyy-MM-dd HH:mm:ss"的时间 * @return */ public static String getDateStr(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date1 = new Date(); String date = sdf.format(date1); return date; } /** * 日期加减多少天 * @param strDate 日期 * @param d 加减的天数 如 1或-1 * @return */ public static String dateCpp(String strDate,int d){ Calendar cal3 = Calendar.getInstance(); cal3.setTime(getFormatDate("yyyy-MM-dd",strDate)); cal3.add(cal3.DATE, d); return getFormatDate("yyyy-MM-dd",cal3.getTime()); } public static String truncate(String str,int len) { if(str!=null) { if(str.length()>len) { return str.substring(0, len); } } return str; } public static String upperCaseFirst(String str) { if(str==null && "".equals(str.trim())) { return str; } char c = str.charAt(0);// 大写第一个字母 return String.valueOf(c).toUpperCase().concat(str.substring(1)); } public static String lowerCaseFirst(String str) { if(str==null && "".equals(str.trim())) { return str; } char c = str.charAt(0);// 大写第一个字母 return String.valueOf(c).toLowerCase().concat(str.substring(1)); } public static String removeLastWith(String str,String endstr) { if(str.toLowerCase().endsWith(endstr.toLowerCase())) { return str.substring(0,str.toLowerCase().lastIndexOf(endstr.toLowerCase())); } return str; } /* * String pattern = "{:name} - {:age} - {:name}"; Map<String,Object> arguments = new HashMap<String, Object>(){{ put("name", "tom"); put("age", 23); String msg = MyMessageFormat.format(pattern, arguments); //System.out.println(msg); }}; */ public static String format(String pattern, Map<String,Object> arguments){ String formatedStr = pattern; for (String key : arguments.keySet()) { formatedStr = formatedStr.replaceAll("\\{:"+key+"\\}", arguments.get(key).toString()); } return formatedStr; } public static String format2(String pattern, Map<String,String> arguments){ String formatedStr = pattern; for (String key : arguments.keySet()) { formatedStr = formatedStr.replaceAll("\\{"+key+"\\}", arguments.get(key).toString()); } return formatedStr; } /** * 将字符串转成unicode * * @param str * 待转字符串 * @return unicode字符串 */ public static String stringToUnicode(String str) { str = (str == null ? "" : str); String tmp; StringBuffer sb = new StringBuffer(1000); char c; int i, j; sb.setLength(0); for (i = 0; i < str.length(); i++) { c = str.charAt(i); sb.append("\\u"); j = (c >>> 8); // 取出高8位 tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append("0"); sb.append(tmp); j = (c & 0xFF); // 取出低8位 tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append("0"); sb.append(tmp); } return (new String(sb)); } /** * 将unicode 字符串 * * @param str * 待转字符串 * @return 普通字符串 */ public static String unicodeToString(String str) { str = (str == null ? "" : str); if (str.indexOf("\\u") == -1)// 如果不是unicode码则原样返回 return str; StringBuffer sb = new StringBuffer(1000); for (int i = 0; i < str.length() - 6;) { String strTemp = str.substring(i, i + 6); String value = strTemp.substring(2); int c = 0; for (int j = 0; j < value.length(); j++) { char tempChar = value.charAt(j); int t = 0; switch (tempChar) { case 'a': t = 10; break; case 'b': t = 11; break; case 'c': t = 12; break; case 'd': t = 13; break; case 'e': t = 14; break; case 'f': t = 15; break; default: t = tempChar - 48; break; } c += t * ((int) Math.pow(16, (value.length() - j - 1))); } sb.append((char) c); i = i + 6; } return sb.toString(); } //支持全角空格 public static boolean isBlank(CharSequence str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } public static boolean isWhitespace(char ch) { if (ch == '\u00a0') { return true; } if (Character.isWhitespace(ch)) { return true; } return false; } //取得最后几位 public static String getLast(String str,int count) { if(str==null) { return null; } System.out.println(str.length()); if(str.length()>count) { System.out.println(str.length()-count-1); return str.substring(str.length()-count,str.length()); } return str; } public static String[] splitByLastSeparator(String s,String separator) { int i = s.lastIndexOf(separator); String[] a = {s.substring(0, i), s.substring(i+1)}; return a; } public static void main(String args[]) { //System.out.println(StringUtil.getLast("60222222222211111234",4)); // //System.out.println(StringUtil.removeLastWith("aaaa,b","b")); // //System.out.println(truncate("国内发行银联卡 万事达(Master) 威士(VISA) 运通(AMEX) 大来(Diners Club) JCB卡",3)); // System.out.print(upperCaseFirst("aaaC")); // try { // //System.out.println(StringUtil.formatDate(new Date(),"yyyy-mm-dd hh:mm:ss")); // } catch (Throwable e) { // e.printStackTrace(); // } //System.out.print(StringUtil.stringToUnicode("璧山县 ").replaceAll("[\\x00a0]","")); //System.out.println("璧山县 ".replaceAll("[\\u00a0]","")); //System.out.println(StringUtil.isBlank(" ")); // String str[]=StringUtil.splitByLastSeparator("refund_id_01", "_"); // for(int i=0;i<str.length;i++) // { // System.out.println(str[i]); // } // String test = "最代码网站地址:www.zuidaima.com"; String unicode = string2Unicode(test); String string = unicode2String(unicode) ; System.out.println(unicode); System.out.println(string); } //java过滤特殊字符串 // http://p-x1984.iteye.com/blog/418132 // \\ 反斜杠 // \t 间隔 \u0009 // \n 换行 \u000A // \r 回车 \u000D // \d 数字 等价于[0-9] // \D 非数字 等价于[^0-9] // \s 空白符号 [\t\n\x0B\f\r] // \S 非空白符号 [^\t\n\x0B\f\r] // \w 单独字符 [a-zA-Z_0-9] // \W 非单独字符 [^a-zA-Z_0-9] // \f 换页符 // \e Escape // \b 一个单词的边界 // \B 一个非单词的边界 // \G 前一个匹配的结束 }
apache-2.0
EvilMcJerkface/alluxio
core/common/src/test/java/alluxio/util/io/ByteIOUtilsTest.java
2440
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.util.io; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * Unit tests for {@link ByteIOUtils}. */ public final class ByteIOUtilsTest { private byte[] mBuf = new byte[1024]; /** * Tests {@link ByteIOUtils#writeByte} and {@link ByteIOUtils#readByte}. */ @Test public void readWriteByte() { long[] values = new long[] {0, 1, 2, 0x7f, 0xff}; for (long i : values) { byte v = (byte) i; ByteIOUtils.writeByte(mBuf, 0, v); assertEquals(v, ByteIOUtils.readByte(mBuf, 0)); } } /** * Tests {@link ByteIOUtils#writeShort} and {@link ByteIOUtils#readShort}. */ @Test public void readWriteShort() { long[] values = new long[] {0, 1, 2, 0x7f, 0xff, 0xffff}; for (long i : values) { short v = (short) i; ByteIOUtils.writeShort(mBuf, 0, v); assertEquals(v, ByteIOUtils.readShort(mBuf, 0)); ByteIOUtils.writeShort(mBuf, 1, v); assertEquals(v, ByteIOUtils.readShort(mBuf, 1)); } } /** * Tests {@link ByteIOUtils#writeInt} and {@link ByteIOUtils#readInt}. */ @Test public void readWriteInt() { long[] values = new long[] {0, 1, 2, 0x7f, 0xff, 0xffff, 0xffffff, 0xffffffff}; for (long i : values) { int v = (int) i; for (int pos = 0; pos < 4; pos++) { ByteIOUtils.writeInt(mBuf, pos, v); assertEquals(v, ByteIOUtils.readInt(mBuf, pos)); } } } /** * Tests {@link ByteIOUtils#writeLong} and {@link ByteIOUtils#readLong}. */ @Test public void readWriteLong() { long[] values = new long[] {0, 1, 2, 0x7f, 0xff, 0xffff, 0xffffff, 0xffffffff, 0xffffffffffL, 0xffffffffffffL, 0xffffffffffffffL, 0xffffffffffffffffL}; for (long v : values) { for (int pos = 0; pos < 8; pos++) { ByteIOUtils.writeLong(mBuf, 0, v); assertEquals(v, ByteIOUtils.readLong(mBuf, 0)); } } } }
apache-2.0
manuel-palacio/keycloak
services/src/main/java/org/keycloak/authorization/admin/representation/PolicyEvaluationRequest.java
3014
/* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.keycloak.authorization.admin.representation; import java.util.List; import java.util.Map; import java.util.Set; /** * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a> */ public class PolicyEvaluationRequest { private Map<String, Map<String, String>> context; private List<Resource> resources; private String clientId; private String userId; private List<String> roleIds; private boolean entitlements; public Map<String, Map<String, String>> getContext() { return this.context; } public void setContext(Map<String, Map<String, String>> context) { this.context = context; } public List<Resource> getResources() { return this.resources; } public void setResources(List<Resource> resources) { this.resources = resources; } public String getClientId() { return this.clientId; } public void setClientId(final String clientId) { this.clientId = clientId; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } public List<String> getRoleIds() { return this.roleIds; } public void setRoleIds(List<String> roleIds) { this.roleIds = roleIds; } public boolean isEntitlements() { return entitlements; } public void setEntitlements(boolean entitlements) { this.entitlements = entitlements; } public static class Resource { private String id; private String name; private String type; private Set<String> scopes; public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(final String type) { this.type = type; } public Set<String> getScopes() { return scopes; } public void setScopes(final Set<String> scopes) { this.scopes = scopes; } } }
apache-2.0
goodwinnk/intellij-community
platform/analysis-api/src/com/intellij/codeInspection/reference/RefGraphAnnotator.java
4489
/* * Copyright 2000-2009 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 com.intellij.codeInspection.reference; import com.intellij.psi.PsiElement; /** * Callback which gets called while a reference graph is being built during a global * inspection run. * * @author anna * @since 6.0 * @see com.intellij.codeInspection.GlobalInspectionTool#getAnnotator */ public abstract class RefGraphAnnotator { /** * Called before the references to the specified element have been collected. * * @param refElement the element the references to which are about to be collected. */ public void onInitialize(RefElement refElement) { } /** * Called after the references to the specified element have been collected. * * @param refElement the element the references to which have been collected. */ public void onReferencesBuild(RefElement refElement){ } /** * Called when a reference to the specified element has been found. * * @param refWhat the referenced element. * @param refFrom the referencing element. * @param referencedFromClassInitializer if true, {@code refFrom} is a class and the reference * has been found in its initializer block. */ public void onMarkReferenced(RefElement refWhat, RefElement refFrom, boolean referencedFromClassInitializer) { } /** * Called when a reference to the specified element has been found. * * @param refWhat the referenced element. * @param refFrom the referencing element. * @param referencedFromClassInitializer if true, {@code refFrom} is a class and the reference * has been found in its initializer block. * @param forReading used for reading * @param forWriting used for writing * @param referenceElement reference element in refFrom */ public void onMarkReferenced(RefElement refWhat, RefElement refFrom, boolean referencedFromClassInitializer, boolean forReading, boolean forWriting, PsiElement referenceElement) { onMarkReferenced(refWhat, refFrom, referencedFromClassInitializer, forReading, forWriting); } /** * Called when a reference to the specified element has been found. * * @param refWhat the referenced element. * @param refFrom the referencing element. * @param referencedFromClassInitializer if true, {@code refFrom} is a class and the reference * has been found in its initializer block. * @param forReading used for reading * @param forWriting used for writing */ public void onMarkReferenced(RefElement refWhat, RefElement refFrom, boolean referencedFromClassInitializer, boolean forReading, boolean forWriting) { onMarkReferenced(refWhat, refFrom, referencedFromClassInitializer); } /** * Called when 'what' element doesn't belong to the selected scope. * @param what the referenced element * @param from the referencing element * @param referencedFromClassInitializer if true, {@code refFrom} is a class and the reference * has been found in its initializer block. */ public void onMarkReferenced(PsiElement what, PsiElement from, boolean referencedFromClassInitializer) {} }
apache-2.0
shakamunyi/drill
exec/java-exec/src/main/codegen/templates/Decimal/DecimalAggrTypeFunctions2.java
4703
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.drill.exec.expr.annotations.Workspace; <@pp.dropOutputFile /> <#list decimalaggrtypes2.aggrtypes as aggrtype> <@pp.changeOutputFile name="/org/apache/drill/exec/expr/fn/impl/gaggr/Decimal${aggrtype.className}Functions.java" /> <#include "/@includes/license.ftl" /> <#-- A utility class that is used to generate java code for aggr functions for decimal data type that maintain a single --> <#-- running counter to hold the result. This includes: MIN, MAX, COUNT. --> /* * This class is automatically generated from AggrTypeFunctions1.tdd using FreeMarker. */ package org.apache.drill.exec.expr.fn.impl.gaggr; <#include "/@includes/vv_imports.ftl" /> import org.apache.drill.exec.expr.DrillAggFunc; import org.apache.drill.exec.expr.annotations.FunctionTemplate; import org.apache.drill.exec.expr.annotations.FunctionTemplate.FunctionScope; import org.apache.drill.exec.expr.annotations.Output; import org.apache.drill.exec.expr.annotations.Param; import org.apache.drill.exec.expr.annotations.Workspace; import org.apache.drill.exec.expr.holders.*; import javax.inject.Inject; import io.netty.buffer.DrillBuf; import org.apache.drill.exec.record.RecordBatch; import io.netty.buffer.ByteBuf; /* * This class is generated using freemarker and the ${.template_name} template. */ @SuppressWarnings("unused") public class Decimal${aggrtype.className}Functions { <#list aggrtype.types as type> @FunctionTemplate(name = "${aggrtype.funcName}", scope = FunctionTemplate.FunctionScope.POINT_AGGREGATE, returnType = FunctionTemplate.ReturnType.DECIMAL_SUM_AGGREGATE) public static class ${type.inputType}${aggrtype.className} implements DrillAggFunc{ @Param ${type.inputType}Holder in; @Inject DrillBuf buffer; @Workspace ObjectHolder value; @Workspace ${type.countRunningType}Holder count; @Workspace IntHolder outputScale; @Output ${type.outputType}Holder out; public void setup() { buffer.reallocIfNeeded(${type.outputType}Holder.WIDTH); value = new ObjectHolder(); value.obj = java.math.BigDecimal.ZERO; count = new ${type.countRunningType}Holder(); count.value = 0; outputScale = new IntHolder(); outputScale.value = Integer.MIN_VALUE; } @Override public void add() { <#if type.inputType?starts_with("Nullable")> sout: { if (in.isSet == 0) { // processing nullable input and the value is null, so don't do anything... break sout; } </#if> count.value++; <#if type.inputType.endsWith("Decimal9") || type.inputType.endsWith("Decimal18")> java.math.BigDecimal currentValue = org.apache.drill.exec.util.DecimalUtility.getBigDecimalFromPrimitiveTypes(in.value, in.scale, in.precision); <#else> java.math.BigDecimal currentValue = org.apache.drill.exec.util.DecimalUtility.getBigDecimalFromSparse(in.buffer, in.start, in.nDecimalDigits, in.scale); </#if> value.obj = ((java.math.BigDecimal)(value.obj)).add(currentValue); if (outputScale.value == Integer.MIN_VALUE) { outputScale.value = in.scale; } <#if type.inputType?starts_with("Nullable")> } // end of sout block </#if> } @Override public void output() { out.buffer = buffer; out.start = 0; out.scale = outputScale.value; out.precision = 38; java.math.BigDecimal average = ((java.math.BigDecimal)(value.obj)).divide(java.math.BigDecimal.valueOf(count.value, 0), out.scale, java.math.BigDecimal.ROUND_HALF_UP); org.apache.drill.exec.util.DecimalUtility.getSparseFromBigDecimal(average, out.buffer, out.start, out.scale, out.precision, out.nDecimalDigits); } @Override public void reset() { value = new ObjectHolder(); value.obj = java.math.BigDecimal.ZERO; count = new ${type.countRunningType}Holder(); count.value = 0; outputScale = new IntHolder(); outputScale.value = Integer.MIN_VALUE; } } </#list> } </#list>
apache-2.0
paulk-asert/groovy
subprojects/groovy-jsr223/src/main/java/org/codehaus/groovy/jsr223/GroovyCompiledScript.java
3642
/* * The initial contribution was derived from the reference implementation * developed by Sun in consultation with the Groovy community. The reference * implementation had the following license header: * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: Redistributions of source code * must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. Neither the name of the Sun Microsystems nor the names of * is contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Subsequent modifications by the Groovy community have been done under the Apache License v2: * * 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.codehaus.groovy.jsr223; import javax.script.CompiledScript; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptException; /** * Used to represent compiled Groovy scripts. Such scripts may be executed repeatedly * by Groovy's <code>ScriptEngine</code> using the <code>eval</code> method without reparsing overheads. * * Adapted from original by Mike Grogan and A. Sundararajan */ public class GroovyCompiledScript extends CompiledScript { private final GroovyScriptEngineImpl engine; private final Class<?> clasz; public GroovyCompiledScript(GroovyScriptEngineImpl engine, Class<?> clazz) { this.engine = engine; this.clasz = clazz; } public Object eval(ScriptContext context) throws ScriptException { return engine.eval(clasz, context); } public ScriptEngine getEngine() { return engine; } }
apache-2.0
0359xiaodong/double-espresso
espresso/src/main/java/com/google/android/apps/common/testing/ui/espresso/base/DefaultFailureHandler.java
2920
package com.google.android.apps.common.testing.ui.espresso.base; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Throwables.propagate; import com.google.android.apps.common.testing.testrunner.inject.TargetContext; import com.google.android.apps.common.testing.ui.espresso.EspressoException; import com.google.android.apps.common.testing.ui.espresso.FailureHandler; import com.google.android.apps.common.testing.ui.espresso.PerformException; import android.content.Context; import android.view.View; import junit.framework.AssertionFailedError; import org.hamcrest.Matcher; import java.util.concurrent.atomic.AtomicInteger; import javax.inject.Inject; /** * Espresso's default {@link FailureHandler}. If this does not fit your needs, feel free to provide * your own implementation via Espresso.setFailureHandler(FailureHandler). */ public final class DefaultFailureHandler implements FailureHandler { private static final AtomicInteger failureCount = new AtomicInteger(0); private final Context appContext; @Inject public DefaultFailureHandler(@TargetContext Context appContext) { this.appContext = checkNotNull(appContext); } @Override public void handle(Throwable error, Matcher<View> viewMatcher) { if (error instanceof EspressoException || error instanceof AssertionFailedError || error instanceof AssertionError) { throw propagate(getUserFriendlyError(error, viewMatcher)); } else { throw propagate(error); } } /** * When the error is coming from espresso, it is more user friendly to: * 1. propagate assertions as assertions * 2. swap the stack trace of the error to that of current thread (which will show * directly where the actual problem is) */ private Throwable getUserFriendlyError(Throwable error, Matcher<View> viewMatcher) { if (error instanceof PerformException) { // Re-throw the exception with the viewMatcher (used to locate the view) as the view // description (makes the error more readable). The reason we do this here: not all creators // of PerformException have access to the viewMatcher. throw new PerformException.Builder() .from((PerformException) error) .withViewDescription(viewMatcher.toString()) .build(); } if (error instanceof AssertionError) { // reports Failure instead of Error. // assertThat(...) throws an AssertionFailedError. error = new AssertionFailedWithCauseError(error.getMessage(), error); } error.setStackTrace(Thread.currentThread().getStackTrace()); return error; } private static final class AssertionFailedWithCauseError extends AssertionFailedError { /* junit hides the cause constructor. */ public AssertionFailedWithCauseError(String message, Throwable cause) { super(message); initCause(cause); } } }
apache-2.0
Unixcision/show-java
app/src/main/java/org/jf/dexlib2/immutable/instruction/ImmutableInstruction31c.java
3350
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.immutable.instruction; import org.jf.dexlib2.Format; import org.jf.dexlib2.Opcode; import org.jf.dexlib2.iface.instruction.formats.Instruction31c; import org.jf.dexlib2.iface.reference.Reference; import org.jf.dexlib2.immutable.reference.ImmutableReference; import org.jf.dexlib2.immutable.reference.ImmutableReferenceFactory; import org.jf.dexlib2.util.Preconditions; import javax.annotation.Nonnull; public class ImmutableInstruction31c extends ImmutableInstruction implements Instruction31c { public static final Format FORMAT = Format.Format31c; protected final int registerA; @Nonnull protected final ImmutableReference reference; public ImmutableInstruction31c(@Nonnull Opcode opcode, int registerA, @Nonnull Reference reference) { super(opcode); this.registerA = Preconditions.checkByteRegister(registerA); this.reference = ImmutableReferenceFactory.of(opcode.referenceType, reference); } public static ImmutableInstruction31c of(Instruction31c instruction) { if (instruction instanceof ImmutableInstruction31c) { return (ImmutableInstruction31c) instruction; } return new ImmutableInstruction31c( instruction.getOpcode(), instruction.getRegisterA(), instruction.getReference()); } @Override public int getRegisterA() { return registerA; } @Nonnull @Override public ImmutableReference getReference() { return reference; } @Override public int getReferenceType() { return opcode.referenceType; } @Override public Format getFormat() { return FORMAT; } }
apache-2.0
ruks/geowave
core/geotime/src/main/java/mil/nga/giat/geowave/core/geotime/store/field/GeometryArraySerializationProvider.java
1371
package mil.nga.giat.geowave.core.geotime.store.field; import mil.nga.giat.geowave.core.geotime.store.field.GeometrySerializationProvider.GeometryReader; import mil.nga.giat.geowave.core.geotime.store.field.GeometrySerializationProvider.GeometryWriter; import mil.nga.giat.geowave.core.store.data.field.FieldReader; import mil.nga.giat.geowave.core.store.data.field.FieldSerializationProviderSpi; import mil.nga.giat.geowave.core.store.data.field.FieldWriter; import mil.nga.giat.geowave.core.store.data.field.ArrayReader.VariableSizeObjectArrayReader; import mil.nga.giat.geowave.core.store.data.field.ArrayWriter.VariableSizeObjectArrayWriter; import com.vividsolutions.jts.geom.Geometry; public class GeometryArraySerializationProvider implements FieldSerializationProviderSpi<Geometry[]> { @Override public FieldReader<Geometry[]> getFieldReader() { return new GeometryArrayReader(); } @Override public FieldWriter<Object, Geometry[]> getFieldWriter() { return new GeometryArrayWriter(); } private static class GeometryArrayReader extends VariableSizeObjectArrayReader<Geometry> { public GeometryArrayReader() { super( new GeometryReader()); } } private static class GeometryArrayWriter extends VariableSizeObjectArrayWriter<Object, Geometry> { public GeometryArrayWriter() { super( new GeometryWriter()); } } }
apache-2.0
psiinon/zaproxy
zap/src/main/java/org/zaproxy/zap/view/PersistSessionDialog.java
8680
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2015 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.view; import java.awt.Frame; import java.awt.GridBagLayout; import java.awt.HeadlessException; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.AbstractDialog; import org.zaproxy.zap.extension.help.ExtensionHelp; public class PersistSessionDialog extends AbstractDialog implements ActionListener { private static final long serialVersionUID = 1L; private JPanel jPanel = null; private JButton startSessionButton = null; private JRadioButton persistRadioButton = null; private JRadioButton timestampRadioButton = null; private JRadioButton temporaryRadioButton = null; private JCheckBox dontAskAgainCheckbox = null; /** * Constructs a modal {@code PersistSessionDialog} with the given owner. * * @param owner the {@code Frame} from which the dialog is displayed * @throws HeadlessException when {@code GraphicsEnvironment.isHeadless()} returns {@code true} */ public PersistSessionDialog(Frame owner) { super(owner, true); this.setModalityType(ModalityType.DOCUMENT_MODAL); initialize(); } /** This method initializes this */ private void initialize() { this.setContentPane(getJPanel()); this.pack(); // Disable the escape key - they have to make a choice! getRootPane().getActionMap().put("ESCAPE", null); } /** * This method initializes jPanel * * @return javax.swing.JPanel */ private JPanel getJPanel() { if (jPanel == null) { jPanel = new JPanel(); jPanel.setLayout(new GridBagLayout()); JLabel question = new JLabel(Constant.messages.getString("database.newsession.question")); jPanel.add(question, LayoutHelper.getGBC(0, 0, 2, 1.0D, new Insets(4, 4, 4, 4))); jPanel.add( this.getTimestampRadioButton(), LayoutHelper.getGBC(0, 1, 2, 1.0D, new Insets(4, 4, 4, 4))); jPanel.add( this.getPersistRadioButton(), LayoutHelper.getGBC(0, 3, 2, 1.0D, new Insets(4, 4, 4, 4))); jPanel.add( this.getTemporaryRadioButton(), LayoutHelper.getGBC(0, 5, 2, 1.0D, new Insets(4, 4, 4, 4))); ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(this.getTimestampRadioButton()); buttonGroup.add(this.getPersistRadioButton()); buttonGroup.add(this.getTemporaryRadioButton()); jPanel.add(new JLabel(), LayoutHelper.getGBC(0, 6, 2, 1.0D, 1.0D)); // Spacer jPanel.add( getDontAskAgainCheckbox(), LayoutHelper.getGBC(0, 7, 2, 1.0D, new Insets(4, 4, 4, 4))); jPanel.add( new JLabel(Constant.messages.getString("database.newsession.prompt.note")), LayoutHelper.getGBC(0, 8, 2, 1.0D, new Insets(4, 4, 4, 4))); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridBagLayout()); JButton helpButton = new JButton(Constant.messages.getString("menu.help")); helpButton.setToolTipText(Constant.messages.getString("help.dialog.button.tooltip")); helpButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ExtensionHelp.showHelp("ui.dialogs.persistsession"); } }); buttonPanel.add(helpButton, LayoutHelper.getGBC(0, 0, 1, 0.0D, new Insets(4, 4, 4, 4))); buttonPanel.add( new JLabel(), LayoutHelper.getGBC(1, 0, 1, 1.0D, new Insets(4, 4, 4, 4))); // Spacer buttonPanel.add( getStartSessionButton(), LayoutHelper.getGBC(2, 0, 1, 0.0D, new Insets(4, 4, 4, 4))); jPanel.add(buttonPanel, LayoutHelper.getGBC(0, 20, 2, 1.0D, new Insets(4, 4, 4, 4))); } return jPanel; } private JRadioButton getPersistRadioButton() { if (persistRadioButton == null) { persistRadioButton = new JRadioButton(Constant.messages.getString("database.newsession.userspec")); persistRadioButton.addActionListener(this); } return persistRadioButton; } private JRadioButton getTimestampRadioButton() { if (timestampRadioButton == null) { timestampRadioButton = new JRadioButton( Constant.messages.getString("database.newsession.timestamped")); timestampRadioButton.addActionListener(this); } return timestampRadioButton; } private JRadioButton getTemporaryRadioButton() { if (temporaryRadioButton == null) { temporaryRadioButton = new JRadioButton(Constant.messages.getString("database.newsession.temporary")); temporaryRadioButton.addActionListener(this); } return temporaryRadioButton; } private JCheckBox getDontAskAgainCheckbox() { if (dontAskAgainCheckbox == null) { dontAskAgainCheckbox = new JCheckBox(Constant.messages.getString("database.newsession.prompt.label")); } return dontAskAgainCheckbox; } public boolean isPersistChosen() { return this.getPersistRadioButton().isSelected(); } public void setPersistChosen() { this.getPersistRadioButton().setSelected(true); this.getStartSessionButton().setEnabled(true); } public boolean isTimestampChosen() { return this.getTimestampRadioButton().isSelected(); } public void setTimestampChosen() { this.getTimestampRadioButton().setSelected(true); this.getStartSessionButton().setEnabled(true); } public boolean isTemporaryChosen() { return this.getTemporaryRadioButton().isSelected(); } public void setTemporaryChosen() { this.getTemporaryRadioButton().setSelected(true); this.getStartSessionButton().setEnabled(true); } public boolean isDontAskAgain() { return this.getDontAskAgainCheckbox().isSelected(); } /** * This method initializes startSessionButton * * @return javax.swing.JButton */ private JButton getStartSessionButton() { if (startSessionButton == null) { startSessionButton = new JButton(); startSessionButton.setText( Constant.messages.getString("database.newsession.button.start")); startSessionButton.setEnabled(false); startSessionButton.addActionListener( new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { PersistSessionDialog.this.dispose(); } }); } return startSessionButton; } @Override public void actionPerformed(ActionEvent e) { // Enable the Start Session button if any of the radio buttons are selected this.getStartSessionButton() .setEnabled( this.getTimestampRadioButton().isSelected() || this.getPersistRadioButton().isSelected() || this.getTemporaryRadioButton().isSelected()); } }
apache-2.0
Darsstar/framework
uitest/src/test/java/com/vaadin/tests/components/window/ComboboxScrollableWindowTest.java
1942
/* * Copyright 2000-2016 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.tests.components.window; import static com.vaadin.tests.components.window.ComboboxScrollableWindow.COMBOBOX_ID; import static com.vaadin.tests.components.window.ComboboxScrollableWindow.WINDOW_ID; import org.junit.Test; import org.openqa.selenium.WebElement; import com.vaadin.testbench.By; import com.vaadin.testbench.commands.TestBenchElementCommands; import com.vaadin.testbench.elements.ComboBoxElement; import com.vaadin.testbench.elements.WindowElement; import com.vaadin.tests.tb3.MultiBrowserTest; /** * Tests that a ComboBox at the bottom of a Window remains visible when clicked. * * @author Vaadin Ltd */ public class ComboboxScrollableWindowTest extends MultiBrowserTest { @Test public void testWindowScrollbars() throws Exception { openTestURL(); WindowElement window = $(WindowElement.class).id(WINDOW_ID); WebElement scrollableElement = window .findElement(By.className("v-scrollable")); TestBenchElementCommands scrollable = testBenchElement( scrollableElement); scrollable.scroll(1000); ComboBoxElement comboBox = $(ComboBoxElement.class).id(COMBOBOX_ID); comboBox.openPopup(); waitForElementPresent(By.className("v-filterselect-suggestpopup")); compareScreen("combobox-open"); } }
apache-2.0
xiexingguang/java-game-server
jetserver/src/main/java/org/menacheri/jetserver/handlers/netty/AMF3ToEventSourceDecoder.java
796
package org.menacheri.jetserver.handlers.netty; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.menacheri.jetserver.event.Event; /** * If the incoming event is of type {@link Event} then it will only * de-serialize the source of the event rather than the whole event object. The * de-serialized source is now set as source of the event. * * @author Abraham Menacherry * */ public class AMF3ToEventSourceDecoder extends AMF3ToJavaObjectDecoder { @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { Event event = (Event) msg; Object source = super.decode(ctx, channel, event.getSource()); event.setSource(source); return event; } }
mit
Skywalker-11/spongycastle
core/src/main/java/org/spongycastle/asn1/cmp/RevAnnContent.java
2585
package org.spongycastle.asn1.cmp; import org.spongycastle.asn1.ASN1EncodableVector; import org.spongycastle.asn1.ASN1GeneralizedTime; import org.spongycastle.asn1.ASN1Object; import org.spongycastle.asn1.ASN1Primitive; import org.spongycastle.asn1.ASN1Sequence; import org.spongycastle.asn1.DERSequence; import org.spongycastle.asn1.crmf.CertId; import org.spongycastle.asn1.x509.Extensions; public class RevAnnContent extends ASN1Object { private PKIStatus status; private CertId certId; private ASN1GeneralizedTime willBeRevokedAt; private ASN1GeneralizedTime badSinceDate; private Extensions crlDetails; private RevAnnContent(ASN1Sequence seq) { status = PKIStatus.getInstance(seq.getObjectAt(0)); certId = CertId.getInstance(seq.getObjectAt(1)); willBeRevokedAt = ASN1GeneralizedTime.getInstance(seq.getObjectAt(2)); badSinceDate = ASN1GeneralizedTime.getInstance(seq.getObjectAt(3)); if (seq.size() > 4) { crlDetails = Extensions.getInstance(seq.getObjectAt(4)); } } public static RevAnnContent getInstance(Object o) { if (o instanceof RevAnnContent) { return (RevAnnContent)o; } if (o != null) { return new RevAnnContent(ASN1Sequence.getInstance(o)); } return null; } public PKIStatus getStatus() { return status; } public CertId getCertId() { return certId; } public ASN1GeneralizedTime getWillBeRevokedAt() { return willBeRevokedAt; } public ASN1GeneralizedTime getBadSinceDate() { return badSinceDate; } public Extensions getCrlDetails() { return crlDetails; } /** * <pre> * RevAnnContent ::= SEQUENCE { * status PKIStatus, * certId CertId, * willBeRevokedAt GeneralizedTime, * badSinceDate GeneralizedTime, * crlDetails Extensions OPTIONAL * -- extra CRL details (e.g., crl number, reason, location, etc.) * } * </pre> * @return a basic ASN.1 object representation. */ public ASN1Primitive toASN1Primitive() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(status); v.add(certId); v.add(willBeRevokedAt); v.add(badSinceDate); if (crlDetails != null) { v.add(crlDetails); } return new DERSequence(v); } }
mit
shiyimin/androidtestdebug
lecture-demo/uiautomator/android-testing-checkpoints/final/app/src/main/java/com/example/android/testing/notes/data/Note.java
2385
/* * Copyright 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.example.android.testing.notes.data; import com.google.common.base.Objects; import android.support.annotation.Nullable; import java.util.UUID; /** * Immutable model class for a Note. */ public final class Note { private final String mId; @Nullable private final String mTitle; @Nullable private final String mDescription; @Nullable private final String mImageUrl; public Note(@Nullable String title, @Nullable String description) { this(title, description, null); } public Note(@Nullable String title, @Nullable String description, @Nullable String imageUrl) { mId = UUID.randomUUID().toString(); mTitle = title; mDescription = description; mImageUrl = imageUrl; } public String getId() { return mId; } @Nullable public String getTitle() { return mTitle; } @Nullable public String getDescription() { return mDescription; } @Nullable public String getImageUrl() { return mImageUrl; } public boolean isEmpty() { return (mTitle == null || "".equals(mTitle)) && (mDescription == null || "".equals(mDescription)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Note note = (Note) o; return Objects.equal(mId, note.mId) && Objects.equal(mTitle, note.mTitle) && Objects.equal(mDescription, note.mDescription) && Objects.equal(mImageUrl, note.mImageUrl); } @Override public int hashCode() { return Objects.hashCode(mId, mTitle, mDescription, mImageUrl); } }
mit
mfietz/AntennaPod
app/src/main/java/de/danoeh/antennapod/fragment/gpodnet/TagFragment.java
1837
package de.danoeh.antennapod.fragment.gpodnet; import android.os.Bundle; import android.support.annotation.Nullable; import org.apache.commons.lang3.Validate; import java.util.List; import de.danoeh.antennapod.activity.MainActivity; import de.danoeh.antennapod.core.gpoddernet.GpodnetService; import de.danoeh.antennapod.core.gpoddernet.GpodnetServiceException; import de.danoeh.antennapod.core.gpoddernet.model.GpodnetPodcast; import de.danoeh.antennapod.core.gpoddernet.model.GpodnetTag; /** * Shows all podcasts from gpodder.net that belong to a specific tag. * Use the newInstance method of this class to create a new TagFragment. */ public class TagFragment extends PodcastListFragment { private static final String TAG = "TagFragment"; private static final int PODCAST_COUNT = 50; private GpodnetTag tag; public static TagFragment newInstance(GpodnetTag tag) { Validate.notNull(tag); TagFragment fragment = new TagFragment(); Bundle args = new Bundle(); args.putParcelable("tag", tag); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); Validate.isTrue(args != null && args.getParcelable("tag") != null, "args invalid"); tag = args.getParcelable("tag"); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ((MainActivity) getActivity()).getSupportActionBar().setTitle(tag.getTitle()); } @Override protected List<GpodnetPodcast> loadPodcastData(GpodnetService service) throws GpodnetServiceException { return service.getPodcastsForTag(tag, PODCAST_COUNT); } }
mit
alexVengrovsk/che
wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/vfs/impl/file/FileMetadataSerializer.java
2651
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.vfs.impl.file; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.List; import java.util.Map; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Maps.newHashMapWithExpectedSize; import static com.google.common.collect.Maps.newLinkedHashMap; /** * Serializer for properties of VirtualFile. * * @author andrew00x */ public class FileMetadataSerializer implements DataSerializer<Map<String, String>> { @Override public void write(DataOutput output, Map<String, String> props) throws IOException { output.writeInt(props.size()); for (Map.Entry<String, String> entry : props.entrySet()) { String value = entry.getValue(); if (value != null) { final String name = entry.getKey(); output.writeUTF(name); final List<String> asList = Splitter.on(',').splitToList(value); output.writeInt(asList.size()); for (String single : asList) { output.writeUTF(single); } } } } @Override public Map<String, String> read(DataInput input) throws IOException { final int recordsNum = input.readInt(); if (recordsNum == 0) { return newLinkedHashMap(); } final Map<String, String> properties = newHashMapWithExpectedSize(recordsNum); final List<String> valuesList = newArrayList(); int readRecords = 0; while (readRecords < recordsNum) { String name = input.readUTF(); final int valueItemNum = input.readInt(); valuesList.clear(); for (int i = 0; i < valueItemNum; i++) { valuesList.add(input.readUTF()); } properties.put(name, Joiner.on(',').join(valuesList)); ++readRecords; } return properties; } }
epl-1.0
TypeFox/che
selenium/che-selenium-test/src/test/resources/projects/move-items-project/src/main/java/r/A9.java
430
/* * Copyright (c) 2012-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package r; import r.A9; //import r.Other; public class A9 { }
epl-1.0
robertoandrade/cyclos
src/nl/strohalm/cyclos/controls/accounts/guarantees/paymentobligations/AcceptPaymentObligationAction.java
4488
/* This file is part of Cyclos (www.cyclos.org). A project of the Social Trade Organisation (www.socialtrade.org). Cyclos is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Cyclos 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 Cyclos; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package nl.strohalm.cyclos.controls.accounts.guarantees.paymentobligations; import nl.strohalm.cyclos.annotations.Inject; import nl.strohalm.cyclos.controls.ActionContext; import nl.strohalm.cyclos.controls.BaseAction; import nl.strohalm.cyclos.entities.accounts.guarantees.Guarantee; import nl.strohalm.cyclos.entities.members.Member; import nl.strohalm.cyclos.entities.settings.LocalSettings; import nl.strohalm.cyclos.services.accounts.guarantees.GuaranteeService; import nl.strohalm.cyclos.services.accounts.guarantees.PaymentObligationPackDTO; import nl.strohalm.cyclos.services.accounts.guarantees.exceptions.ActiveCertificationNotFoundException; import nl.strohalm.cyclos.services.accounts.guarantees.exceptions.CertificationAmountExceededException; import nl.strohalm.cyclos.services.accounts.guarantees.exceptions.CertificationValidityExceededException; import nl.strohalm.cyclos.utils.ActionHelper; import nl.strohalm.cyclos.utils.EntityHelper; import nl.strohalm.cyclos.utils.conversion.CalendarConverter; import nl.strohalm.cyclos.utils.conversion.UnitsConverter; import org.apache.struts.action.ActionForward; public class AcceptPaymentObligationAction extends BaseAction { private GuaranteeService guaranteeService; @Inject public void setGuaranteeService(final GuaranteeService guaranteeService) { this.guaranteeService = guaranteeService; } @Override protected ActionForward executeAction(final ActionContext context) throws Exception { final AcceptPaymentObligationForm form = context.getForm(); final Long issuerId = form.getIssuerId(); final Long paymentObligationId = form.getPaymentObligationId(); try { final Guarantee guarantee = requestGuarantee(paymentObligationId, EntityHelper.reference(Member.class, issuerId)); context.sendMessage("paymentObligation.requestGuaranteeOk", context.message("guarantee.status." + guarantee.getStatus())); } catch (final ActiveCertificationNotFoundException e) { context.sendMessage("paymentObligation.error.noActiveCertificationFound", e.getBuyer(), e.getIssuer()); } catch (final CertificationAmountExceededException e) { final LocalSettings localSettings = settingsService.getLocalSettings(); final UnitsConverter converter = localSettings.getUnitsConverter(e.getCertification().getGuaranteeType().getCurrency().getPattern()); context.sendMessage("paymentObligation.error.certificationAmountExceeded", converter.toString(e.getRemainingCertificationAmount()), converter.toString(e.getTotalExceededAmount())); } catch (final CertificationValidityExceededException e) { final LocalSettings localSettings = settingsService.getLocalSettings(); final CalendarConverter converter = localSettings.getRawDateConverter(); final String validityBegin = converter.toString(e.getCertification().getValidity().getBegin()); final String validityEnd = converter.toString(e.getCertification().getValidity().getEnd()); context.sendMessage("paymentObligation.error.certificationValidityExceeded", validityBegin, validityEnd); } return ActionHelper.redirectWithParam(context.getRequest(), context.getSuccessForward(), "paymentObligationId", paymentObligationId); } private Guarantee requestGuarantee(final Long id, final Member issuer) { final PaymentObligationPackDTO pack = new PaymentObligationPackDTO(); pack.setIssuer(issuer); pack.setPaymentObligations(new Long[] { id }); return guaranteeService.requestGuarantee(pack); } }
gpl-2.0
austinv11/DartCraft2
src/api/java/forestry/api/arboriculture/EnumTreeChromosome.java
2766
/******************************************************************************* * Copyright 2011-2014 SirSengir * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.arboriculture; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleArea; import forestry.api.genetics.IAlleleBoolean; import forestry.api.genetics.IAlleleFloat; import forestry.api.genetics.IAlleleInteger; import forestry.api.genetics.IAllelePlantType; import forestry.api.genetics.IChromosomeType; import forestry.api.genetics.IFruitFamily; import forestry.api.genetics.ISpeciesRoot; import net.minecraftforge.common.EnumPlantType; public enum EnumTreeChromosome implements IChromosomeType { /** * Determines the following: - WorldGen, including the used wood blocks - {@link IFruitFamily}s supported. Limits which {@link IFruitProvider} * will actually yield fruit with this species. - Native {@link EnumPlantType} for this tree. Combines with the PLANT chromosome. */ SPECIES(IAlleleTreeSpecies.class), /** * {@link IGrowthProvider}, determines conditions required by the tree to grow. */ GROWTH(IAlleleGrowth.class), /** * A float modifying the height of the tree. Taken into account at worldgen. */ HEIGHT(IAlleleFloat.class), /** * Chance for saplings. */ FERTILITY(IAlleleFloat.class), /** * {@link IFruitProvider}, determines if and what fruits are grown on the tree. Limited by the {@link IFruitFamily}s the species supports. */ FRUITS(IAlleleFruit.class), /** * Chance for fruit leaves and/or drops. */ YIELD(IAlleleFloat.class), /** * May add additional tolerances for {@link EnumPlantTypes}. */ PLANT(IAllelePlantType.class), /** * Determines the speed at which fruit will ripen on this tree. */ SAPPINESS(IAlleleFloat.class), /** * Territory for leaf effects. Unused. */ TERRITORY(IAlleleArea.class), /** * Leaf effect. Unused. */ EFFECT(IAlleleLeafEffect.class), /** * Amount of random ticks which need to elapse before a sapling will grow into a tree. */ MATURATION(IAlleleInteger.class), GIRTH(IAlleleInteger.class), /** * Determines if the tree can burn. */ FIREPROOF(IAlleleBoolean.class), ; Class<? extends IAllele> clss; EnumTreeChromosome(Class<? extends IAllele> clss) { this.clss = clss; } @Override public Class<? extends IAllele> getAlleleClass() { return clss; } @Override public String getName() { return this.toString().toLowerCase(); } @Override public ISpeciesRoot getSpeciesRoot() { return AlleleManager.alleleRegistry.getSpeciesRoot("rootTrees"); } }
gpl-2.0
mykmelez/pluotsorbet
java/cldc1.1.1/java/util/PropertyPermission.java
14505
/* * @(#)PropertyPermission.java 1.32 06/10/10 * * Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * 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 version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. * */ package java.util; import java.io.IOException; import java.security.*; import java.util.Enumeration; import java.io.IOException; /** * This class is for property permissions. * * <P> * The name is the name of the property ("java.home", * "os.name", etc). The naming * convention follows the hierarchical property naming convention. * Also, an asterisk * may appear at the end of the name, following a ".", or by itself, to * signify a wildcard match. For example: "java.*" or "*" is valid, * "*java" or "a*b" is not valid. * <P> * <P> * The actions to be granted are passed to the constructor in a string containing * a list of zero or more comma-separated keywords. The possible keywords are * "read" and "write". Their meaning is defined as follows: * <P> * <DL> * <DT> read * <DD> read permission. Allows <code>System.getProperty</code> to * be called. * <DT> write * <DD> write permission. Allows <code>System.setProperty</code> to * be called. * </DL> * <P> * The actions string is converted to lowercase before processing. * <P> * Care should be taken before granting code permission to access * certain system properties. For example, granting permission to * access the "java.home" system property gives potentially malevolent * code sensitive information about the system environment (the Java * installation directory). Also, granting permission to access * the "user.name" and "user.home" system properties gives potentially * malevolent code sensitive information about the user environment * (the user's account name and home directory). * * @see java.security.BasicPermission * @see java.security.Permission * @see java.security.Permissions * @see java.security.PermissionCollection * @see java.lang.SecurityManager * * @version 1.24 00/02/02 * * @author Roland Schemers * @since 1.2 * * @serial exclude */ public final class PropertyPermission extends BasicPermission { /** * Read action. */ private final static int READ = 0x1; /** * Write action. */ private final static int WRITE = 0x2; /** * All actions (read,write); */ private final static int ALL = READ|WRITE; /** * No actions. */ private final static int NONE = 0x0; /** * The actions mask. * */ private transient int mask; /** * The actions string. * * @serial */ private String actions; // Left null as long as possible, then // created and re-used in the getAction function. /** * initialize a PropertyPermission object. Common to all constructors. * Also called during de-serialization. * * @param mask the actions mask to use. * */ private void init(int mask) { if ((mask & ALL) != mask) throw new IllegalArgumentException("invalid actions mask"); if (mask == NONE) throw new IllegalArgumentException("invalid actions mask"); if (getName() == null) throw new NullPointerException("name can't be null"); this.mask = mask; } /** * Creates a new PropertyPermission object with the specified name. * The name is the name of the system property, and * <i>actions</i> contains a comma-separated list of the * desired actions granted on the property. Possible actions are * "read" and "write". * * @param name the name of the PropertyPermission. * @param actions the actions string. */ public PropertyPermission(String name, String actions) { super(name,actions); init(getMask(actions)); } /** * Checks if this PropertyPermission object "implies" the specified * permission. * <P> * More specifically, this method returns true if:<p> * <ul> * <li> <i>p</i> is an instanceof PropertyPermission,<p> * <li> <i>p</i>'s actions are a subset of this * object's actions, and <p> * <li> <i>p</i>'s name is implied by this object's * name. For example, "java.*" implies "java.home". * </ul> * @param p the permission to check against. * * @return true if the specified permission is implied by this object, * false if not. */ public boolean implies(Permission p) { if (!(p instanceof PropertyPermission)) return false; PropertyPermission that = (PropertyPermission) p; // we get the effective mask. i.e., the "and" of this and that. // They must be equal to that.mask for implies to return true. return ((this.mask & that.mask) == that.mask) && super.implies(that); } /** * Checks two PropertyPermission objects for equality. Checks that <i>obj</i> is * a PropertyPermission, and has the same name and actions as this object. * <P> * @param obj the object we are testing for equality with this object. * @return true if obj is a PropertyPermission, and has the same name and * actions as this PropertyPermission object. */ public boolean equals(Object obj) { if (obj == this) return true; if (! (obj instanceof PropertyPermission)) return false; PropertyPermission that = (PropertyPermission) obj; return (this.mask == that.mask) && (this.getName().equals(that.getName())); } /** * Returns the hash code value for this object. * The hash code used is the hash code of this permissions name, that is, * <code>getName().hashCode()</code>, where <code>getName</code> is * from the Permission superclass. * * @return a hash code value for this object. */ public int hashCode() { return this.getName().hashCode(); } /** * Converts an actions String to an actions mask. * * @param action the action string. * @return the actions mask. */ private static int getMask(String actions) { int mask = NONE; if (actions == null) { return mask; } char[] a = actions.toCharArray(); int i = a.length - 1; if (i < 0) return mask; while (i != -1) { // check for the known strings int matchlen; if (i >= 3 && (a[i-3] == 'r' || a[i-3] == 'R') && (a[i-2] == 'e' || a[i-2] == 'E') && (a[i-1] == 'a' || a[i-1] == 'A') && (a[i] == 'd' || a[i] == 'D')) { matchlen = 4; mask |= READ; } else if (i >= 4 && (a[i-4] == 'w' || a[i-4] == 'W') && (a[i-3] == 'r' || a[i-3] == 'R') && (a[i-2] == 'i' || a[i-2] == 'I') && (a[i-1] == 't' || a[i-1] == 'T') && (a[i] == 'e' || a[i] == 'E')) { matchlen = 5; mask |= WRITE; } else { // parse error throw new IllegalArgumentException( "invalid actions: " + actions); } // make sure we didn't just match the tail of a word // like "ackbarfaccept". Also, skip to the comma. if (i >= matchlen) { // don't match the comma at the beginning of the string if (i > matchlen && a[i-matchlen] == ',') { i--; } else { // parse error throw new IllegalArgumentException( "invalid actions: " + actions); } } // point i at the location of the comma minus one (or -1). i -= matchlen; } return mask; } /** * Return the canonical string representation of the actions. * Always returns present actions in the following order: * read, write. * * @return the canonical string representation of the actions. */ static String getActions(int mask) { StringBuffer sb = new StringBuffer(); boolean comma = false; if ((mask & READ) == READ) { comma = true; sb.append("read"); } if ((mask & WRITE) == WRITE) { if (comma) sb.append(','); else comma = true; sb.append("write"); } return sb.toString(); } /** * Returns the "canonical string representation" of the actions. * That is, this method always returns present actions in the following order: * read, write. For example, if this PropertyPermission object * allows both write and read actions, a call to <code>getActions</code> * will return the string "read,write". * * @return the canonical string representation of the actions. */ public String getActions() { if (actions == null) actions = getActions(this.mask); return actions; } /** * Return the current action mask. * Used by the PropertyPermissionCollection * * @return the actions mask. */ int getMask() { return mask; } /** * Returns a new PermissionCollection object for storing * PropertyPermission objects. * <p> * * @return a new PermissionCollection object suitable for storing * PropertyPermissions. */ public PermissionCollection newPermissionCollection() { return new PropertyPermissionCollection(); } } /** * A PropertyPermissionCollection stores a set of PropertyPermission * permissions. * * @see java.security.Permission * @see java.security.Permissions * @see java.security.PermissionCollection * * @version 1.24, 02/02/00 * * @author Roland Schemers * * @serial include */ final class PropertyPermissionCollection extends PermissionCollection { /** * Boolean saying if "*" is in the collection. * * @see #serialPersistentFields */ private boolean all_allowed; Hashtable perms; /** * Create an empty PropertyPermissions object. * */ public PropertyPermissionCollection() { perms = new Hashtable(32); // Capacity for default policy all_allowed = false; } /** * Adds a permission to the PropertyPermissions. The key for the hash is * the name. * * @param permission the Permission object to add. * * @exception IllegalArgumentException - if the permission is not a * PropertyPermission * * @exception SecurityException - if this PropertyPermissionCollection * object has been marked readonly */ public void add(Permission permission) { if (! (permission instanceof PropertyPermission)) throw new IllegalArgumentException("invalid permission: "+ permission); if (isReadOnly()) throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection"); PropertyPermission pp = (PropertyPermission) permission; PropertyPermission existing = (PropertyPermission) perms.get(pp.getName()); // No need to synchronize because all adds are done sequentially // before any implies() calls if (existing != null) { int oldMask = existing.getMask(); int newMask = pp.getMask(); if (oldMask != newMask) { int effective = oldMask | newMask; String actions = PropertyPermission.getActions(effective); perms.put(pp.getName(), new PropertyPermission(pp.getName(), actions)); } } else { perms.put(pp.getName(), permission); } if (!all_allowed) { if (pp.getName().equals("*")) all_allowed = true; } } /** * Check and see if this set of permissions implies the permissions * expressed in "permission". * * @param p the Permission object to compare * * @return true if "permission" is a proper subset of a permission in * the set, false if not. */ public boolean implies(Permission permission) { if (! (permission instanceof PropertyPermission)) return false; PropertyPermission pp = (PropertyPermission) permission; PropertyPermission x; int desired = pp.getMask(); int effective = 0; // short circuit if the "*" Permission was added if (all_allowed) { x = (PropertyPermission) perms.get("*"); if (x != null) { effective |= x.getMask(); if ((effective & desired) == desired) return true; } } // strategy: // Check for full match first. Then work our way up the // name looking for matches on a.b.* String name = pp.getName(); x = (PropertyPermission) perms.get(name); if (x != null) { // we have a direct hit! effective |= x.getMask(); if ((effective & desired) == desired) return true; } // work our way up the tree... int last, offset; offset = name.length()-1; while ((last = name.lastIndexOf('.', offset)) != -1) { name = name.substring(0, last+1) + "*"; x = (PropertyPermission) perms.get(name); if (x != null) { effective |= x.getMask(); if ((effective & desired) == desired) { return true; } } offset = last -1; } // we don't have to check for "*" as it was already checked // at the top (all_allowed), so we just return false return false; } /** * Returns an enumeration of all the PropertyPermission objects in the * container. * * @return an enumeration of all the PropertyPermission objects. */ public Enumeration elements() { // Convert Iterator of Map values into an Enumeration return perms.elements(); } private static final long serialVersionUID = 7015263904581634791L; }
gpl-2.0
biddyweb/checker-framework
framework/src/org/checkerframework/framework/util/ContractsUtils.java
10771
package org.checkerframework.framework.util; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import org.checkerframework.framework.qual.ConditionalPostconditionAnnotation; import org.checkerframework.framework.qual.EnsuresQualifier; import org.checkerframework.framework.qual.EnsuresQualifierIf; import org.checkerframework.framework.qual.EnsuresQualifiers; import org.checkerframework.framework.qual.EnsuresQualifiersIf; import org.checkerframework.framework.qual.PostconditionAnnotation; import org.checkerframework.framework.qual.PreconditionAnnotation; import org.checkerframework.framework.qual.RequiresQualifier; import org.checkerframework.framework.qual.RequiresQualifiers; import org.checkerframework.framework.type.GenericAnnotatedTypeFactory; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.Pair; /** * A utility class to handle pre- and postconditions. * * @see PreconditionAnnotation * @see RequiresQualifier * @see PostconditionAnnotation * @see EnsuresQualifier * @see EnsuresQualifierIf * @author Stefan Heule */ public class ContractsUtils { protected static ContractsUtils instance; protected GenericAnnotatedTypeFactory<?, ?, ?, ?> factory; /** * Returns an instance of the {@link ContractsUtils} class. */ public static ContractsUtils getInstance( GenericAnnotatedTypeFactory<?, ?, ?, ?> factory) { if (instance == null || instance.factory != factory) { instance = new ContractsUtils(factory); } return instance; } /** * Returns a set of pairs {@code (expr, annotation)} of preconditions on the * element {@code element}. */ public Set<Pair<String, String>> getPreconditions( Element element) { Set<Pair<String, String>> result = new HashSet<>(); // Check for a single contract. AnnotationMirror requiresAnnotation = factory.getDeclAnnotation( element, RequiresQualifier.class); result.addAll(getPrecondition(requiresAnnotation)); // Check for multiple contracts. AnnotationMirror requiresAnnotations = factory.getDeclAnnotation( element, RequiresQualifiers.class); if (requiresAnnotations != null) { List<AnnotationMirror> annotations = AnnotationUtils .getElementValueArray(requiresAnnotations, "value", AnnotationMirror.class, false); for (AnnotationMirror a : annotations) { result.addAll(getPrecondition(a)); } } // Check type-system specific annotations. Class<PreconditionAnnotation> metaAnnotation = PreconditionAnnotation.class; List<Pair<AnnotationMirror, AnnotationMirror>> declAnnotations = factory .getDeclAnnotationWithMetaAnnotation(element, metaAnnotation); for (Pair<AnnotationMirror, AnnotationMirror> r : declAnnotations) { AnnotationMirror anno = r.first; AnnotationMirror metaAnno = r.second; List<String> expressions = AnnotationUtils.getElementValueArray(anno, "value", String.class, false); String annotationString = AnnotationUtils.getElementValueClassName( metaAnno, "qualifier", false).toString(); for (String expr : expressions) { result.add(Pair.of(expr, annotationString)); } } return result; } /** * Returns a set of pairs {@code (expr, annotation)} of preconditions * according to the given {@link RequiresQualifier}. */ private Set<Pair<String, String>> getPrecondition( AnnotationMirror requiresAnnotation) { if (requiresAnnotation == null) { return Collections.emptySet(); } Set<Pair<String, String>> result = new HashSet<>(); List<String> expressions = AnnotationUtils.getElementValueArray( requiresAnnotation, "expression", String.class, false); String annotation = AnnotationUtils.getElementValueClassName( requiresAnnotation, "qualifier", false).toString(); for (String expr : expressions) { result.add(Pair.of(expr, annotation)); } return result; } /** * Returns a set of pairs {@code (expr, annotation)} of postconditions on * the method {@code methodElement}. */ public Set<Pair<String, String>> getPostconditions( ExecutableElement methodElement) { Set<Pair<String, String>> result = new HashSet<>(); // Check for a single contract. AnnotationMirror ensuresAnnotation = factory.getDeclAnnotation( methodElement, EnsuresQualifier.class); result.addAll(getPostcondition(ensuresAnnotation)); // Check for multiple contracts. AnnotationMirror ensuresAnnotations = factory.getDeclAnnotation( methodElement, EnsuresQualifiers.class); if (ensuresAnnotations != null) { List<AnnotationMirror> annotations = AnnotationUtils .getElementValueArray(ensuresAnnotations, "value", AnnotationMirror.class, false); for (AnnotationMirror a : annotations) { result.addAll(getPostcondition(a)); } } // Check type-system specific annotations. Class<PostconditionAnnotation> metaAnnotation = PostconditionAnnotation.class; List<Pair<AnnotationMirror, AnnotationMirror>> declAnnotations = factory .getDeclAnnotationWithMetaAnnotation(methodElement, metaAnnotation); for (Pair<AnnotationMirror, AnnotationMirror> r : declAnnotations) { AnnotationMirror anno = r.first; AnnotationMirror metaAnno = r.second; List<String> expressions = AnnotationUtils.getElementValueArray(anno, "value", String.class, false); String annotationString = AnnotationUtils.getElementValueClassName( metaAnno, "qualifier", false).toString(); for (String expr : expressions) { result.add(Pair.of(expr, annotationString)); } } return result; } /** * Returns a set of pairs {@code (expr, annotation)} of postconditions * according to the given {@link EnsuresQualifier}. */ private Set<Pair<String, String>> getPostcondition( AnnotationMirror ensuresAnnotation) { if (ensuresAnnotation == null) { return Collections.emptySet(); } Set<Pair<String, String>> result = new HashSet<>(); List<String> expressions = AnnotationUtils.getElementValueArray( ensuresAnnotation, "expression", String.class, false); String annotation = AnnotationUtils.getElementValueClassName( ensuresAnnotation, "qualifier", false).toString(); for (String expr : expressions) { result.add(Pair.of(expr, annotation)); } return result; } /** * Returns a set of triples {@code (expr, (result, annotation))} of * conditional postconditions on the method {@code methodElement}. */ public Set<Pair<String, Pair<Boolean, String>>> getConditionalPostconditions( ExecutableElement methodElement) { Set<Pair<String, Pair<Boolean, String>>> result = new HashSet<>(); // Check for a single contract. AnnotationMirror ensuresAnnotationIf = factory.getDeclAnnotation( methodElement, EnsuresQualifierIf.class); result.addAll(getConditionalPostcondition(ensuresAnnotationIf)); // Check for multiple contracts. AnnotationMirror ensuresAnnotationsIf = factory.getDeclAnnotation( methodElement, EnsuresQualifiersIf.class); if (ensuresAnnotationsIf != null) { List<AnnotationMirror> annotations = AnnotationUtils .getElementValueArray(ensuresAnnotationsIf, "value", AnnotationMirror.class, false); for (AnnotationMirror a : annotations) { result.addAll(getConditionalPostcondition(a)); } } // Check type-system specific annotations. Class<ConditionalPostconditionAnnotation> metaAnnotation = ConditionalPostconditionAnnotation.class; List<Pair<AnnotationMirror, AnnotationMirror>> declAnnotations = factory .getDeclAnnotationWithMetaAnnotation(methodElement, metaAnnotation); for (Pair<AnnotationMirror, AnnotationMirror> r : declAnnotations) { AnnotationMirror anno = r.first; AnnotationMirror metaAnno = r.second; List<String> expressions = AnnotationUtils.getElementValueArray(anno, "expression", String.class, false); String annotationString = AnnotationUtils.getElementValueClassName( metaAnno, "qualifier", false).toString(); boolean annoResult = AnnotationUtils.getElementValue(anno, "result", Boolean.class, false); for (String expr : expressions) { result.add(Pair.of(expr, Pair.of(annoResult, annotationString))); } } return result; } /** * Returns a set of triples {@code (expr, (result, annotation))} of * conditional postconditions according to the given * {@link EnsuresQualifierIf}. */ private Set<Pair<String, Pair<Boolean, String>>> getConditionalPostcondition( AnnotationMirror ensuresAnnotationIf) { if (ensuresAnnotationIf == null) { return Collections.emptySet(); } Set<Pair<String, Pair<Boolean, String>>> result = new HashSet<>(); List<String> expressions = AnnotationUtils.getElementValueArray( ensuresAnnotationIf, "expression", String.class, false); String annotation = AnnotationUtils.getElementValueClassName( ensuresAnnotationIf, "qualifier", false).toString(); boolean annoResult = AnnotationUtils.getElementValue(ensuresAnnotationIf, "result", Boolean.class, false); for (String expr : expressions) { result.add(Pair.of(expr, Pair.of(annoResult, annotation))); } return result; } // private constructor private ContractsUtils(GenericAnnotatedTypeFactory<?, ?, ?, ?> factory) { this.factory = factory; } }
gpl-2.0
axDev-JDK/jaxws
src/share/jaxws_classes/com/sun/xml/internal/ws/handler/XMLHandlerProcessor.java
2535
/* * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * LogicalHandlerProcessor.java * * Created on February 8, 2006, 5:40 PM * */ package com.sun.xml.internal.ws.handler; import com.sun.xml.internal.ws.api.WSBinding; import com.sun.xml.internal.ws.api.message.Messages; import java.util.List; import javax.xml.ws.ProtocolException; import javax.xml.ws.handler.Handler; import javax.xml.ws.handler.MessageContext; import javax.xml.ws.http.HTTPException; /** * This is used only for XML/HTTP binding * @author WS Development Team */ final class XMLHandlerProcessor<C extends MessageUpdatableContext> extends HandlerProcessor<C> { /** * Creates a new instance of LogicalHandlerProcessor */ public XMLHandlerProcessor(HandlerTube owner, WSBinding binding, List<? extends Handler> chain) { super(owner, binding, chain); } /* * TODO: This is valid only for XML/HTTP binding * Empty the XML message */ final void insertFaultMessage(C context, ProtocolException exception) { if(exception instanceof HTTPException) { context.put(MessageContext.HTTP_RESPONSE_CODE,((HTTPException)exception).getStatusCode()); } if (context != null) { // non-soap case context.setPacketMessage(Messages.createEmpty(binding.getSOAPVersion())); } } }
gpl-2.0
md-5/jdk10
test/hotspot/jtreg/vmTestbase/vm/runtime/defmeth/scenarios/PrivateMethods_v52_syncstrict_direct_noredefine/TestDescription.java
1603
/* * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @modules java.base/jdk.internal.org.objectweb.asm:+open java.base/jdk.internal.org.objectweb.asm.util:+open * * @summary converted from VM Testbase vm/runtime/defmeth/scenarios/PrivateMethods_v52_syncstrict_direct_noredefine. * VM Testbase keywords: [defmeth, jdk8, quick] * * @library /vmTestbase /test/lib * @run driver jdk.test.lib.FileInstaller . . * @run main/othervm * -XX:+IgnoreUnrecognizedVMOptions * vm.runtime.defmeth.PrivateMethodsTest * -ver 52 * -flags 2080 * -mode direct */
gpl-2.0
saeder/CodenameOne
CodenameOne/src/com/codename1/maps/layers/PointLayer.java
3485
/* * Copyright (c) 2010, 2011 Itiner.pl. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Itiner designates this * particular file as subject to the "Classpath" exception as provided * by Itiner in the LICENSE.txt file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.codename1.maps.layers; import com.codename1.maps.BoundingBox; import com.codename1.maps.Coord; import com.codename1.ui.geom.Point; import com.codename1.maps.Tile; import com.codename1.ui.Graphics; import com.codename1.ui.Image; /** * Do not use this layer directly, you need to add this layer into a PointsLayer class * instance in order for it to work as expected! * * @author Roman Kamyk <roman.kamyk@itiner.pl> */ public class PointLayer extends Coord implements Layer{ private final String name; private Image icon; private boolean displayName; /** * Creates a Point Layer. * * @param position the position of the Point * @param getName the getName of the Point * @param icon icon of the Point */ public PointLayer(Coord position, String name, Image icon) { super(position); this.name = name; this.icon = icon; } /** * Gets the Point name * @return the Point name */ public String getName() { return name; } /** * Gets the point Icon * @return the point Icon */ public Image getIcon() { return icon; } /** * Sets the display icon * @param icon */ public void setIcon(Image icon) { this.icon = icon; } /** * This method declares if the point name should be displayed * * @param displayName */ public void setDisplayName(boolean displayName){ this.displayName = displayName; } /** * {@inheritDoc} */ public void paint(Graphics g, Tile tile) { Point pos = tile.pointPosition(this); int width = 6; int height = 6; if (icon != null) { width = icon.getWidth(); height = icon.getHeight(); } int x = pos.getX() - width / 2; int y = pos.getY() - height / 2; if (icon == null) { g.fillRect(x, y, width, height); } else { g.drawImage(icon, x, y); } if (name != null && displayName) { g.drawString(getName(), x + width + 1, pos.getY() - g.getFont().getHeight() / 2 - 1); } } /** * {@inheritDoc} */ public String toString() { return super.toString() + " " + name; } /** * {@inheritDoc} */ public BoundingBox boundingBox() { return null; } }
gpl-2.0
md-5/jdk10
src/java.desktop/share/classes/javax/print/attribute/standard/JobOriginatingUserName.java
5039
/* * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.print.attribute.standard; import java.util.Locale; import javax.print.attribute.Attribute; import javax.print.attribute.PrintJobAttribute; import javax.print.attribute.TextSyntax; /** * Class {@code JobOriginatingUserName} is a printing attribute class, a text * attribute, that contains the name of the end user that submitted the print * job. If possible, the printer sets this attribute to the most authenticated * printable user name that it can obtain from the authentication service that * authenticated the submitted Print Request. If such is not available, the * printer uses the value of the {@link RequestingUserName RequestingUserName} * attribute supplied by the client in the Print Request's attribute set. If no * authentication service is available, and the client did not supply a * {@link RequestingUserName RequestingUserName} attribute, the printer sets the * JobOriginatingUserName attribute to an empty (zero-length) string. * <p> * <b>IPP Compatibility:</b> The string value gives the IPP name value. The * locale gives the IPP natural language. The category name returned by * {@code getName()} gives the IPP attribute name. * * @author Alan Kaminsky */ public final class JobOriginatingUserName extends TextSyntax implements PrintJobAttribute { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ private static final long serialVersionUID = -8052537926362933477L; /** * Constructs a new job originating user name attribute with the given user * name and locale. * * @param userName user name * @param locale natural language of the text string. {@code null} is * interpreted to mean the default locale as returned by * {@code Locale.getDefault()} * @throws NullPointerException if {@code userName} is {@code null} */ public JobOriginatingUserName(String userName, Locale locale) { super (userName, locale); } /** * Returns whether this job originating user name attribute is equivalent to * the passed in object. To be equivalent, all of the following conditions * must be true: * <ol type=1> * <li>{@code object} is not {@code null}. * <li>{@code object} is an instance of class * {@code JobOriginatingUserName}. * <li>This job originating user name attribute's underlying string and * {@code object}'s underlying string are equal. * <li>This job originating user name attribute's locale and * {@code object}'s locale are equal. * </ol> * * @param object {@code Object} to compare to * @return {@code true} if {@code object} is equivalent to this job * originating user name attribute, {@code false} otherwise */ public boolean equals(Object object) { return (super.equals (object) && object instanceof JobOriginatingUserName); } /** * Get the printing attribute class which is to be used as the "category" * for this printing attribute value. * <p> * For class {@code JobOriginatingUserName}, the category is class * {@code JobOriginatingUserName} itself. * * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ public final Class<? extends Attribute> getCategory() { return JobOriginatingUserName.class; } /** * Get the name of the category of which this attribute value is an * instance. * <p> * For class {@code JobOriginatingUserName}, the category name is * {@code "job-originating-user-name"}. * * @return attribute category name */ public final String getName() { return "job-originating-user-name"; } }
gpl-2.0
5AMW3155/shattered-pixel-dungeon
src/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/npcs/Sheep.java
1765
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2015 Evan Debenham * * 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 * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs; import com.shatteredpixel.shatteredpixeldungeon.sprites.SheepSprite; import com.watabou.utils.Random; public class Sheep extends NPC { private static final String[] QUOTES = {"Baa!", "Baa?", "Baa.", "Baa..."}; { name = "sheep"; spriteClass = SheepSprite.class; } public float lifespan; private boolean initialized = false; @Override protected boolean act() { if (initialized) { HP = 0; destroy(); sprite.die(); } else { initialized = true; spend( lifespan + Random.Float(2) ); } return true; } @Override public void damage( int dmg, Object src ) { } @Override public String description() { return "This is a magic sheep. What's so magical about it? You can't kill it. " + "It will stand there until it magcially fades away, all the while chewing cud with a blank stare."; } @Override public void interact() { yell( Random.element( QUOTES ) ); } }
gpl-3.0
tdefilip/opennms
opennms-webapp/src/main/java/org/opennms/web/svclayer/dao/ViewDisplayDao.java
1609
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.svclayer.dao; import org.opennms.netmgt.config.viewsdisplay.View; /** * <p>ViewDisplayDao interface.</p> * * @author <a href="mailto:jason.aras@opennms.org">Jason Aras</a> * @version $Id: $ * @since 1.8.1 */ public interface ViewDisplayDao { /** * <p>getView</p> * * @return a {@link org.opennms.netmgt.config.viewsdisplay.View} object. */ View getView(); }
agpl-3.0
cmqdcyy/Gaea
server/src/contract/com/bj58/spat/gaea/server/contract/context/StopWatch.java
3839
/* * Copyright Beijing 58 Information Technology Co.,Ltd. * * 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.bj58.spat.gaea.server.contract.context; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * ServerStateType * * @author Service Platform Architecture Team (spat@58.com) */ public class StopWatch { private Date monitorTime; private String methodName; private String lookup; private String fromIP; private String localIP; private Map<String, PerformanceCounter> mapCounter = new HashMap<String, PerformanceCounter>(); public void start() { mapCounter.put("default", new PerformanceCounter("","",System.currentTimeMillis())); } public void stop() { PerformanceCounter pc = mapCounter.get("default"); if(pc != null) { pc.setEndTime(System.currentTimeMillis()); } } public void reset(){ mapCounter.clear(); } public void startNew(String key, String description) { mapCounter.put(key, new PerformanceCounter(key, description, System.currentTimeMillis())); } public void stop(String key) { PerformanceCounter pc = mapCounter.get(key); if(pc != null) { pc.setEndTime(System.currentTimeMillis()); } } public class PerformanceCounter { private String key; private String description; private long startTime; private long endTime; public PerformanceCounter() { } public PerformanceCounter(String key, String description, long startTime) { this.setKey(key); this.setDescription(description); this.setStartTime(startTime); } public long getExecuteTime(){ return endTime - startTime; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public long getEndTime() { return endTime; } public void setEndTime(long endTime) { this.endTime = endTime; } } public Map<String, PerformanceCounter> getMapCounter() { return mapCounter; } public Date getMonitorTime() { return monitorTime; } public void setMonitorTime(Date monitorTime) { this.monitorTime = monitorTime; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public void setLookup(String lookup) { this.lookup = lookup; } public String getLookup() { return lookup; } public String getFromIP() { return fromIP; } public void setFromIP(String fromIP) { this.fromIP = fromIP; } public String getLocalIP() { return localIP; } public void setLocalIP(String localIP) { this.localIP = localIP; } }
apache-2.0
jonesgithub/nd4j
nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/iterator/MultipleEpochsIterator.java
5354
/* * * * Copyright 2015 Skymind,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.nd4j.linalg.dataset.api.iterator; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.dataset.api.DataSetPreProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A dataset iterator for doing multiple passes over a dataset */ public class MultipleEpochsIterator implements DataSetIterator { private static final Logger log = LoggerFactory.getLogger(MultipleEpochsIterator.class); private int numPasses; private int batch = 0; private DataSetIterator iter; private int passes = 0; private DataSetPreProcessor preProcessor; public MultipleEpochsIterator(int numPasses, DataSetIterator iter) { this.numPasses = numPasses; this.iter = iter; } /** * Like the standard next method but allows a * customizable number of examples returned * * @param num the number of examples * @return the next data applyTransformToDestination */ @Override public DataSet next(int num) { if (!iter.hasNext()) { if (passes < numPasses) { passes++; batch = 0; log.info("Epoch " + passes + " batch " + batch); iter.reset(); } } batch++; DataSet next = iter.next(num); if (preProcessor != null) preProcessor.preProcess(next); return next; } /** * Total examples in the iterator * * @return */ @Override public int totalExamples() { return iter.totalExamples(); } /** * Input columns for the dataset * * @return */ @Override public int inputColumns() { return iter.inputColumns(); } /** * The number of labels for the dataset * * @return */ @Override public int totalOutcomes() { return iter.totalOutcomes(); } /** * Resets the iterator back to the beginning */ @Override public void reset() { passes = 0; batch = 0; iter.reset(); } /** * Batch size * * @return */ @Override public int batch() { return iter.batch(); } /** * The current cursor if applicable * * @return */ @Override public int cursor() { return iter.cursor(); } /** * Total number of examples in the dataset * * @return */ @Override public int numExamples() { return iter.numExamples(); } /** * Set a pre processor * * @param preProcessor a pre processor to set */ @Override public void setPreProcessor(DataSetPreProcessor preProcessor) { this.preProcessor = preProcessor; } /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ @Override public boolean hasNext() { return iter.hasNext() || passes < numPasses; } /** * Returns the next element in the iteration. * * @return the next element in the iteration */ @Override public DataSet next() { if (!iter.hasNext()) { if (passes < numPasses) { passes++; batch = 0; log.info("Epoch " + passes + " batch " + batch); iter.reset(); } } batch++; DataSet next = iter.next(); if (preProcessor != null) preProcessor.preProcess(next); return next; } /** * Removes from the underlying collection the last element returned * by this iterator (optional operation). This method can be called * only once per call to {@link #next}. The behavior of an iterator * is unspecified if the underlying collection is modified while the * iteration is in progress in any way other than by calling this * method. * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this iterator * @throws IllegalStateException if the {@code next} method has not * yet been called, or the {@code remove} method has already * been called after the last call to the {@code next} * method */ @Override public void remove() { iter.remove(); } }
apache-2.0
krzysztof-magosa/encog-java-core
src/main/java/org/encog/ml/factory/method/EPLFactory.java
2770
/* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.factory.method; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import org.encog.EncogError; import org.encog.ml.MLMethod; import org.encog.ml.factory.MLMethodFactory; import org.encog.ml.factory.parse.ArchitectureParse; import org.encog.ml.prg.EncogProgramContext; import org.encog.ml.prg.extension.StandardExtensions; import org.encog.ml.prg.generator.RampedHalfAndHalf; import org.encog.ml.prg.train.PrgPopulation; import org.encog.util.ParamsHolder; public class EPLFactory { /** * Create a feed forward network. * @param architecture The architecture string to use. * @param input The input count. * @param output The output count. * @return The feedforward network. */ public MLMethod create(final String architecture, final int input, final int output) { if( input<=0 ) { throw new EncogError("Must have at least one input for EPL."); } if( output<=0 ) { throw new EncogError("Must have at least one output for EPL."); } final Map<String, String> args = ArchitectureParse.parseParams(architecture); final ParamsHolder holder = new ParamsHolder(args); final int populationSize = holder.getInt( MLMethodFactory.PROPERTY_POPULATION_SIZE, false, 1000); String variables = holder.getString("vars", false, "x"); String funct = holder.getString("funct", false, null); EncogProgramContext context = new EncogProgramContext(); StringTokenizer tok = new StringTokenizer(variables,","); while(tok.hasMoreElements()) { context.defineVariable(tok.nextToken()); } if( "numeric".equalsIgnoreCase(funct) ) { StandardExtensions.createNumericOperators(context); } PrgPopulation pop = new PrgPopulation(context,populationSize); if( context.getFunctions().size()>0 ) { (new RampedHalfAndHalf(context,2,6)).generate(new Random(), pop); } return pop; } }
apache-2.0
ueshin/apache-flink
flink-core/src/main/java/org/apache/flink/configuration/ConfigOptions.java
3558
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.configuration; import org.apache.flink.annotation.PublicEvolving; import static org.apache.flink.util.Preconditions.checkNotNull; /** * {@code ConfigOptions} are used to build a {@link ConfigOption}. * The option is typically built in one of the following pattern: * * <pre>{@code * // simple string-valued option with a default value * ConfigOption<String> tempDirs = ConfigOptions * .key("tmp.dir") * .defaultValue("/tmp"); * * // simple integer-valued option with a default value * ConfigOption<Integer> parallelism = ConfigOptions * .key("application.parallelism") * .defaultValue(100); * * // option with no default value * ConfigOption<String> userName = ConfigOptions * .key("user.name") * .noDefaultValue(); * * // option with deprecated keys to check * ConfigOption<Double> threshold = ConfigOptions * .key("cpu.utilization.threshold") * .defaultValue(0.9). * .withDeprecatedKeys("cpu.threshold"); * }</pre> */ @PublicEvolving public class ConfigOptions { /** * Starts building a new {@link ConfigOption}. * * @param key The key for the config option. * @return The builder for the config option with the given key. */ public static OptionBuilder key(String key) { checkNotNull(key); return new OptionBuilder(key); } // ------------------------------------------------------------------------ /** * The option builder is used to create a {@link ConfigOption}. * It is instantiated via {@link ConfigOptions#key(String)}. */ public static final class OptionBuilder { /** The key for the config option. */ private final String key; /** * Creates a new OptionBuilder. * @param key The key for the config option */ OptionBuilder(String key) { this.key = key; } /** * Creates a ConfigOption with the given default value. * * <p>This method does not accept "null". For options with no default value, choose * one of the {@code noDefaultValue} methods. * * @param value The default value for the config option * @param <T> The type of the default value. * @return The config option with the default value. */ public <T> ConfigOption<T> defaultValue(T value) { checkNotNull(value); return new ConfigOption<>(key, value); } /** * Creates a string-valued option with no default value. * String-valued options are the only ones that can have no * default value. * * @return The created ConfigOption. */ public ConfigOption<String> noDefaultValue() { return new ConfigOption<>(key, null); } } // ------------------------------------------------------------------------ /** Not intended to be instantiated. */ private ConfigOptions() {} }
apache-2.0
DocuSignDev/android-test-kit
espresso/contrib/src/main/java/com/google/android/apps/common/testing/ui/espresso/contrib/DrawerActions.java
8176
package com.google.android.apps.common.testing.ui.espresso.contrib; import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView; import static com.google.android.apps.common.testing.ui.espresso.contrib.DrawerMatchers.isClosed; import static com.google.android.apps.common.testing.ui.espresso.contrib.DrawerMatchers.isOpen; import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isAssignableFrom; import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId; import com.google.android.apps.common.testing.ui.espresso.Espresso; import com.google.android.apps.common.testing.ui.espresso.IdlingResource; import com.google.android.apps.common.testing.ui.espresso.PerformException; import com.google.android.apps.common.testing.ui.espresso.UiController; import com.google.android.apps.common.testing.ui.espresso.ViewAction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.DrawerLayout.DrawerListener; import android.view.View; import org.hamcrest.Matcher; import java.lang.reflect.Field; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nullable; /** * Espresso actions for using a {@link DrawerLayout}. * * @see <a href="http://developer.android.com/design/patterns/navigation-drawer.html">Navigation * drawer design guide</a> */ public final class DrawerActions { private DrawerActions() { // forbid instantiation } private static Field listenerField; /** * Opens the {@link DrawerLayout} with the given id. This method blocks until the drawer is fully * open. No operation if the drawer is already open. */ public static void openDrawer(int drawerLayoutId) { //if the drawer is already open, return. if (checkDrawer(drawerLayoutId, isOpen())) { return; } onView(withId(drawerLayoutId)).perform(registerListener()); onView(withId(drawerLayoutId)).perform(actionOpenDrawer()); } /** * Closes the {@link DrawerLayout} with the given id. This method blocks until the drawer is fully * closed. No operation if the drawer is already closed. */ public static void closeDrawer(int drawerLayoutId) { //if the drawer is already closed, return. if (checkDrawer(drawerLayoutId, isClosed())) { return; } onView(withId(drawerLayoutId)).perform(registerListener()); onView(withId(drawerLayoutId)).perform(actionCloseDrawer()); } /** * Returns true if the given matcher matches the drawer. */ private static boolean checkDrawer(int drawerLayoutId, final Matcher<View> matcher) { final AtomicBoolean matches = new AtomicBoolean(false); onView(withId(drawerLayoutId)).perform(new ViewAction() { @Override public Matcher<View> getConstraints() { return isAssignableFrom(DrawerLayout.class); } @Override public String getDescription() { return "check drawer"; } @Override public void perform(UiController uiController, View view) { matches.set(matcher.matches(view)); } }); return matches.get(); } private static ViewAction actionOpenDrawer() { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isAssignableFrom(DrawerLayout.class); } @Override public String getDescription() { return "open drawer"; } @Override public void perform(UiController uiController, View view) { ((DrawerLayout) view).openDrawer(GravityCompat.START); } }; } private static ViewAction actionCloseDrawer() { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isAssignableFrom(DrawerLayout.class); } @Override public String getDescription() { return "close drawer"; } @Override public void perform(UiController uiController, View view) { ((DrawerLayout) view).closeDrawer(GravityCompat.START); } }; } /** * Returns a {@link ViewAction} that adds an {@link IdlingDrawerListener} as a drawer listener to * the {@link DrawerLayout}. The idling drawer listener wraps any listener that already exists. */ private static ViewAction registerListener() { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isAssignableFrom(DrawerLayout.class); } @Override public String getDescription() { return "register idling drawer listener"; } @Override public void perform(UiController uiController, View view) { DrawerLayout drawer = (DrawerLayout) view; DrawerListener existingListener = getDrawerListener(drawer); if (existingListener instanceof IdlingDrawerListener) { // listener is already registered. No need to assign. return; } drawer.setDrawerListener(IdlingDrawerListener.getInstance(existingListener)); } }; } /** * Pries the current {@link DrawerListener} loose from the cold dead hands of the given * {@link DrawerLayout}. Uses reflection. */ @Nullable private static DrawerListener getDrawerListener(DrawerLayout drawer) { try { if (listenerField == null) { // lazy initialization of reflected field. listenerField = DrawerLayout.class.getDeclaredField("mListener"); listenerField.setAccessible(true); } return (DrawerListener) listenerField.get(drawer); } catch (IllegalArgumentException ex) { // Pity we can't use Java 7 multi-catch for all of these. throw new PerformException.Builder().withCause(ex).build(); } catch (IllegalAccessException ex) { throw new PerformException.Builder().withCause(ex).build(); } catch (NoSuchFieldException ex) { throw new PerformException.Builder().withCause(ex).build(); } catch (SecurityException ex) { throw new PerformException.Builder().withCause(ex).build(); } } /** * Drawer listener that wraps an existing {@link DrawerListener}, and functions as an * {@link IdlingResource} for Espresso. */ private static class IdlingDrawerListener implements DrawerListener, IdlingResource { private static IdlingDrawerListener instance; private static IdlingDrawerListener getInstance(DrawerListener parentListener) { if (instance == null) { instance = new IdlingDrawerListener(); Espresso.registerIdlingResources(instance); } instance.setParentListener(parentListener); return instance; } @Nullable private DrawerListener parentListener; private ResourceCallback callback; // Idle state is only accessible from main thread. private boolean idle = true; public void setParentListener(@Nullable DrawerListener parentListener) { this.parentListener = parentListener; } @Override public void onDrawerClosed(View drawer) { if (parentListener != null) { parentListener.onDrawerClosed(drawer); } } @Override public void onDrawerOpened(View drawer) { if (parentListener != null) { parentListener.onDrawerOpened(drawer); } } @Override public void onDrawerSlide(View drawer, float slideOffset) { if (parentListener != null) { parentListener.onDrawerSlide(drawer, slideOffset); } } @Override public void onDrawerStateChanged(int newState) { if (newState == DrawerLayout.STATE_IDLE) { idle = true; if (callback != null) { callback.onTransitionToIdle(); } } else { idle = false; } if (parentListener != null) { parentListener.onDrawerStateChanged(newState); } } @Override public String getName() { return "IdlingDrawerListener"; } @Override public boolean isIdleNow() { return idle; } @Override public void registerIdleTransitionCallback(ResourceCallback callback) { this.callback = callback; } } }
apache-2.0
zhangzuoqiang/Oceanus
oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/context/SqlType.java
2802
/* * Copyright Beijing 58 Information Technology Co.,Ltd. * * 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.bj58.oceanus.core.context; import java.util.regex.Pattern; /** * SQL类型 * * @author Service Platform Architecture Team (spat@58.com) */ public enum SqlType { INSERT, DELETE, UPDATE, SELECT, SELECT_FOR_UPDATE, REPLACE, TRUNCATE, EXECUTE, CALL, CREATE, DROP, LOAD, MERGE, SHOW, DEFAULT; private static final Pattern SELECT_FOR_UPDATE_PATTERN = Pattern.compile("^select\\s+.*\\s+for\\s+update.*$", Pattern.CASE_INSENSITIVE); public static SqlType getSqlType(String sql) { if(sql==null || sql.trim().length()==0) throw new IllegalArgumentException("Can not parse sql type, sql is empty!"); String upperSql = sql.trim().toUpperCase(); if (upperSql.startsWith(SELECT.name())) { if (SELECT_FOR_UPDATE_PATTERN.matcher(upperSql).matches()) { return SELECT_FOR_UPDATE; } else { return SELECT; } } else if (upperSql.startsWith(SHOW.name())) { return SHOW; } else if (upperSql.startsWith(INSERT.name())) { return INSERT; } else if (upperSql.startsWith(UPDATE.name())) { return UPDATE; } else if (upperSql.startsWith(DELETE.name())) { return DELETE; } else if (upperSql.startsWith(REPLACE.name())) { return REPLACE; } else if (upperSql.startsWith(TRUNCATE.name())){ return TRUNCATE; } else if (upperSql.startsWith(EXECUTE.name())){ return EXECUTE; } else if (upperSql.startsWith(CALL.name())){ return CALL; } else if (upperSql.startsWith(CREATE.name())) { return CREATE; } else if (upperSql.startsWith(DROP.name())) { return DROP; } else if (upperSql.startsWith(LOAD.name())) { return LOAD; } else if (upperSql.startsWith(MERGE.name())){ return MERGE; } else { throw new IllegalArgumentException("Sql is not supported : <"+sql+">"); } } }
apache-2.0
hurricup/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/MavenProjectsStructure.java
47519
/* * 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.idea.maven.navigator; import com.intellij.execution.ProgramRunnerUtil; import com.intellij.execution.RunManager; import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.icons.AllIcons; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.pom.NavigatableAdapter; import com.intellij.psi.xml.XmlElement; import com.intellij.ui.JBColor; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.components.JBList; import com.intellij.ui.treeStructure.*; import com.intellij.util.PathUtil; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import gnu.trove.THashSet; import icons.MavenIcons; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.MavenPluginDomUtil; import org.jetbrains.idea.maven.dom.model.MavenDomProfile; import org.jetbrains.idea.maven.dom.model.MavenDomProfiles; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.dom.model.MavenDomSettingsModel; import org.jetbrains.idea.maven.dom.plugin.MavenDomMojo; import org.jetbrains.idea.maven.dom.plugin.MavenDomPluginModel; import org.jetbrains.idea.maven.execution.MavenRunConfiguration; import org.jetbrains.idea.maven.execution.MavenRunConfigurationType; import org.jetbrains.idea.maven.execution.MavenRunner; import org.jetbrains.idea.maven.model.*; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.tasks.MavenShortcutsManager; import org.jetbrains.idea.maven.tasks.MavenTasksManager; import org.jetbrains.idea.maven.utils.*; import javax.swing.*; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.InputEvent; import java.net.URL; import java.util.*; import java.util.List; import static org.jetbrains.idea.maven.project.ProjectBundle.message; public class MavenProjectsStructure extends SimpleTreeStructure { private static final URL ERROR_ICON_URL = MavenProjectsStructure.class.getResource("/general/error.png"); private static final Collection<String> BASIC_PHASES = MavenConstants.BASIC_PHASES; private static final Collection<String> PHASES = MavenConstants.PHASES; private static final Comparator<MavenSimpleNode> NODE_COMPARATOR = (o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), true); private final Project myProject; private final MavenProjectsManager myProjectsManager; private final MavenTasksManager myTasksManager; private final MavenShortcutsManager myShortcutsManager; private final MavenProjectsNavigator myProjectsNavigator; private final SimpleTreeBuilder myTreeBuilder; private final RootNode myRoot = new RootNode(); private final Map<MavenProject, ProjectNode> myProjectToNodeMapping = new THashMap<>(); public MavenProjectsStructure(Project project, MavenProjectsManager projectsManager, MavenTasksManager tasksManager, MavenShortcutsManager shortcutsManager, MavenProjectsNavigator projectsNavigator, SimpleTree tree) { myProject = project; myProjectsManager = projectsManager; myTasksManager = tasksManager; myShortcutsManager = shortcutsManager; myProjectsNavigator = projectsNavigator; configureTree(tree); myTreeBuilder = new SimpleTreeBuilder(tree, (DefaultTreeModel)tree.getModel(), this, null); Disposer.register(myProject, myTreeBuilder); myTreeBuilder.initRoot(); myTreeBuilder.expand(myRoot, null); } private void configureTree(final SimpleTree tree) { tree.setRootVisible(false); tree.setShowsRootHandles(true); MavenUIUtil.installCheckboxRenderer(tree, new MavenUIUtil.CheckboxHandler() { @Override public void toggle(TreePath treePath, InputEvent e) { SimpleNode node = tree.getNodeFor(treePath); if (node != null) { node.handleDoubleClickOrEnter(tree, e); } } @Override public boolean isVisible(Object userObject) { return userObject instanceof ProfileNode; } @Override public MavenUIUtil.CheckBoxState getState(Object userObject) { MavenProfileKind state = ((ProfileNode)userObject).getState(); switch (state) { case NONE: return MavenUIUtil.CheckBoxState.UNCHECKED; case EXPLICIT: return MavenUIUtil.CheckBoxState.CHECKED; case IMPLICIT: return MavenUIUtil.CheckBoxState.PARTIAL; } MavenLog.LOG.error("unknown profile state: " + state); return MavenUIUtil.CheckBoxState.UNCHECKED; } }); } @Override public RootNode getRootElement() { return myRoot; } public void update() { List<MavenProject> projects = myProjectsManager.getProjects(); Set<MavenProject> deleted = new HashSet<>(myProjectToNodeMapping.keySet()); deleted.removeAll(projects); updateProjects(projects, deleted); } private void updateFrom(SimpleNode node) { myTreeBuilder.addSubtreeToUpdateByElement(node); } private void updateUpTo(SimpleNode node) { SimpleNode each = node; while (each != null) { updateFrom(each); each = each.getParent(); } } public void updateProjects(List<MavenProject> updated, Collection<MavenProject> deleted) { for (MavenProject each : updated) { ProjectNode node = findNodeFor(each); if (node == null) { node = new ProjectNode(each); myProjectToNodeMapping.put(each, node); } doUpdateProject(node); } for (MavenProject each : deleted) { ProjectNode node = myProjectToNodeMapping.remove(each); if (node != null) { ProjectsGroupNode parent = node.getGroup(); parent.remove(node); } } myRoot.updateProfiles(); } private void doUpdateProject(ProjectNode node) { MavenProject project = node.getMavenProject(); ProjectsGroupNode newParentNode = myRoot; if (myProjectsNavigator.getGroupModules()) { MavenProject aggregator = myProjectsManager.findAggregator(project); if (aggregator != null) { ProjectNode aggregatorNode = findNodeFor(aggregator); if (aggregatorNode != null && aggregatorNode.isVisible()) { newParentNode = aggregatorNode.getModulesNode(); } } } node.updateProject(); reconnectNode(node, newParentNode); ProjectsGroupNode newModulesParentNode = myProjectsNavigator.getGroupModules() && node.isVisible() ? node.getModulesNode() : myRoot; for (MavenProject each : myProjectsManager.getModules(project)) { ProjectNode moduleNode = findNodeFor(each); if (moduleNode != null && !moduleNode.getParent().equals(newModulesParentNode)) { reconnectNode(moduleNode, newModulesParentNode); } } } private void reconnectNode(ProjectNode node, ProjectsGroupNode newParentNode) { ProjectsGroupNode oldParentNode = node.getGroup(); if (oldParentNode == null || !oldParentNode.equals(newParentNode)) { if (oldParentNode != null) { oldParentNode.remove(node); } newParentNode.add(node); } else { newParentNode.sortProjects(); } } public void updateProfiles() { myRoot.updateProfiles(); } public void updateIgnored(List<MavenProject> projects) { for (MavenProject each : projects) { ProjectNode node = findNodeFor(each); if (node == null) continue; node.updateIgnored(); } } public void accept(SimpleNodeVisitor visitor) { ((SimpleTree)myTreeBuilder.getTree()).accept(myTreeBuilder, visitor); } public void updateGoals() { for (ProjectNode each : myProjectToNodeMapping.values()) { each.updateGoals(); } } public void updateRunConfigurations() { for (ProjectNode each : myProjectToNodeMapping.values()) { each.updateRunConfigurations(); } } public void select(MavenProject project) { ProjectNode node = findNodeFor(project); if (node != null) select(node); } public void select(SimpleNode node) { myTreeBuilder.select(node, null); } private ProjectNode findNodeFor(MavenProject project) { return myProjectToNodeMapping.get(project); } private boolean isShown(Class aClass) { Class<? extends MavenSimpleNode>[] classes = getVisibleNodesClasses(); if (classes == null) return true; for (Class<? extends MavenSimpleNode> c : classes) { if (c == aClass) { return true; } } return false; } enum DisplayKind { ALWAYS, NEVER, NORMAL } protected Class<? extends MavenSimpleNode>[] getVisibleNodesClasses() { return null; } protected boolean showDescriptions() { return true; } protected boolean showOnlyBasicPhases() { return myProjectsNavigator.getShowBasicPhasesOnly(); } public static <T extends MavenSimpleNode> List<T> getSelectedNodes(SimpleTree tree, Class<T> nodeClass) { final List<T> filtered = new ArrayList<>(); for (SimpleNode node : getSelectedNodes(tree)) { if ((nodeClass != null) && (!nodeClass.isInstance(node))) { filtered.clear(); break; } //noinspection unchecked filtered.add((T)node); } return filtered; } private static List<SimpleNode> getSelectedNodes(SimpleTree tree) { List<SimpleNode> nodes = new ArrayList<>(); TreePath[] treePaths = tree.getSelectionPaths(); if (treePaths != null) { for (TreePath treePath : treePaths) { nodes.add(tree.getNodeFor(treePath)); } } return nodes; } @Nullable public static ProjectNode getCommonProjectNode(Collection<? extends MavenSimpleNode> nodes) { ProjectNode parent = null; for (MavenSimpleNode node : nodes) { ProjectNode nextParent = node.findParent(ProjectNode.class); if (parent == null) { parent = nextParent; } else if (parent != nextParent) { return null; } } return parent; } public enum ErrorLevel { NONE, ERROR } public abstract class MavenSimpleNode extends CachingSimpleNode { private MavenSimpleNode myParent; private ErrorLevel myErrorLevel = ErrorLevel.NONE; private ErrorLevel myTotalErrorLevel = null; public MavenSimpleNode(MavenSimpleNode parent) { super(MavenProjectsStructure.this.myProject, null); setParent(parent); } public void setParent(MavenSimpleNode parent) { myParent = parent; } @Override public NodeDescriptor getParentDescriptor() { return myParent; } public <T extends MavenSimpleNode> T findParent(Class<T> parentClass) { MavenSimpleNode node = this; while (true) { node = node.myParent; if (node == null || parentClass.isInstance(node)) { //noinspection unchecked return (T)node; } } } public boolean isVisible() { return getDisplayKind() != DisplayKind.NEVER; } public DisplayKind getDisplayKind() { Class[] visibles = getVisibleNodesClasses(); if (visibles == null) return DisplayKind.NORMAL; for (Class each : visibles) { if (each.isInstance(this)) return DisplayKind.ALWAYS; } return DisplayKind.NEVER; } @Override protected SimpleNode[] buildChildren() { List<? extends MavenSimpleNode> children = doGetChildren(); if (children.isEmpty()) return NO_CHILDREN; List<MavenSimpleNode> result = new ArrayList<>(); for (MavenSimpleNode each : children) { if (each.isVisible()) result.add(each); } return result.toArray(new MavenSimpleNode[result.size()]); } protected List<? extends MavenSimpleNode> doGetChildren() { return Collections.emptyList(); } @Override public void cleanUpCache() { super.cleanUpCache(); myTotalErrorLevel = null; } protected void childrenChanged() { MavenSimpleNode each = this; while (each != null) { each.cleanUpCache(); each = (MavenSimpleNode)each.getParent(); } updateUpTo(this); } public ErrorLevel getTotalErrorLevel() { if (myTotalErrorLevel == null) { myTotalErrorLevel = calcTotalErrorLevel(); } return myTotalErrorLevel; } private ErrorLevel calcTotalErrorLevel() { ErrorLevel childrenErrorLevel = getChildrenErrorLevel(); return childrenErrorLevel.compareTo(myErrorLevel) > 0 ? childrenErrorLevel : myErrorLevel; } public ErrorLevel getChildrenErrorLevel() { ErrorLevel result = ErrorLevel.NONE; for (SimpleNode each : getChildren()) { ErrorLevel eachLevel = ((MavenSimpleNode)each).getTotalErrorLevel(); if (eachLevel.compareTo(result) > 0) result = eachLevel; } return result; } public void setErrorLevel(ErrorLevel level) { if (myErrorLevel == level) return; myErrorLevel = level; updateUpTo(this); } @Override protected void doUpdate() { setNameAndTooltip(getName(), null); } protected void setNameAndTooltip(String name, @Nullable String tooltip) { setNameAndTooltip(name, tooltip, (String)null); } protected void setNameAndTooltip(String name, @Nullable String tooltip, @Nullable String hint) { setNameAndTooltip(name, tooltip, getPlainAttributes()); if (showDescriptions() && !StringUtil.isEmptyOrSpaces(hint)) { addColoredFragment(" (" + hint + ")", SimpleTextAttributes.GRAY_ATTRIBUTES); } } protected void setNameAndTooltip(String name, @Nullable String tooltip, SimpleTextAttributes attributes) { clearColoredText(); addColoredFragment(name, prepareAttributes(attributes)); getTemplatePresentation().setTooltip(tooltip); } private SimpleTextAttributes prepareAttributes(SimpleTextAttributes from) { ErrorLevel level = getTotalErrorLevel(); Color waveColor = level == ErrorLevel.NONE ? null : JBColor.RED; int style = from.getStyle(); if (waveColor != null) style |= SimpleTextAttributes.STYLE_WAVED; return new SimpleTextAttributes(from.getBgColor(), from.getFgColor(), waveColor, style); } @Nullable @NonNls String getActionId() { return null; } @Nullable @NonNls String getMenuId() { return null; } @Nullable public VirtualFile getVirtualFile() { return null; } @Nullable public Navigatable getNavigatable() { return MavenNavigationUtil.createNavigatableForPom(getProject(), getVirtualFile()); } @Override public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) { String actionId = getActionId(); if (actionId != null) { MavenUIUtil.executeAction(actionId, inputEvent); } } } public abstract class GroupNode extends MavenSimpleNode { public GroupNode(MavenSimpleNode parent) { super(parent); } @Override public boolean isVisible() { if (getDisplayKind() == DisplayKind.ALWAYS) return true; for (SimpleNode each : getChildren()) { if (((MavenSimpleNode)each).isVisible()) return true; } return false; } protected <T extends MavenSimpleNode> void insertSorted(List<T> list, T newObject) { int pos = Collections.binarySearch(list, newObject, NODE_COMPARATOR); list.add(pos >= 0 ? pos : -pos - 1, newObject); } protected void sort(List<? extends MavenSimpleNode> list) { Collections.sort(list, NODE_COMPARATOR); } } public abstract class ProjectsGroupNode extends GroupNode { private final List<ProjectNode> myProjectNodes = new ArrayList<>(); public ProjectsGroupNode(MavenSimpleNode parent) { super(parent); setUniformIcon(MavenIcons.ModulesClosed); } @Override protected List<? extends MavenSimpleNode> doGetChildren() { return myProjectNodes; } @TestOnly public List<ProjectNode> getProjectNodesInTests() { return myProjectNodes; } protected void add(ProjectNode projectNode) { projectNode.setParent(this); insertSorted(myProjectNodes, projectNode); childrenChanged(); } public void remove(ProjectNode projectNode) { projectNode.setParent(null); myProjectNodes.remove(projectNode); childrenChanged(); } public void sortProjects() { sort(myProjectNodes); childrenChanged(); } } public class RootNode extends ProjectsGroupNode { private final ProfilesNode myProfilesNode; public RootNode() { super(null); myProfilesNode = new ProfilesNode(this); } @Override public boolean isVisible() { return true; } @Override protected List<? extends MavenSimpleNode> doGetChildren() { return ContainerUtil.concat(Collections.singletonList(myProfilesNode), super.doGetChildren()); } public void updateProfiles() { myProfilesNode.updateProfiles(); } } public class ProfilesNode extends GroupNode { private List<ProfileNode> myProfileNodes = new ArrayList<>(); public ProfilesNode(MavenSimpleNode parent) { super(parent); setUniformIcon(MavenIcons.ProfilesClosed); } @Override protected List<? extends MavenSimpleNode> doGetChildren() { return myProfileNodes; } @Override public String getName() { return message("view.node.profiles"); } public void updateProfiles() { Collection<Pair<String, MavenProfileKind>> profiles = myProjectsManager.getProfilesWithStates(); List<ProfileNode> newNodes = new ArrayList<>(profiles.size()); for (Pair<String, MavenProfileKind> each : profiles) { ProfileNode node = findOrCreateNodeFor(each.first); node.setState(each.second); newNodes.add(node); } myProfileNodes = newNodes; sort(myProfileNodes); childrenChanged(); } private ProfileNode findOrCreateNodeFor(String profileName) { for (ProfileNode each : myProfileNodes) { if (each.getProfileName().equals(profileName)) return each; } return new ProfileNode(this, profileName); } } public class ProfileNode extends MavenSimpleNode { private final String myProfileName; private MavenProfileKind myState; public ProfileNode(ProfilesNode parent, String profileName) { super(parent); myProfileName = profileName; } @Override public String getName() { return myProfileName; } public String getProfileName() { return myProfileName; } public MavenProfileKind getState() { return myState; } private void setState(MavenProfileKind state) { myState = state; } @Override @Nullable @NonNls protected String getActionId() { return "Maven.ToggleProfile"; } @Nullable @Override public Navigatable getNavigatable() { if (myProject == null) return null; final List<MavenDomProfile> profiles = ContainerUtil.newArrayList(); // search in "Per User Maven Settings" - %USER_HOME%/.m2/settings.xml // and in "Global Maven Settings" - %M2_HOME%/conf/settings.xml for (VirtualFile virtualFile : myProjectsManager.getGeneralSettings().getEffectiveSettingsFiles()) { if (virtualFile != null) { final MavenDomSettingsModel model = MavenDomUtil.getMavenDomModel(myProject, virtualFile, MavenDomSettingsModel.class); if (model != null) { addProfiles(profiles, model.getProfiles().getProfiles()); } } } for (MavenProject mavenProject : myProjectsManager.getProjects()) { // search in "Profile descriptors" - located in project basedir (profiles.xml) final VirtualFile mavenProjectFile = mavenProject.getFile(); final VirtualFile profilesXmlFile = MavenUtil.findProfilesXmlFile(mavenProjectFile); if (profilesXmlFile != null) { final MavenDomProfiles profilesModel = MavenDomUtil.getMavenDomProfilesModel(myProject, profilesXmlFile); if (profilesModel != null) { addProfiles(profiles, profilesModel.getProfiles()); } } // search in "Per Project" - Defined in the POM itself (pom.xml) final MavenDomProjectModel projectModel = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProjectFile); if (projectModel != null) { addProfiles(profiles, projectModel.getProfiles().getProfiles()); } } return getNavigatable(profiles); } private Navigatable getNavigatable(@NotNull final List<MavenDomProfile> profiles) { if (profiles.size() > 1) { return new NavigatableAdapter() { @Override public void navigate(final boolean requestFocus) { final JBList list = new JBList(profiles); list.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component result = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); @SuppressWarnings("unchecked") MavenDomProfile mavenDomProfile = (MavenDomProfile)value; XmlElement xmlElement = mavenDomProfile.getXmlElement(); if (xmlElement != null) { setText(xmlElement.getContainingFile().getVirtualFile().getPath()); } return result; } }); JBPopupFactory.getInstance().createListPopupBuilder(list) .setTitle("Choose file to open ") .setItemChoosenCallback(() -> { final Object value = list.getSelectedValue(); if (value instanceof MavenDomProfile) { final Navigatable navigatable = getNavigatable((MavenDomProfile)value); if (navigatable != null) navigatable.navigate(requestFocus); } }).createPopup().showInFocusCenter(); } }; } else { return getNavigatable(ContainerUtil.getFirstItem(profiles)); } } @Nullable private Navigatable getNavigatable(@Nullable final MavenDomProfile profile) { if (profile == null) return null; XmlElement xmlElement = profile.getId().getXmlElement(); return xmlElement instanceof Navigatable ? (Navigatable)xmlElement : null; } private void addProfiles(@NotNull List<MavenDomProfile> result, @Nullable List<MavenDomProfile> profilesToAdd) { if (profilesToAdd == null) return; for (MavenDomProfile profile : profilesToAdd) { if (StringUtil.equals(profile.getId().getValue(), myProfileName)) { result.add(profile); } } } } public class ProjectNode extends GroupNode { private final MavenProject myMavenProject; private final LifecycleNode myLifecycleNode; private final PluginsNode myPluginsNode; private final DependenciesNode myDependenciesNode; private final ModulesNode myModulesNode; private final RunConfigurationsNode myRunConfigurationsNode; private String myTooltipCache; public ProjectNode(@NotNull MavenProject mavenProject) { super(null); myMavenProject = mavenProject; myLifecycleNode = new LifecycleNode(this); myPluginsNode = new PluginsNode(this); myDependenciesNode = new DependenciesNode(this, mavenProject); myModulesNode = new ModulesNode(this); myRunConfigurationsNode = new RunConfigurationsNode(this); setUniformIcon(MavenIcons.MavenProject); updateProject(); } public MavenProject getMavenProject() { return myMavenProject; } public ProjectsGroupNode getGroup() { return (ProjectsGroupNode)super.getParent(); } @Override public boolean isVisible() { if (!myProjectsNavigator.getShowIgnored() && myProjectsManager.isIgnored(myMavenProject)) return false; return super.isVisible(); } @Override protected List<? extends MavenSimpleNode> doGetChildren() { return Arrays.asList(myLifecycleNode, myPluginsNode, myRunConfigurationsNode, myDependenciesNode, myModulesNode); } public ModulesNode getModulesNode() { return myModulesNode; } private void updateProject() { setErrorLevel(myMavenProject.getProblems().isEmpty() ? ErrorLevel.NONE : ErrorLevel.ERROR); myLifecycleNode.updateGoalsList(); myPluginsNode.updatePlugins(myMavenProject); if (isShown(DependencyNode.class)) { myDependenciesNode.updateDependencies(); } myRunConfigurationsNode.updateRunConfigurations(myMavenProject); myTooltipCache = makeDescription(); updateFrom(getParent()); } public void updateIgnored() { getGroup().childrenChanged(); } public void updateGoals() { updateFrom(myLifecycleNode); updateFrom(myPluginsNode); } public void updateRunConfigurations() { myRunConfigurationsNode.updateRunConfigurations(myMavenProject); updateFrom(myRunConfigurationsNode); } @Override public String getName() { if (myProjectsNavigator.getAlwaysShowArtifactId()) { return myMavenProject.getMavenId().getArtifactId(); } else { return myMavenProject.getDisplayName(); } } @Override protected void doUpdate() { String hint = null; if (!myProjectsNavigator.getGroupModules() && myProjectsManager.findAggregator(myMavenProject) == null && myProjectsManager.getProjects().size() > myProjectsManager.getRootProjects().size()) { hint = "root"; } setNameAndTooltip(getName(), myTooltipCache, hint); } @Override protected SimpleTextAttributes getPlainAttributes() { if (myProjectsManager.isIgnored(myMavenProject)) { return new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, JBColor.GRAY); } return super.getPlainAttributes(); } private String makeDescription() { StringBuilder desc = new StringBuilder(); desc.append("<html>" + "<table>" + "<tr>" + "<td nowrap>" + "<table>" + "<tr>" + "<td nowrap>Project:</td>" + "<td nowrap>").append(myMavenProject.getMavenId()) .append("</td>" + "</tr>" + "<tr>" + "<td nowrap>Location:</td>" + "<td nowrap>").append(myMavenProject.getPath()) .append("</td>" + "</tr>" + "</table>" + "</td>" + "</tr>"); appendProblems(desc); desc.append("</table></html>"); return desc.toString(); } private void appendProblems(StringBuilder desc) { List<MavenProjectProblem> problems = myMavenProject.getProblems(); if (problems.isEmpty()) return; desc.append("<tr>" + "<td nowrap>" + "<table>"); boolean first = true; for (MavenProjectProblem each : problems) { desc.append("<tr>"); if (first) { desc.append("<td nowrap valign=top>").append(MavenUtil.formatHtmlImage(ERROR_ICON_URL)).append("</td>"); desc.append("<td nowrap valign=top>Problems:</td>"); first = false; } else { desc.append("<td nowrap colspan=2></td>"); } desc.append("<td nowrap valign=top>").append(wrappedText(each)).append("</td>"); desc.append("</tr>"); } desc.append("</table>" + "</td>" + "</tr>"); } private String wrappedText(MavenProjectProblem each) { String text = StringUtil.replace(each.getDescription(), new String[]{"<", ">"}, new String[]{"&lt;", "&gt;"}); StringBuilder result = new StringBuilder(); int count = 0; for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); result.append(ch); if (count++ > 80) { if (ch == ' ') { count = 0; result.append("<br>"); } } } return result.toString(); } @Override public VirtualFile getVirtualFile() { return myMavenProject.getFile(); } @Override protected void setNameAndTooltip(String name, @Nullable String tooltip, SimpleTextAttributes attributes) { super.setNameAndTooltip(name, tooltip, attributes); if (myProjectsNavigator.getShowVersions()) { addColoredFragment(":" + myMavenProject.getMavenId().getVersion(), new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, JBColor.GRAY)); } } @Override @Nullable @NonNls protected String getMenuId() { return "Maven.NavigatorProjectMenu"; } } public class ModulesNode extends ProjectsGroupNode { public ModulesNode(ProjectNode parent) { super(parent); setUniformIcon(MavenIcons.ModulesClosed); } @Override public String getName() { return message("view.node.modules"); } } public abstract class GoalsGroupNode extends GroupNode { protected final List<GoalNode> myGoalNodes = new ArrayList<>(); public GoalsGroupNode(MavenSimpleNode parent) { super(parent); } @Override protected List<? extends MavenSimpleNode> doGetChildren() { return myGoalNodes; } } public abstract class GoalNode extends MavenSimpleNode { private final MavenProject myMavenProject; private final String myGoal; private final String myDisplayName; public GoalNode(GoalsGroupNode parent, String goal, String displayName) { super(parent); myMavenProject = findParent(ProjectNode.class).getMavenProject(); myGoal = goal; myDisplayName = displayName; setUniformIcon(MavenIcons.Phase); } public MavenProject getMavenProject() { return myMavenProject; } public String getProjectPath() { return myMavenProject.getPath(); } public String getGoal() { return myGoal; } @Override public String getName() { return myDisplayName; } @Override protected void doUpdate() { String s1 = StringUtil.nullize(myShortcutsManager.getDescription(myMavenProject, myGoal)); String s2 = StringUtil.nullize(myTasksManager.getDescription(myMavenProject, myGoal)); String hint; if (s1 == null) { hint = s2; } else if (s2 == null) { hint = s1; } else { hint = s1 + ", " + s2; } setNameAndTooltip(getName(), null, hint); } @Override protected SimpleTextAttributes getPlainAttributes() { SimpleTextAttributes original = super.getPlainAttributes(); int style = original.getStyle(); Color color = original.getFgColor(); boolean custom = false; if ("test".equals(myGoal) && MavenRunner.getInstance(myProject).getSettings().isSkipTests()) { color = SimpleTextAttributes.GRAYED_ATTRIBUTES.getFgColor(); style |= SimpleTextAttributes.STYLE_STRIKEOUT; custom = true; } if (myGoal.equals(myMavenProject.getDefaultGoal())) { style |= SimpleTextAttributes.STYLE_BOLD; custom = true; } if (custom) return original.derive(style, color, null, null); return original; } @Override @Nullable @NonNls protected String getActionId() { return "Maven.RunBuild"; } @Override @Nullable @NonNls protected String getMenuId() { return "Maven.BuildMenu"; } } public class LifecycleNode extends GoalsGroupNode { public LifecycleNode(ProjectNode parent) { super(parent); for (String goal : PHASES) { myGoalNodes.add(new StandardGoalNode(this, goal)); } setUniformIcon(MavenIcons.PhasesClosed); } @Override public String getName() { return message("view.node.lifecycle"); } public void updateGoalsList() { childrenChanged(); } } public class StandardGoalNode extends GoalNode { public StandardGoalNode(GoalsGroupNode parent, String goal) { super(parent, goal, goal); } @Override public boolean isVisible() { if (showOnlyBasicPhases() && !BASIC_PHASES.contains(getGoal())) return false; return super.isVisible(); } } public class PluginsNode extends GroupNode { private final List<PluginNode> myPluginNodes = new ArrayList<>(); public PluginsNode(ProjectNode parent) { super(parent); setUniformIcon(MavenIcons.PhasesClosed); } @Override public String getName() { return message("view.node.plugins"); } @Override protected List<? extends MavenSimpleNode> doGetChildren() { return myPluginNodes; } public void updatePlugins(MavenProject mavenProject) { List<MavenPlugin> plugins = mavenProject.getDeclaredPlugins(); for (Iterator<PluginNode> itr = myPluginNodes.iterator(); itr.hasNext(); ) { PluginNode each = itr.next(); if (plugins.contains(each.getPlugin())) { each.updatePlugin(); } else { itr.remove(); } } for (MavenPlugin each : plugins) { if (!hasNodeFor(each)) { myPluginNodes.add(new PluginNode(this, each)); } } sort(myPluginNodes); childrenChanged(); } private boolean hasNodeFor(MavenPlugin plugin) { for (PluginNode each : myPluginNodes) { if (each.getPlugin().getMavenId().equals(plugin.getMavenId())) { return true; } } return false; } } public class PluginNode extends GoalsGroupNode { private final MavenPlugin myPlugin; private MavenPluginInfo myPluginInfo; public PluginNode(PluginsNode parent, MavenPlugin plugin) { super(parent); myPlugin = plugin; setUniformIcon(MavenIcons.MavenPlugin); updatePlugin(); } public MavenPlugin getPlugin() { return myPlugin; } @Override public String getName() { return myPluginInfo == null ? myPlugin.getDisplayString() : myPluginInfo.getGoalPrefix(); } @Override protected void doUpdate() { setNameAndTooltip(getName(), null, myPluginInfo != null ? myPlugin.getDisplayString() : null); } public void updatePlugin() { boolean hadPluginInfo = myPluginInfo != null; myPluginInfo = MavenArtifactUtil.readPluginInfo(myProjectsManager.getLocalRepository(), myPlugin.getMavenId()); boolean hasPluginInfo = myPluginInfo != null; setErrorLevel(myPluginInfo == null ? ErrorLevel.ERROR : ErrorLevel.NONE); if (hadPluginInfo == hasPluginInfo) return; myGoalNodes.clear(); if (myPluginInfo != null) { for (MavenPluginInfo.Mojo mojo : myPluginInfo.getMojos()) { myGoalNodes.add(new PluginGoalNode(this, mojo.getQualifiedGoal(), mojo.getGoal(), mojo.getDisplayName())); } } sort(myGoalNodes); updateFrom(this); childrenChanged(); } @Override public boolean isVisible() { // show regardless absence of children return super.isVisible() || getDisplayKind() != DisplayKind.NEVER; } } public class PluginGoalNode extends GoalNode { private final String myUnqualifiedGoal; public PluginGoalNode(PluginNode parent, String goal, String unqualifiedGoal, String displayName) { super(parent, goal, displayName); setUniformIcon(MavenIcons.PluginGoal); myUnqualifiedGoal = unqualifiedGoal; } @Nullable @Override public Navigatable getNavigatable() { PluginNode pluginNode = (PluginNode)getParent(); MavenDomPluginModel pluginModel = MavenPluginDomUtil.getMavenPluginModel(myProject, pluginNode.getPlugin().getGroupId(), pluginNode.getPlugin().getArtifactId(), pluginNode.getPlugin().getVersion()); if (pluginModel == null) return null; for (MavenDomMojo mojo : pluginModel.getMojos().getMojos()) { final XmlElement xmlElement = mojo.getGoal().getXmlElement(); if (xmlElement instanceof Navigatable && Comparing.equal(myUnqualifiedGoal, mojo.getGoal().getStringValue())) { return new NavigatableAdapter() { @Override public void navigate(boolean requestFocus) { ((Navigatable)xmlElement).navigate(requestFocus); } }; } } return null; } } public abstract class BaseDependenciesNode extends GroupNode { protected final MavenProject myMavenProject; private List<DependencyNode> myChildren = new ArrayList<>(); protected BaseDependenciesNode(MavenSimpleNode parent, MavenProject mavenProject) { super(parent); myMavenProject = mavenProject; } public MavenProject getMavenProject() { return myMavenProject; } @Override protected List<? extends MavenSimpleNode> doGetChildren() { return myChildren; } protected void updateChildren(List<MavenArtifactNode> children, MavenProject mavenProject) { List<DependencyNode> newNodes = null; int validChildCount = 0; for (MavenArtifactNode each : children) { if (each.getState() != MavenArtifactState.ADDED && each.getState() != MavenArtifactState.CONFLICT && each.getState() != MavenArtifactState.DUPLICATE) { continue; } if (newNodes == null) { if (validChildCount < myChildren.size()) { DependencyNode currentValidNode = myChildren.get(validChildCount); if (currentValidNode.myArtifact.equals(each.getArtifact())) { if (each.getState() == MavenArtifactState.ADDED) { currentValidNode.updateChildren(each.getDependencies(), mavenProject); } currentValidNode.updateDependency(); validChildCount++; continue; } } newNodes = new ArrayList<>(children.size()); newNodes.addAll(myChildren.subList(0, validChildCount)); } DependencyNode newNode = findOrCreateNodeFor(each, mavenProject, validChildCount); newNodes.add(newNode); if (each.getState() == MavenArtifactState.ADDED) { newNode.updateChildren(each.getDependencies(), mavenProject); } newNode.updateDependency(); } if (newNodes == null) { if (validChildCount == myChildren.size()) { return; // All nodes are valid, child did not changed. } assert validChildCount < myChildren.size(); newNodes = new ArrayList<>(myChildren.subList(0, validChildCount)); } myChildren = newNodes; childrenChanged(); } private DependencyNode findOrCreateNodeFor(MavenArtifactNode artifact, MavenProject mavenProject, int from) { for (int i = from; i < myChildren.size(); i++) { DependencyNode node = myChildren.get(i); if (node.myArtifact.equals(artifact.getArtifact())) { return node; } } return new DependencyNode(this, artifact, mavenProject); } @Override String getMenuId() { return "Maven.DependencyMenu"; } } public class DependenciesNode extends BaseDependenciesNode { public DependenciesNode(ProjectNode parent, MavenProject mavenProject) { super(parent, mavenProject); setUniformIcon(AllIcons.Nodes.PpLibFolder); } @Override public String getName() { return message("view.node.dependencies"); } public void updateDependencies() { updateChildren(myMavenProject.getDependencyTree(), myMavenProject); } } public class DependencyNode extends BaseDependenciesNode { private final MavenArtifact myArtifact; private final MavenArtifactNode myArtifactNode; public DependencyNode(MavenSimpleNode parent, MavenArtifactNode artifactNode, MavenProject mavenProject) { super(parent, mavenProject); myArtifactNode = artifactNode; myArtifact = artifactNode.getArtifact(); setUniformIcon(AllIcons.Nodes.PpLib); } public MavenArtifact getArtifact() { return myArtifact; } @Override public String getName() { return myArtifact.getDisplayStringForLibraryName(); } private String getToolTip() { final StringBuilder myToolTip = new StringBuilder(""); String scope = myArtifactNode.getOriginalScope(); if (StringUtil.isNotEmpty(scope) && !MavenConstants.SCOPE_COMPILE.equals(scope)) { myToolTip.append(scope).append(" "); } if (myArtifactNode.getState() == MavenArtifactState.CONFLICT) { myToolTip.append("omitted for conflict"); if (myArtifactNode.getRelatedArtifact() != null) { myToolTip.append(" with ").append(myArtifactNode.getRelatedArtifact().getVersion()); } } if (myArtifactNode.getState() == MavenArtifactState.DUPLICATE) { myToolTip.append("omitted for duplicate"); } return myToolTip.toString().trim(); } @Override protected void doUpdate() { setNameAndTooltip(getName(), null, getToolTip()); } @Override protected void setNameAndTooltip(String name, @Nullable String tooltip, SimpleTextAttributes attributes) { final SimpleTextAttributes mergedAttributes; if (myArtifactNode.getState() == MavenArtifactState.CONFLICT || myArtifactNode.getState() == MavenArtifactState.DUPLICATE) { mergedAttributes = SimpleTextAttributes.merge(attributes, SimpleTextAttributes.GRAYED_ATTRIBUTES); } else { mergedAttributes = attributes; } super.setNameAndTooltip(name, tooltip, mergedAttributes); } private void updateDependency() { setErrorLevel(myArtifact.isResolved() ? ErrorLevel.NONE : ErrorLevel.ERROR); } @Override public Navigatable getNavigatable() { final MavenArtifactNode parent = myArtifactNode.getParent(); final VirtualFile file; if (parent == null) { file = getMavenProject().getFile(); } else { final MavenId id = parent.getArtifact().getMavenId(); final MavenProject pr = myProjectsManager.findProject(id); file = pr == null ? MavenNavigationUtil.getArtifactFile(getProject(), id) : pr.getFile(); } return file == null ? null : MavenNavigationUtil.createNavigatableForDependency(getProject(), file, getArtifact()); } @Override public boolean isVisible() { // show regardless absence of children return getDisplayKind() != DisplayKind.NEVER; } } public class RunConfigurationsNode extends GroupNode { private final List<RunConfigurationNode> myChildren = new ArrayList<>(); public RunConfigurationsNode(ProjectNode parent) { super(parent); setUniformIcon(MavenIcons.Phase); } @Override public String getName() { return message("view.node.run.configurations"); } @Override protected List<? extends MavenSimpleNode> doGetChildren() { return myChildren; } public void updateRunConfigurations(MavenProject mavenProject) { boolean childChanged = false; Set<RunnerAndConfigurationSettings> settings = new THashSet<>( RunManager.getInstance(myProject).getConfigurationSettingsList(MavenRunConfigurationType.getInstance())); for (Iterator<RunConfigurationNode> itr = myChildren.iterator(); itr.hasNext(); ) { RunConfigurationNode node = itr.next(); if (settings.remove(node.getSettings())) { node.updateRunConfiguration(); } else { itr.remove(); childChanged = true; } } String directory = PathUtil.getCanonicalPath(mavenProject.getDirectory()); int oldSize = myChildren.size(); for (RunnerAndConfigurationSettings cfg : settings) { MavenRunConfiguration mavenRunConfiguration = (MavenRunConfiguration)cfg.getConfiguration(); if (directory.equals(PathUtil.getCanonicalPath(mavenRunConfiguration.getRunnerParameters().getWorkingDirPath()))) { myChildren.add(new RunConfigurationNode(this, cfg)); } } if (oldSize != myChildren.size()) { childChanged = true; sort(myChildren); } if (childChanged) { childrenChanged(); } } } public class RunConfigurationNode extends MavenSimpleNode { private final RunnerAndConfigurationSettings mySettings; public RunConfigurationNode(RunConfigurationsNode parent, RunnerAndConfigurationSettings settings) { super(parent); mySettings = settings; setUniformIcon(ProgramRunnerUtil.getConfigurationIcon(settings, false)); } public RunnerAndConfigurationSettings getSettings() { return mySettings; } @Override public String getName() { return mySettings.getName(); } @Override protected void doUpdate() { setNameAndTooltip(getName(), null, StringUtil.join(((MavenRunConfiguration)mySettings.getConfiguration()).getRunnerParameters().getGoals(), " ")); } @Nullable @Override String getMenuId() { return "Maven.RunConfigurationMenu"; } public void updateRunConfiguration() { } @Override public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) { ProgramRunnerUtil.executeConfiguration(myProject, mySettings, DefaultRunExecutor.getRunExecutorInstance()); } } }
apache-2.0
howepeng/isis
core/metamodel/src/test/java/org/apache/isis/core/metamodel/adapter/oid/VersionTest_valueSemantics.java
1761
/* * 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.isis.core.metamodel.adapter.oid; import java.util.Arrays; import java.util.Date; import java.util.List; import org.apache.isis.core.metamodel.adapter.version.Version; import org.apache.isis.core.unittestsupport.value.ValueTypeContractTestAbstract; public class VersionTest_valueSemantics extends ValueTypeContractTestAbstract<Version> { @Override protected List<Version> getObjectsWithSameValue() { return Arrays.asList( Version.create(123L, null, (Long)null), Version.create(123L, "jimmy", (Long)null), Version.create(123L, null, new Date().getTime()) ); } @Override protected List<Version> getObjectsWithDifferentValue() { return Arrays.asList( Version.create(124L, null, (Long)null), Version.create(125L, null, (Long)null) ); } }
apache-2.0
anoordover/camel
components/camel-web3j/src/test/java/org/apache/camel/component/web3j/Web3jConsumerCatchUpToLatestTransactionsObservableMockTest.java
4375
/** * 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.camel.component.web3j; import org.apache.camel.builder.RouteBuilder; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.web3j.protocol.core.DefaultBlockParameter; import org.web3j.protocol.core.methods.response.Transaction; import rx.Observable; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; import static org.apache.camel.component.web3j.Web3jConstants.CATCH_UP_TO_LATEST_TRANSACTION_OBSERVABLE; import static org.apache.camel.component.web3j.Web3jConstants.OPERATION; import static org.mockito.ArgumentMatchers.any; public class Web3jConsumerCatchUpToLatestTransactionsObservableMockTest extends Web3jMockTestSupport { @Mock private Observable<Transaction> observable; @Test public void successTest() throws Exception { mockError.expectedMinimumMessageCount(0); mockResult.expectedMinimumMessageCount(1); Mockito.when(mockWeb3j.catchUpToLatestTransactionObservable(any(DefaultBlockParameter.class))).thenReturn(observable); Mockito.when(observable.subscribe(any(), any(), any())).thenAnswer(new Answer() { public Subscription answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); ((Action1<Transaction>)args[0]).call(new Transaction()); return subscription; } }); context.start(); mockResult.assertIsSatisfied(); mockError.assertIsSatisfied(); } @Test public void errorTest() throws Exception { mockResult.expectedMessageCount(0); mockError.expectedMinimumMessageCount(1); Mockito.when(mockWeb3j.catchUpToLatestTransactionObservable(any(DefaultBlockParameter.class))).thenReturn(observable); Mockito.when(observable.subscribe(any(), any(), any())).thenAnswer(new Answer() { public Subscription answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); ((Action1<Throwable>)args[1]).call(new RuntimeException("Error")); return subscription; } }); context.start(); mockError.assertIsSatisfied(); mockResult.assertIsSatisfied(); } @Test public void doneTest() throws Exception { mockResult.expectedMessageCount(1); mockResult.expectedHeaderReceived("status", "done"); mockError.expectedMinimumMessageCount(0); Mockito.when(mockWeb3j.catchUpToLatestTransactionObservable(any(DefaultBlockParameter.class))).thenReturn(observable); Mockito.when(observable.subscribe(any(), any(), any())).thenAnswer(new Answer() { public Subscription answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); ((Action0)args[2]).call(); return subscription; } }); context.start(); mockError.assertIsSatisfied(); mockResult.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { errorHandler(deadLetterChannel("mock:error")); from(getUrl() + OPERATION.toLowerCase() + "=" + CATCH_UP_TO_LATEST_TRANSACTION_OBSERVABLE + "&fromBlock=5499965") .to("mock:result"); } }; } }
apache-2.0
fogbeam/Heceta_solr
solr/core/src/java/org/apache/solr/analytics/expression/DualDelegateExpression.java
2843
/* * 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.solr.analytics.expression; /** * Abstraction of an expression that applies a function to two delegate expressions. */ public abstract class DualDelegateExpression extends Expression { protected Expression a; protected Expression b; public DualDelegateExpression(Expression a, Expression b) { this.a = a; this.b = b; } } /** * <code>DivideExpression</code> returns the quotient of 'a' and 'b'. */ class DivideExpression extends DualDelegateExpression { /** * @param a numerator * @param b divisor */ public DivideExpression(Expression a, Expression b) { super(a,b); } @Override public Comparable getValue() { Comparable aComp = a.getValue(); Comparable bComp = b.getValue(); if (aComp==null || bComp==null) { return null; } double div = ((Number)aComp).doubleValue(); div = div / ((Number)bComp).doubleValue(); return new Double(div); } } /** * <code>PowerExpression</code> returns 'a' to the power of 'b'. */ class PowerExpression extends DualDelegateExpression { /** * @param a base * @param b exponent */ public PowerExpression(Expression a, Expression b) { super(a,b); } @Override public Comparable getValue() { Comparable aComp = a.getValue(); Comparable bComp = b.getValue(); if (aComp==null || bComp==null) { return null; } return new Double(Math.pow(((Number)aComp).doubleValue(),((Number)bComp).doubleValue())); } } /** * <code>LogExpression</code> returns the log of the delegate's value given a base number. */ class LogExpression extends DualDelegateExpression { /** * @param a number * @param b base */ public LogExpression(Expression a, Expression b) { super(a,b); } @Override public Comparable getValue() { Comparable aComp = a.getValue(); Comparable bComp = b.getValue(); if (aComp==null || bComp==null) { return null; } return Math.log(((Number)aComp).doubleValue())/Math.log(((Number)bComp).doubleValue()); } }
apache-2.0
dashorst/wicket
wicket-core/src/test/java/org/apache/wicket/markup/html/form/NestedFormsTest.java
4332
/* * 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.wicket.markup.html.form; import java.util.ArrayList; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.markup.IMarkupResourceStreamProvider; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.util.resource.IResourceStream; import org.apache.wicket.util.resource.StringResourceStream; import org.apache.wicket.util.tester.FormTester; import org.apache.wicket.util.tester.WicketTestCase; import org.junit.Test; /** * @author Pedro Santos */ public class NestedFormsTest extends WicketTestCase { /** * */ @Test public void postOrderSequenceSubmittingRootForm() { tester.startPage(TestPage.class); TestPage testPage = (TestPage)tester.getLastRenderedPage(); FormTester formTester = tester.newFormTester("outerForm"); formTester.submit("outerSubmit"); assertEquals(3, testPage.submitSequence.size()); assertEquals(0, testPage.submitSequence.indexOf(testPage.outerSubmit)); assertEquals(1, testPage.submitSequence.indexOf(testPage.innerForm)); assertEquals(2, testPage.submitSequence.indexOf(testPage.outerForm)); } /** * */ @Test public void postOrderSequenceSubmittingInnerForm() { tester.startPage(TestPage.class); TestPage testPage = (TestPage)tester.getLastRenderedPage(); FormTester formTester = tester.newFormTester("outerForm"); formTester.submit("innerForm:innerSubmit"); assertEquals(2, testPage.submitSequence.size()); assertEquals(0, testPage.submitSequence.indexOf(testPage.innerSubmit)); assertEquals(1, testPage.submitSequence.indexOf(testPage.innerForm)); } /** */ public static class TestPage extends WebPage implements IMarkupResourceStreamProvider { /** */ private static final long serialVersionUID = 1L; private List<Component> submitSequence = new ArrayList<Component>(); Form<Void> outerForm; Button outerSubmit; Form<Void> innerForm; Button innerSubmit; /** * Construct. */ public TestPage() { outerForm = new Form<Void>("outerForm") { /** */ private static final long serialVersionUID = 1L; @Override protected void onSubmit() { submitSequence.add(this); } }; add(outerForm); outerSubmit = new Button("outerSubmit") { /** */ private static final long serialVersionUID = 1L; @Override public void onSubmit() { submitSequence.add(this); } }; outerForm.add(outerSubmit); innerForm = new Form<Void>("innerForm") { /** */ private static final long serialVersionUID = 1L; @Override protected void onSubmit() { submitSequence.add(this); } }; outerForm.add(innerForm); innerSubmit = new Button("innerSubmit") { /** */ private static final long serialVersionUID = 1L; @Override public void onSubmit() { submitSequence.add(this); } }; innerForm.add(innerSubmit); } @Override public IResourceStream getMarkupResourceStream(MarkupContainer container, Class<?> containerClass) { return new StringResourceStream( "<html><body>" + "<form wicket:id=\"outerForm\">"// + " <input type=\"submit\" wicket:id=\"outerSubmit\"/>"// + " <form wicket:id=\"innerForm\"><input type=\"submit\" wicket:id=\"innerSubmit\"/></form>"// + "</form>" + // "</body></html>"); } } }
apache-2.0
prestodb/presto
presto-orc/src/main/java/com/facebook/presto/orc/stream/FloatInputStream.java
1953
/* * 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.facebook.presto.orc.stream; import com.facebook.presto.common.block.BlockBuilder; import com.facebook.presto.common.type.Type; import com.facebook.presto.orc.checkpoint.FloatStreamCheckpoint; import java.io.IOException; import static io.airlift.slice.SizeOf.SIZE_OF_FLOAT; import static java.lang.Float.floatToRawIntBits; public class FloatInputStream implements ValueInputStream<FloatStreamCheckpoint> { private final OrcInputStream input; public FloatInputStream(OrcInputStream input) { this.input = input; } @Override public Class<FloatStreamCheckpoint> getCheckpointType() { return FloatStreamCheckpoint.class; } @Override public void seekToCheckpoint(FloatStreamCheckpoint checkpoint) throws IOException { input.seekToCheckpoint(checkpoint.getInputStreamCheckpoint()); } @Override public void skip(long items) throws IOException { long length = items * SIZE_OF_FLOAT; input.skipFully(length); } public float next() throws IOException { return input.readFloat(); } public void nextVector(Type type, int items, BlockBuilder builder) throws IOException { for (int i = 0; i < items; i++) { type.writeLong(builder, floatToRawIntBits(next())); } } }
apache-2.0
Malintha/product-emm
modules/mobile-agents/android/app-catalog/app/src/main/java/org/wso2/app/catalog/services/DynamicClientManager.java
8988
/* * Copyright (c) 2016, 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.app.catalog.services; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.JsonRequest; import com.android.volley.toolbox.StringRequest; import org.json.JSONException; import org.json.JSONObject; import org.wso2.app.catalog.AppCatalogException; import org.wso2.app.catalog.beans.RegistrationProfile; import org.wso2.app.catalog.beans.ServerConfig; import org.wso2.app.catalog.beans.UnregisterProfile; import org.wso2.app.catalog.utils.Constants; import org.wso2.emm.agent.proxy.IDPTokenManagerException; import org.wso2.emm.agent.proxy.IdentityProxy; import org.wso2.emm.agent.proxy.beans.EndPointInfo; import org.wso2.emm.agent.proxy.interfaces.APIResultCallBack; import org.wso2.emm.agent.proxy.utils.ServerUtilities; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ExecutionException; /** * This class is used to register and unregister oauth application. */ public class DynamicClientManager { private static final String TAG = DynamicClientManager.class.getSimpleName(); private static final String USER_ID = "userId"; private static final String CONSUMER_KEY = "consumerKey"; private static final String APPLICATION_NAME = "applicationName"; private static final String BASIC_HEADER = "Basic "; /** * This method is used to register an oauth application in the backend. * * @param profile Payload of the register request. * @param utils Server configurations. * * @return returns consumer key and consumer secret if success. Else returns null * if it fails to register. * @throws AppCatalogException */ public void getClientCredentials(RegistrationProfile profile, ServerConfig utils, Context context, String credentials, APIResultCallBack apiResultCallback) throws AppCatalogException { IdentityProxy.getInstance().setContext(context); EndPointInfo endPointInfo = new EndPointInfo(); String endPoint = utils.getAPIServerURL(context) + Constants.DYNAMIC_CLIENT_REGISTER_ENDPOINT; endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST); endPointInfo.setEndPoint(endPoint); endPointInfo.setRequestParams(profile.toJSON()); endPointInfo.setHeader(BASIC_HEADER + credentials); endPointInfo.setRequestParamsMap(profile.toMap()); sendRequest(endPointInfo, apiResultCallback, Constants.DYNAMIC_CLIENT_REGISTER_REQUEST_CODE); } /** * This method is used to unregister the oauth application that has been * registered at the device authentication. * * @param profile Payload of the unregister request. * @param utils Server configurations * * @return true if unregistration success, else false. * @throws AppCatalogException */ public boolean unregisterClient(UnregisterProfile profile, ServerConfig utils, Context context) throws AppCatalogException { StringBuilder endPoint = new StringBuilder(); endPoint.append(utils.getAPIServerURL(context)); endPoint.append(Constants.DYNAMIC_CLIENT_REGISTER_ENDPOINT); endPoint.append("?" + USER_ID + "=" + profile.getUserId()); endPoint.append("&" + CONSUMER_KEY + "=" + profile.getConsumerKey()); endPoint.append("&" + APPLICATION_NAME + "=" + profile.getApplicationName()); EndPointInfo endPointInfo = new EndPointInfo(); endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.DELETE); endPointInfo.setEndPoint(endPoint.toString()); sendRequest(endPointInfo, null, Constants.DYNAMIC_CLIENT_UNREGISTER_REQUEST_CODE); return true; } /** * This method is used to send requests to backend. * The reason to use this method because the function which is already * available for sending requests is secured with token. Therefor this can be used * to send requests without tokens. */ private void sendRequest(final EndPointInfo endPointInfo, final APIResultCallBack apiResultCallback, final int requestCode) { RequestQueue queue = null; int requestMethod = 0; org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS httpMethod = endPointInfo.getHttpMethod(); switch (httpMethod) { case POST: requestMethod = Request.Method.POST; break; case DELETE: requestMethod = Request.Method.DELETE; break; } try { queue = ServerUtilities.getCertifiedHttpClient(); } catch (IDPTokenManagerException e) { Log.e(TAG, "Failed to retrieve HTTP client", e); } JsonObjectRequest request = null; try { request = new JsonObjectRequest(requestMethod, endPointInfo.getEndPoint(), (endPointInfo.getRequestParams() != null) ? new JSONObject(endPointInfo.getRequestParams()) : null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(TAG, error.toString()); } }) { @Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { String result = new String(response.data); if(org.wso2.emm.agent.proxy.utils.Constants.DEBUG_ENABLED) { if(result != null && !result.isEmpty()) { Log.d(TAG, "Result :" + result); } } Map<String, String> responseParams = new HashMap<>(); responseParams.put(org.wso2.emm.agent.proxy.utils.Constants.SERVER_RESPONSE_BODY, result); responseParams.put(org.wso2.emm.agent.proxy.utils.Constants.SERVER_RESPONSE_STATUS, String.valueOf(response.statusCode)); if (apiResultCallback != null) { apiResultCallback.onReceiveAPIResult(responseParams, requestCode); } return super.parseNetworkResponse(response); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("Accept", "application/json"); headers.put("User-Agent", Constants.USER_AGENT); if (endPointInfo.getHeader() != null && !endPointInfo.getHeader().trim().isEmpty()) { headers.put("Authorization", endPointInfo.getHeader().trim()); } return headers; } }; } catch (JSONException e) { Log.e(TAG, "Failed to parse request JSON", e); } queue.add(request); } }
apache-2.0
yssharma/pig-on-drill
exec/java-exec/src/main/java/org/apache/drill/exec/rpc/TransportCheck.java
2716
/** * 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.drill.exec.rpc; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollServerSocketChannel; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.internal.SystemPropertyUtil; import java.util.Locale; /** * TransportCheck decides whether or not to use the native EPOLL mechanism for communication. */ @SuppressWarnings("unused") public class TransportCheck { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TransportCheck.class); public static final boolean SUPPORTS_EPOLL; static{ String name = SystemPropertyUtil.get("os.name").toLowerCase(Locale.US).trim(); if (!name.startsWith("linux") || SystemPropertyUtil.getBoolean("drill.exec.disable-linux-epoll", false) // /* disable epoll */ || true // ) { SUPPORTS_EPOLL = false; }else{ SUPPORTS_EPOLL = true; } } public static Class<? extends ServerSocketChannel> getServerSocketChannel(){ if(SUPPORTS_EPOLL){ return EpollServerSocketChannel.class; }else{ return NioServerSocketChannel.class; } } public static Class<? extends SocketChannel> getClientSocketChannel(){ if(SUPPORTS_EPOLL){ return EpollSocketChannel.class; }else{ return NioSocketChannel.class; } } public static EventLoopGroup createEventLoopGroup(int nThreads, String prefix) { if(SUPPORTS_EPOLL){ return new EpollEventLoopGroup(nThreads, new NamedThreadFactory(prefix)); }else{ return new NioEventLoopGroup(nThreads, new NamedThreadFactory(prefix)); } } }
apache-2.0
mrgroen/reCAPTCHA
test/javasource/communitycommons/ConversationLog.java
13767
package communitycommons; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import com.mendix.core.Core; import com.mendix.logging.ILogNode; /** * * @author mwe * @date 11-10-2012 * * This class can be used to allow more advanced logging, especially, to LOG short-running-conversations. * * This conversations leave the notions of INFO/DEBUG/TRACE and instead use notion of less details and more details. * See @see section() and @see endSection() methods. See @see setBaseDetailVisibilityLevel about how much detail is visible * * Loglines are marked with the conversation id, so loglines of a single conversation can be aggregated together. * * The ConversationLog has a playback notion, for example, if an exception occurs, all loglines, even the detailed ones which would not be visible otherwise, are displayed. * * A typical logline will look like this: * * * MxSync - [sDvX][Thu 08:56:00] starting module ... FAILED (in 20 ms. 3 hidden) * ^ ^ ^ ^ ^ ^ ^ ^ * | | | | | | | | * lognode | timestamp | LOG message | | nr. of hidden details * | | | | * conversation ID | result | * | | * indent, indicates the level of detail timing behavior * * * */ public class ConversationLog { private final ILogNode log; private final int id; private static final AtomicInteger conversationNumber = new AtomicInteger(); private enum LogType { SECTION_START, NORMAL, SECTION_END, WARNING, ERROR } private static final DateTimeFormatter dateFormat = DateTimeFormat.forPattern("HH:mm:ss"); //DateTimeFormat is thread safe, simpleDateFormat is not! private static class LogLine { final LogType type; final String msg; final long time; final int level; int closed = -1; boolean hasError; int started; final Throwable exception; LogLine(LogType type, String msg, int level, Throwable e) { this.type = type; this.msg = msg; this.time = System.currentTimeMillis(); this.level = level; this.exception = e; } public LogLine(LogType type, String msg, int level) { this(type, msg, level, null); } @Override public String toString() { return msg == null ? "(empty)" : msg.toString(); } } private List<LogLine> messages = new ArrayList<LogLine>(); private int currentlevel = 0; private int flushedUntil = 0; private int basevisiblelevel = 0; private boolean closed = false; /** * Create a new conversion * @param M2ee loglevel to report to */ public ConversationLog(String lognode) { this.log = Core.getLogger(lognode); id = conversationNumber.incrementAndGet(); } /** * Create a new conversion * @param M2ee loglevel to report to * @param Log message of the first section that will be created */ public ConversationLog(String lognode, String firstSection) { this.log = Core.getLogger(lognode); id = conversationNumber.incrementAndGet(); section(firstSection); } /** * @return the Id of this converstion */ public int getId() { return id; } /** * Starts a section. That is, first print the provided then increase the level of detail. * * For each section, timing behavior and result status will be measured. * * Note that all sections should be ended! @see endSection * * If an exception is thrown, that ends the conversation entirely, this constraint can be dropped, * but in all other cases (no- or catched exceptions) all sections should be ended, probably by using finally. * * @param message to print * @param optional message arguments * @return */ public ConversationLog section(String msg, Object... args) { messages.add(new LogLine(LogType.SECTION_START, String.format(msg + " ... ", args), currentlevel)); currentlevel += 1; return this; } public ConversationLog endSection() { return endSection(null); } /** * Ends the current section, generates a report of the section (if visible). * @see section() about when and how to end sections * * @param The result message of this section to be reported back. Defaults to "DONE". * @return */ public ConversationLog endSection(String result) { if (currentlevel < 1) warn("(ConversationLog too many endsection invocations)"); currentlevel -= 1; LogLine l = new LogLine(LogType.SECTION_END, result, currentlevel); for (int i = messages.size() - 1; i >= 0; i--) if (messages.get(i).level == currentlevel && messages.get(i).type == LogType.SECTION_START) { messages.get(i).closed = messages.size(); l.started = i; break; } messages.add(l); flushIfLastLineVisible(); return this; } public void log(String msg, Object... args) { messages.add(new LogLine(LogType.NORMAL, String.format(msg, args), currentlevel)); flushIfLastLineVisible(); } public ConversationLog warn(String msg, Object... args) { return warn(null, msg, args); } public ConversationLog warn(Throwable e, String msg, Object... args) { messages.add(new LogLine(LogType.WARNING, String.format(msg, args), currentlevel, e)); flushIfLastLineVisible(); return this; } public void error(Throwable e) { error(e, e.getMessage()); } public void error(String msg, Object... args) { error(null, msg, args); } public void error(Throwable e, String msg, Object... args) { messages.add(new LogLine(LogType.ERROR, String.format(msg, args), currentlevel, e)); int minlevel = currentlevel; for (int i = messages.size() -1; i >= 0; i--) { LogLine line = messages.get(i); if (line.level <= minlevel) { if (line.hasError) //been there, done that, appereantly there ar multiple errors.. break; line.hasError = true; minlevel = Math.min(minlevel, line.level); //once we seen a lower level, we do not want to go into higher levels anymor } } flush(); //always flush on exceptions } long lastResportedTime = 0; final static int REPORT_INTERVAL = 10; final static int PROGRESSBAR_WIDTH = 10; /** * Reports progress about a batch. The total can default to zero if not provided. * This function is state-less, so many calls to it will not result in heap issues. * * @param msg * @param current * @param total */ public void reportProgress(String msg, long current, long total) { long currentReportTime = System.currentTimeMillis(); boolean report = (currentReportTime - lastResportedTime > REPORT_INTERVAL * 1000) || total == current; if (report) { lastResportedTime = currentReportTime; if (total == 0 || total < current) log.info(String.format("[%s| %d / ?] %s", StringUtils.leftPad("", (long) (PROGRESSBAR_WIDTH + 1), "_"), current, msg )); else { int chars = Math.round((current / total) * PROGRESSBAR_WIDTH); log.info(String.format("[%s%s| %d / %d] %s", StringUtils.leftPad("|", (long) chars, "="), StringUtils.leftPad("", (long) (PROGRESSBAR_WIDTH - chars), "_"), current, total, msg )); } } } public void reportProgress(String msg, float progress) { reportProgress(msg, Math.round(progress * 100), 100); } /** * Sets the detail level of the current conversation. This determines how deep sections can be nested before becoming invisible in the LOG * * If the detail level is for example 3, this means that the contents of the first 2 nested sections are visible. * * This holds only if the loglevel of the M2EE LOG is set to 'INFO'. * If the loglevel is set to 'DEBUG', the effective detail level is always 2 higher than the assigned level. * If the loglevel is set to 'TRACE', all loglines are always visible, regardless the assigned level. * * Use getDetailVisibilityLevel to get the effective visibility level. * * Furthermore, warnings and errors are always visible. * * @param detaillevel The detail level, defaults two 2. */ public ConversationLog setBaseDetailVisibilityLevel(int detaillevel) { this.basevisiblelevel = detaillevel; return this; } /** * Returns the ACTIVE visibility level of this conversation. This depends on the base detail visibility level and the loglevel of the * M2ee node. @see setBaseDetailVisibilityLevel for more info. * @return */ public int getVisibleLogLegel() { return log.isTraceEnabled() ? 1000 : log.isDebugEnabled() ? this.basevisiblelevel + 1 : this.basevisiblelevel; } private void flushIfLastLineVisible() { //flush if this is a visible section if (currentlevel <= getVisibleLogLegel()) flush(); } /** * Force all current known loglines to be written to the M2ee LOG. * @return */ public ConversationLog flush() { int hidden = 0; int actuallevel = getVisibleLogLegel(); while (flushedUntil < messages.size()) { LogLine line = messages.get(flushedUntil); switch (line.type) { case ERROR: writeToLog(line, (line.msg != null ? line.msg : line.exception != null ? line.exception.getMessage() : "")); break; case WARNING: writeToLog(line,(line.msg != null ? line.msg : line.exception != null ? line.exception.getMessage() : "")); break; case NORMAL: if (line.level <= actuallevel || line.hasError) writeToLog(line); else hidden += 1; break; case SECTION_START: /** * error INSIDE this section? */ if (line.hasError && flushedUntil + 1 < messages.size() /*avoid out of bounds*/) { LogLine nextline = messages.get(flushedUntil + 1); //is the error ínside this section? if (nextline.hasError && nextline.type != LogType.SECTION_END) writeToLog(line); } /** * visible level and not ended yet. We are flushing so we want to display that the section did start */ else if (line.level <= actuallevel && line.closed == -1) writeToLog(line); /** * section is ended, but there are submessages and they are visible. Show begin */ else if (line.closed > flushedUntil + 1 && line.level < actuallevel) writeToLog(line); /** * we are flushing a subsection of the current section, that is, there are visible messages inside this section, * even if this section is not closed. Note that this only works because the following holds. * * - The SECTION is not closed yet (it would have been flushed earlier otherwise) * - Something triggered a flush (ENDSECTION or ERROR) which is inside this section (it would have feen flushed earlier otherwise) * */ else if (flushedUntil < messages.size() && line.level < actuallevel && line.closed == 0) writeToLog(line); /** * Not printing, report hidden */ else if (line.level >= actuallevel) hidden += 1; //all other cases, this line is written by end_section break; case SECTION_END: LogLine begin = this.messages.get(line.started); boolean outputline = false; /** * begin section has error, generate report */ if (begin.hasError) outputline = true; /** * visible, but empty section, generate report */ else if (line.level <= actuallevel) outputline = true; if (outputline) { String hiddenmsg = hidden == 0 ? "": String.format("%d hidden", hidden); String statusmsg = line.msg == null ? "DONE" : line.msg; long delta = line.time - begin.time; String msg = String.format("%s %s (in %d ms. %s)", begin.msg, statusmsg, delta, hiddenmsg); writeToLog(line, msg); } //reset hidden if (line.level >= actuallevel) hidden = 0; break; } flushedUntil += 1; } return this; } private void writeToLog(LogLine line) { writeToLog(line, line.msg); } private void writeToLog(LogLine line, String msg) { String base = String.format("[%04d][%s]%s %s", this.getId(), dateFormat.print(line.time), StringUtils.leftPad("", line.level * 4L, " "), msg ); switch(line.type) { case ERROR: log.error(base, line.exception); break; case NORMAL: case SECTION_END: case SECTION_START: log.info(base); break; case WARNING: log.warn(base, line.exception); break; } if (closed) log.warn(String.format("[%s] (Objection! Messages were added to the conversation after being closed!)", this.id)); } /** * Closes the conversation. This is a kind of assertion to see if your code properly ends all sections. Warnings are printed otherwise. */ public void close() { if (flushedUntil < messages.size()) { flush(); } if (currentlevel > 0) log.warn(String.format("[%04d] (Objection! Being destructed, but found %d unclosed sections. The conversation did not end normally?)", getId(), currentlevel)); this.closed = true; } @Override public String toString() { return messages.toString(); } @Override protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } public int getCurrentLevel() { return currentlevel; } }
apache-2.0
272029252/Kylin
jdbc/src/test/java/org/apache/kylin/jdbc/DummyClient.java
3372
/* * 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.kylin.jdbc; import java.sql.Types; import java.util.ArrayList; import java.util.List; import net.hydromatic.avatica.AvaticaStatement; import net.hydromatic.avatica.ColumnMetaData; import net.hydromatic.avatica.ColumnMetaData.Rep; import net.hydromatic.linq4j.Enumerator; import org.apache.kylin.jdbc.stub.ConnectionException; import org.apache.kylin.jdbc.stub.DataSet; import org.apache.kylin.jdbc.stub.RemoteClient; /** * @author xduo * */ public class DummyClient implements RemoteClient { public DummyClient(KylinConnectionImpl conn) { } @Override public void connect() throws ConnectionException { } @Override public KylinMetaImpl.MetaProject getMetadata(String project) throws ConnectionException { List<ColumnMetaData> meta = new ArrayList<ColumnMetaData>(); for (int i = 0; i < 10; i++) { meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true)); } List<KylinMetaImpl.MetaTable> tables = new ArrayList<KylinMetaImpl.MetaTable>(); KylinMetaImpl.MetaTable table = new KylinMetaImpl.MetaTable("dummy", "dummy", "dummy", "dummy", "dummy", "dummy", "dummy", "dummy", "dummy", "dummy", new ArrayList<KylinMetaImpl.MetaColumn>()); tables.add(table); List<KylinMetaImpl.MetaSchema> schemas = new ArrayList<KylinMetaImpl.MetaSchema>(); schemas.add(new KylinMetaImpl.MetaSchema("dummy", "dummy", tables)); List<KylinMetaImpl.MetaCatalog> catalogs = new ArrayList<KylinMetaImpl.MetaCatalog>(); catalogs.add(new KylinMetaImpl.MetaCatalog("dummy", schemas)); return new KylinMetaImpl.MetaProject(null, catalogs); } @Override public DataSet<Object[]> query(AvaticaStatement statement, String sql) { List<Object[]> data = new ArrayList<Object[]>(); Object[] row = new Object[] { "foo", "bar", "tool" }; data.add(row); Enumerator<Object[]> enumerator = new KylinEnumerator<Object[]>(data); List<ColumnMetaData> meta = new ArrayList<ColumnMetaData>(); meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true)); meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true)); meta.add(ColumnMetaData.dummy(ColumnMetaData.scalar(Types.VARCHAR, "varchar", Rep.STRING), true)); return new DataSet<Object[]>(meta, enumerator); } }
apache-2.0
aurbroszniowski/ehcache3
core/src/main/java/org/ehcache/core/config/package-info.java
825
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Package holding some core implementations related to configuration such as * {@link org.ehcache.core.config.ResourcePoolsImpl} and {@link org.ehcache.core.config.DefaultConfiguration}. */ package org.ehcache.core.config;
apache-2.0
netbear/CloudAnts
yscb/src/com/yahoo/ycsb/TerminatorThread.java
4048
/** * Copyright (c) 2011 Yahoo! Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package com.yahoo.ycsb; import java.util.Vector; /** * A thread that waits for the maximum specified time and then interrupts all the client * threads passed as the Vector at initialization of this thread. * * The maximum execution time passed is assumed to be in seconds. * * @author sudipto * */ public class TerminatorThread extends Thread { private Vector<Thread> threads; private long maxExecutionTime; private Workload workload; private long waitTimeOutInMS; public TerminatorThread(long maxExecutionTime, Vector<Thread> threads, Workload workload) { this.maxExecutionTime = maxExecutionTime; this.threads = threads; this.workload = workload; waitTimeOutInMS = 2000; System.err.println("Maximum execution time specified as: " + maxExecutionTime + " secs"); } public void run() { try { Thread.sleep(maxExecutionTime * 1000); } catch (InterruptedException e) { System.err.println("Could not wait until max specified time, TerminatorThread interrupted."); return; } System.err.println("Maximum time elapsed. Requesting stop for the workload."); workload.requestStop(); System.err.println("Stop requested for workload. Now Joining!"); for (Thread t : threads) { while (t.isAlive()) { try { t.join(waitTimeOutInMS); if (t.isAlive()) { System.err.println("Still waiting for thread " + t.getName() + " to complete. " + "Workload status: " + workload.isStopRequested()); } } catch (InterruptedException e) { // Do nothing. Don't know why I was interrupted. } } } } }
apache-2.0
addozhang/flume-ng-elasticsearch-sink
src/main/java/org/apache/flume/sink/elasticsearch/ElasticSearchEventSerializer.java
1836
/* * 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.flume.sink.elasticsearch; import java.io.IOException; import java.nio.charset.Charset; import org.apache.flume.Event; import org.apache.flume.conf.Configurable; import org.apache.flume.conf.ConfigurableComponent; import org.elasticsearch.common.io.BytesStream; /** * Interface for an event serializer which serializes the headers and body of an * event to write them to ElasticSearch. This is configurable, so any config * params required should be taken through this. */ public interface ElasticSearchEventSerializer extends Configurable, ConfigurableComponent { public static final Charset charset = Charset.defaultCharset(); /** * Return an {@link BytesStream} made up of the serialized flume event * @param event * The flume event to serialize * @return A {@link BytesStream} used to write to ElasticSearch * @throws IOException * If an error occurs during serialization */ abstract BytesStream getContentBuilder(Event event) throws IOException; }
apache-2.0
ric2b/Vivaldi-browser
chromium/chrome/browser/video_tutorials/android/java/src/org/chromium/chrome/browser/video_tutorials/iph/VideoTutorialIPHUtils.java
3516
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.video_tutorials.iph; import androidx.annotation.Nullable; import org.chromium.chrome.browser.video_tutorials.FeatureType; import org.chromium.components.feature_engagement.EventConstants; import org.chromium.components.feature_engagement.FeatureConstants; /** * Handles various feature utility functions associated with video tutorials IPH. */ public class VideoTutorialIPHUtils { /** * @return The feature name to be used in IPH backend for the given {@code featureType} in order * to show the feature IPH on NTP. */ public static @Nullable String getFeatureNameForNTP(@FeatureType int featureType) { switch (featureType) { case FeatureType.SUMMARY: return FeatureConstants.VIDEO_TUTORIAL_NTP_SUMMARY_FEATURE; case FeatureType.CHROME_INTRO: return FeatureConstants.VIDEO_TUTORIAL_NTP_CHROME_INTRO_FEATURE; case FeatureType.DOWNLOAD: return FeatureConstants.VIDEO_TUTORIAL_NTP_DOWNLOAD_FEATURE; case FeatureType.SEARCH: return FeatureConstants.VIDEO_TUTORIAL_NTP_SEARCH_FEATURE; case FeatureType.VOICE_SEARCH: return FeatureConstants.VIDEO_TUTORIAL_NTP_VOICE_SEARCH_FEATURE; default: // It's possible that there are more feature types known to server than the client. // Don't show an IPH for those tutorials. return null; } } /** * @return The event used in IPH backend when the IPH associated with the {@code featureType} * on NTP is clicked. */ public static String getClickEvent(@FeatureType int featureType) { switch (featureType) { case FeatureType.SUMMARY: return EventConstants.VIDEO_TUTORIAL_CLICKED_SUMMARY; case FeatureType.CHROME_INTRO: return EventConstants.VIDEO_TUTORIAL_CLICKED_CHROME_INTRO; case FeatureType.DOWNLOAD: return EventConstants.VIDEO_TUTORIAL_CLICKED_DOWNLOAD; case FeatureType.SEARCH: return EventConstants.VIDEO_TUTORIAL_CLICKED_SEARCH; case FeatureType.VOICE_SEARCH: return EventConstants.VIDEO_TUTORIAL_CLICKED_VOICE_SEARCH; default: assert false; return null; } } /** * @return The event used in IPH backend when the IPH associated with the {@code featureType} * on NTP is dismissed. */ public static String getDismissEvent(@FeatureType int featureType) { switch (featureType) { case FeatureType.SUMMARY: return EventConstants.VIDEO_TUTORIAL_DISMISSED_SUMMARY; case FeatureType.CHROME_INTRO: return EventConstants.VIDEO_TUTORIAL_DISMISSED_CHROME_INTRO; case FeatureType.DOWNLOAD: return EventConstants.VIDEO_TUTORIAL_DISMISSED_DOWNLOAD; case FeatureType.SEARCH: return EventConstants.VIDEO_TUTORIAL_DISMISSED_SEARCH; case FeatureType.VOICE_SEARCH: return EventConstants.VIDEO_TUTORIAL_DISMISSED_VOICE_SEARCH; default: assert false; return null; } } }
bsd-3-clause
scheib/chromium
components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/TaskInfo.java
27028
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.background_task_scheduler; import android.content.Context; import android.os.Bundle; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * TaskInfo represents a request to run a specific {@link BackgroundTask} given the required * parameters, such as whether a special type of network is available. */ public class TaskInfo { public static final String SERIALIZED_TASK_EXTRAS = "serialized_task_extras"; private static final String TAG = "BkgrdTaskInfo"; /** * Common interface for all types of task information. */ public interface TimingInfo { /** * Receives a {@link TimingInfoVisitor}, which will perform actions on this object. * @param visitor object that will perform actions on this instance. */ void accept(TimingInfoVisitor visitor); } /** * Common interface for actions over TimingInfo implementations. * * This implements the Visitor design pattern over {@link TimingInfo} objects. * For a guide on how to use it, see the `Performing actions over TimingInfo objects` section * in //components/background_task_scheduler/README.md. */ public interface TimingInfoVisitor { /** * Applies actions on a given {@link OneOffInfo}. This affects information regarding * timing for a one-off task. * @param oneOffInfo object to act on. */ void visit(OneOffInfo oneOffInfo); /** * Applies actions on a given {@link PeriodicInfo}. This affects information regarding * timing for a periodic task. * @param periodicInfo object to act on. */ void visit(PeriodicInfo periodicInfo); /** * Applies actions on a given {@link ExactInfo}. This affects information regarding * timing for an exact task. * @param exactInfo object to act on. */ void visit(ExactInfo exactInfo); } /** * Specifies information regarding one-off tasks. */ public static class OneOffInfo implements TimingInfo { private final long mWindowStartTimeMs; private final long mWindowEndTimeMs; private final boolean mHasWindowStartTimeConstraint; private final boolean mExpiresAfterWindowEndTime; private OneOffInfo(Builder builder) { mWindowStartTimeMs = builder.mWindowStartTimeMs; mWindowEndTimeMs = builder.mWindowEndTimeMs; mHasWindowStartTimeConstraint = builder.mHasWindowStartTimeConstraint; mExpiresAfterWindowEndTime = builder.mExpiresAfterWindowEndTime; } /** * @return the start of the window that the task can begin executing as a delta in * milliseconds from now. */ public long getWindowStartTimeMs() { return mWindowStartTimeMs; } /** * @return the end of the window that the task can begin executing as a delta in * milliseconds from now. */ public long getWindowEndTimeMs() { return mWindowEndTimeMs; } /** * @return whether this one-off task has a window start time constraint. */ public boolean hasWindowStartTimeConstraint() { return mHasWindowStartTimeConstraint; } /** * @return whether this one-off task expires after {@link #getWindowEndTimeMs()} * False by default. */ public boolean expiresAfterWindowEndTime() { return mExpiresAfterWindowEndTime; } /** * Checks if a one-off task expired. * @param scheduleTimeMs the time at which the task was scheduled. * @param endTimeMs the time at which the task was set to expire. * @param currentTimeMs the current time to check for expiration. * @return true if the task expired and false otherwise. */ public static boolean getExpirationStatus( long scheduleTimeMs, long endTimeMs, long currentTimeMs) { return currentTimeMs >= scheduleTimeMs + endTimeMs; } @Override public void accept(TimingInfoVisitor visitor) { visitor.visit(this); } @Override public String toString() { StringBuilder sb = new StringBuilder("{"); if (hasWindowStartTimeConstraint()) { sb.append("windowStartTimeMs: ").append(mWindowStartTimeMs).append(", "); } sb.append("windowEndTimeMs: ").append(mWindowEndTimeMs).append(", "); sb.append("expiresAfterWindowEndTime (+flex): ").append(mExpiresAfterWindowEndTime); sb.append("}"); return sb.toString(); } /** * @return a new {@link Builder} object to set the values of the one-off task. */ public static Builder create() { return new Builder(); } /** * A helper builder to provide a way to build {@link OneOffInfo}. * * @see #create() */ public static final class Builder { private long mWindowStartTimeMs; private long mWindowEndTimeMs; // By default, a {@link OneOffInfo} doesn't have a set start time. The start time is // considered the time of scheduling the task. private boolean mHasWindowStartTimeConstraint; // By default, a {@link OneOffInfo} doesn't have the expiration feature activated. private boolean mExpiresAfterWindowEndTime; public Builder setWindowStartTimeMs(long windowStartTimeMs) { mWindowStartTimeMs = windowStartTimeMs; mHasWindowStartTimeConstraint = true; return this; } public Builder setWindowEndTimeMs(long windowEndTimeMs) { mWindowEndTimeMs = windowEndTimeMs; return this; } public Builder setExpiresAfterWindowEndTime(boolean expiresAfterWindowEndTime) { mExpiresAfterWindowEndTime = expiresAfterWindowEndTime; return this; } /** * Build the {@link OneOffInfo object} specified by this builder. * * @return the {@link OneOffInfo} object. */ public OneOffInfo build() { return new OneOffInfo(this); } } } /** * Specifies information regarding periodic tasks. */ public static class PeriodicInfo implements TimingInfo { private final long mIntervalMs; private final long mFlexMs; private final boolean mHasFlex; private final boolean mExpiresAfterWindowEndTime; private PeriodicInfo(PeriodicInfo.Builder builder) { mIntervalMs = builder.mIntervalMs; mFlexMs = builder.mFlexMs; mHasFlex = builder.mHasFlex; mExpiresAfterWindowEndTime = builder.mExpiresAfterWindowEndTime; } /** * @return the interval between occurrences of this task in milliseconds. */ public long getIntervalMs() { return mIntervalMs; } /** * @return the flex time for this task. The task can execute at any time in a window of flex * length at the end of the period. It is reported in milliseconds. */ public long getFlexMs() { return mFlexMs; } /** * @return true whether this task has defined a flex time. False otherwise. */ public boolean hasFlex() { return mHasFlex; } /** * @return whether this periodic task expires after {@link #getIntervalMs()} + * {@link #getFlexMs()} * False by default. */ public boolean expiresAfterWindowEndTime() { return mExpiresAfterWindowEndTime; } /** * Checks if a periodic task expired. * @param scheduleTimeMs the time at which the task was scheduled. * @param intervalTimeMs the interval at which the periodic task was scheduled. * @param flexTimeMs the flex time of the task, either set by the caller or the default one. * @param currentTimeMs the current time to check for expiration. * @return true if the task expired and false otherwise. */ public static boolean getExpirationStatus( long scheduleTimeMs, long intervalTimeMs, long flexTimeMs, long currentTimeMs) { // Whether the task is executed during the wanted time window is determined here. The // position of the current time in relation to the time window is calculated here. // This position is compared with the time window margins. // For example, if a task is scheduled at 6am with an interval of 5h and a flex of // 5min, the valid starting times in that day are: 10:55am to 11am, 3:55pm to 4pm and // 8:55pm to 9pm. For 7pm as the current time, the time in the interval window is 3h. // This is not inside a valid starting time, so the task is considered expired. // Similarly, for 8:58pm as the current time, the time in the interval window is 4h // and 58min, which fits in a valid interval window. // In the case of a flex value equal or bigger than the interval value, the task // never expires. long timeSinceScheduledMs = currentTimeMs - scheduleTimeMs; long deltaTimeComparedToWindowMs = timeSinceScheduledMs % intervalTimeMs; return deltaTimeComparedToWindowMs < intervalTimeMs - flexTimeMs && flexTimeMs < intervalTimeMs; } @Override public void accept(TimingInfoVisitor visitor) { visitor.visit(this); } @Override public String toString() { StringBuilder sb = new StringBuilder("{"); sb.append("intervalMs: ").append(mIntervalMs).append(", "); if (mHasFlex) { sb.append(", flexMs: ").append(mFlexMs).append(", "); } sb.append("expiresAfterWindowEndTime (+flex): ").append(mExpiresAfterWindowEndTime); sb.append("}"); return sb.toString(); } /** * @return a new {@link OneOffInfo.Builder} object to set the values of the one-off task. */ public static PeriodicInfo.Builder create() { return new PeriodicInfo.Builder(); } /** * A helper builder to provide a way to build {@link OneOffInfo}. * * @see #create() */ public static final class Builder { private long mIntervalMs; private long mFlexMs; // By default, a {@link PeriodicInfo} doesn't have a specified flex and the default // one will be used in the scheduler. private boolean mHasFlex; // By default, a {@link PeriodicInfo} doesn't have the expiration feature activated. private boolean mExpiresAfterWindowEndTime; public Builder setIntervalMs(long intervalMs) { mIntervalMs = intervalMs; return this; } public Builder setFlexMs(long flexMs) { mFlexMs = flexMs; mHasFlex = true; return this; } public Builder setExpiresAfterWindowEndTime(boolean expiresAfterWindowEndTime) { mExpiresAfterWindowEndTime = expiresAfterWindowEndTime; return this; } /** * Build the {@link PeriodicInfo object} specified by this builder. * * @return the {@link PeriodicInfo} object. */ public PeriodicInfo build() { return new PeriodicInfo(this); } } } /** * Specifies information regarding exact tasks. */ public static class ExactInfo implements TimingInfo { private final long mTriggerAtMs; private ExactInfo(Builder builder) { mTriggerAtMs = builder.mTriggerAtMs; } public long getTriggerAtMs() { return mTriggerAtMs; } @Override public void accept(TimingInfoVisitor visitor) { visitor.visit(this); } @Override public String toString() { StringBuilder sb = new StringBuilder("{"); sb.append("triggerAtMs: ").append(mTriggerAtMs).append("}"); return sb.toString(); } /** * TODO(crbug.com/1190755): Either remove this or make sure it's compatible with Android S. * Warning: This functionality might get removed, check with OWNERS before using this in new * code: //components/background_task_scheduler/OWNERS. * @return a new {@link Builder} object to set the values of the exact task. */ public static Builder create() { return new Builder(); } /** * A helper builder to provide a way to build {@link ExactInfo}. * * @see #create() */ public static final class Builder { private long mTriggerAtMs; /** * Sets the exact UTC timestamp at which to schedule the exact task. * @param triggerAtMs the UTC timestamp at which the task should be started. * @return the {@link Builder} for creating the {@link ExactInfo} object. */ public Builder setTriggerAtMs(long triggerAtMs) { mTriggerAtMs = triggerAtMs; return this; } /** * Build the {@link ExactInfo object} specified by this builder. * * @return the {@link ExactInfo} object. */ public ExactInfo build() { return new ExactInfo(this); } } } @IntDef({NetworkType.NONE, NetworkType.ANY, NetworkType.UNMETERED}) @Retention(RetentionPolicy.SOURCE) public @interface NetworkType { /** * This task has no requirements for network connectivity. Default. * * @see NetworkType */ int NONE = 0; /** * This task requires network connectivity. * * @see NetworkType */ int ANY = 1; /** * This task requires network connectivity that is unmetered. * * @see NetworkType */ int UNMETERED = 2; } /** * The task ID should be unique across all tasks. A list of such unique IDs exists in * {@link TaskIds}. */ private final int mTaskId; /** * The extras to provide to the {@link BackgroundTask} when it is run. */ @NonNull private final Bundle mExtras; /** * The type of network the task requires to run. */ @NetworkType private final int mRequiredNetworkType; /** * Whether the task requires charging to run. */ private final boolean mRequiresCharging; /** * Whether or not to persist this task across device reboots. */ private final boolean mIsPersisted; /** * Whether this task should override any preexisting tasks with the same task id. */ private final boolean mUpdateCurrent; /** * Task information regarding a type of task. */ private final TimingInfo mTimingInfo; private TaskInfo(Builder builder) { mTaskId = builder.mTaskId; mExtras = builder.mExtras == null ? new Bundle() : builder.mExtras; mRequiredNetworkType = builder.mRequiredNetworkType; mRequiresCharging = builder.mRequiresCharging; mIsPersisted = builder.mIsPersisted; mUpdateCurrent = builder.mUpdateCurrent; mTimingInfo = builder.mTimingInfo; } /** * @return the unique ID of this task. */ public int getTaskId() { return mTaskId; } /** * @return the extras that will be provided to the {@link BackgroundTask}. */ @NonNull public Bundle getExtras() { return mExtras; } /** * @return the type of network the task requires to run. */ @NetworkType public int getRequiredNetworkType() { return mRequiredNetworkType; } /** * @return whether the task requires charging to run. */ public boolean requiresCharging() { return mRequiresCharging; } /** * @return whether or not to persist this task across device reboots. */ public boolean isPersisted() { return mIsPersisted; } /** * @return whether this task should override any preexisting tasks with the same task id. */ public boolean shouldUpdateCurrent() { return mUpdateCurrent; } /** * @return Whether or not this task is a periodic task. */ @Deprecated public boolean isPeriodic() { return mTimingInfo instanceof PeriodicInfo; } /** * This is part of a {@link TaskInfo} iff the task is a one-off task. * * @return the specific data if it is a one-off tasks and null otherwise. */ @Deprecated public OneOffInfo getOneOffInfo() { if (mTimingInfo instanceof OneOffInfo) return (OneOffInfo) mTimingInfo; return null; } /** * This is part of a {@link TaskInfo} iff the task is a periodic task. * * @return the specific data that if it is a periodic tasks and null otherwise. */ @Deprecated public PeriodicInfo getPeriodicInfo() { if (mTimingInfo instanceof PeriodicInfo) return (PeriodicInfo) mTimingInfo; return null; } /** * @return the specific data based on the type of task. */ public TimingInfo getTimingInfo() { return mTimingInfo; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("taskId: ").append(mTaskId); sb.append(", extras: ").append(mExtras); sb.append(", requiredNetworkType: ").append(mRequiredNetworkType); sb.append(", requiresCharging: ").append(mRequiresCharging); sb.append(", isPersisted: ").append(mIsPersisted); sb.append(", updateCurrent: ").append(mUpdateCurrent); sb.append(", timingInfo: ").append(mTimingInfo); sb.append("}"); return sb.toString(); } /** * Creates a task that holds all information necessary to schedule it. * * @param taskId the unique task ID for this task. Should be listed in {@link TaskIds}. * @param timingInfo the task information specific to each type of task. * @return the builder which can be used to continue configuration and {@link Builder#build()}. * @see TaskIds */ public static Builder createTask(int taskId, TimingInfo timingInfo) { return new Builder(taskId).setTimingInfo(timingInfo); } /** * Schedule a one-off task to execute within a deadline. If windowEndTimeMs is 0, the task will * run as soon as possible. For executing a task within a time window, see * {@link #createOneOffTask(int, long, long)}. * * @param taskId the unique task ID for this task. Should be listed in {@link TaskIds}. * @param windowEndTimeMs the end of the window that the task can begin executing as a delta in * milliseconds from now. Note that the task begins executing at this point even if the * prerequisite conditions are not met. * @return the builder which can be used to continue configuration and {@link Builder#build()}. * @see TaskIds * * @deprecated the {@see #createTask(int, Class, TimingInfo)} method should be used instead. * This method requires an additional step for the caller: the creation of the specific * {@link TimingInfo} object with the wanted properties. */ @Deprecated public static Builder createOneOffTask(int taskId, long windowEndTimeMs) { TimingInfo oneOffInfo = OneOffInfo.create().setWindowEndTimeMs(windowEndTimeMs).build(); return new Builder(taskId).setTimingInfo(oneOffInfo); } /** * Schedule a one-off task to execute within a time window. For executing a task within a * deadline, see {@link #createOneOffTask(int, long)}, * * @param taskId the unique task ID for this task. Should be listed in {@link TaskIds}. * @param windowStartTimeMs the start of the window that the task can begin executing as a delta * in milliseconds from now. * @param windowEndTimeMs the end of the window that the task can begin executing as a delta in * milliseconds from now. Note that the task begins executing at this point even if the * prerequisite conditions are not met. * @return the builder which can be used to continue configuration and {@link Builder#build()}. * @see TaskIds * * @deprecated the {@see #createTask(int, Class, TimingInfo)} method should be used instead. * This method requires an additional step for the caller: the creation of the specific * {@link TimingInfo} object with the wanted properties. */ @Deprecated public static Builder createOneOffTask( int taskId, long windowStartTimeMs, long windowEndTimeMs) { TimingInfo oneOffInfo = OneOffInfo.create() .setWindowStartTimeMs(windowStartTimeMs) .setWindowEndTimeMs(windowEndTimeMs) .build(); return new Builder(taskId).setTimingInfo(oneOffInfo); } /** * Schedule a periodic task that will recur at the specified interval, without the need to * be rescheduled. The task will continue to recur until * {@link BackgroundTaskScheduler#cancel(Context, int)} is invoked with the task ID from this * {@link TaskInfo}. * The flex time specifies how close to the end of the interval you are willing to execute. * Instead of executing at the exact interval, the task will execute at the interval or up to * flex milliseconds before. * * @param taskId the unique task ID for this task. Should be listed in {@link TaskIds}. * @param intervalMs the interval between occurrences of this task in milliseconds. * @param flexMs the flex time for this task. The task can execute at any time in a window of * flex * length at the end of the period. It is reported in milliseconds. * @return the builder which can be used to continue configuration and {@link Builder#build()}. * @see TaskIds * * @deprecated the {@see #createTask(int, TimingInfo)} method should be used instead. * This method requires an additional step for the caller: the creation of the specific * {@link TimingInfo} object with the wanted properties. */ @Deprecated public static Builder createPeriodicTask(int taskId, long intervalMs, long flexMs) { TimingInfo periodicInfo = PeriodicInfo.create().setIntervalMs(intervalMs).setFlexMs(flexMs).build(); return new Builder(taskId).setTimingInfo(periodicInfo); } /** * A helper builder to provide a way to build {@link TaskInfo}. To create a {@link Builder} * use the createTask method on {@link TaskInfo}. * * @see @createTask(int, Class, TimingInfo) */ public static final class Builder { private final int mTaskId; private Bundle mExtras; @NetworkType private int mRequiredNetworkType; private boolean mRequiresCharging; private boolean mIsPersisted; private boolean mUpdateCurrent; private TimingInfo mTimingInfo; Builder(int taskId) { mTaskId = taskId; } Builder setTimingInfo(TimingInfo timingInfo) { mTimingInfo = timingInfo; return this; } /** * Set the optional extra values necessary for this task. Must only ever contain simple * values supported by {@link android.os.BaseBundle}. All other values are thrown away. * If the extras for this builder are not set, or set to null, the resulting * {@link TaskInfo} will have an empty bundle (i.e. not null). * * @param bundle the bundle of extra values necessary for this task. * @return this {@link Builder}. */ public Builder setExtras(Bundle bundle) { mExtras = bundle; return this; } /** * Set the type of network the task requires to run. * * @param networkType the {@link NetworkType} required for this task. * @return this {@link Builder}. */ public Builder setRequiredNetworkType(@NetworkType int networkType) { mRequiredNetworkType = networkType; return this; } /** * Set whether the task requires charging to run. * * @param requiresCharging true if this task requires charging. * @return this {@link Builder}. */ public Builder setRequiresCharging(boolean requiresCharging) { mRequiresCharging = requiresCharging; return this; } /** * Set whether or not to persist this task across device reboots. * * @param isPersisted true if this task should be persisted across reboots. * @return this {@link Builder}. */ public Builder setIsPersisted(boolean isPersisted) { mIsPersisted = isPersisted; return this; } /** * Set whether this task should override any preexisting tasks with the same task id. * * @param updateCurrent true if this task should overwrite a currently existing task with * the same ID, if it exists. * @return this {@link Builder}. */ public Builder setUpdateCurrent(boolean updateCurrent) { mUpdateCurrent = updateCurrent; return this; } /** * Build the {@link TaskInfo object} specified by this builder. * * @return the {@link TaskInfo} object. */ public TaskInfo build() { return new TaskInfo(this); } } }
bsd-3-clause