repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
sscdotopen/giraph-compensations | src/main/java/org/apache/giraph/comm/RPCCommunications.java | 6478 | /*
* 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.giraph.comm;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
/*if_not[HADOOP]
else[HADOOP]*/
import java.security.PrivilegedExceptionAction;
import org.apache.hadoop.mapreduce.security.TokenCache;
import org.apache.hadoop.mapreduce.security.token.JobTokenIdentifier;
import org.apache.hadoop.mapreduce.security.token.JobTokenSecretManager;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.ServiceAuthorizationManager;
import org.apache.hadoop.security.token.Token;
/*end[HADOOP]*/
import org.apache.log4j.Logger;
import org.apache.giraph.bsp.CentralizedServiceWorker;
import org.apache.giraph.graph.GraphState;
import org.apache.giraph.hadoop.BspPolicyProvider;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RPC.Server;
import org.apache.hadoop.mapreduce.Mapper;
@SuppressWarnings("rawtypes")
public class RPCCommunications<
I extends WritableComparable,
V extends Writable,
E extends Writable,
M extends Writable>
/*if_not[HADOOP]
extends BasicRPCCommunications<I, V, E, M, Object> {
else[HADOOP]*/
extends BasicRPCCommunications<I, V, E, M, Token<JobTokenIdentifier>> {
/*end[HADOOP]*/
/** Class logger */
public static final Logger LOG = Logger.getLogger(RPCCommunications.class);
public RPCCommunications(Mapper<?, ?, ?, ?>.Context context,
CentralizedServiceWorker<I, V, E, M> service,
GraphState<I, V, E, M> graphState)
throws IOException, UnknownHostException, InterruptedException {
super(context, service);
}
/*if_not[HADOOP]
protected Object createJobToken() throws IOException {
return null;
}
else[HADOOP]*/
protected Token<JobTokenIdentifier> createJobToken() throws IOException {
String localJobTokenFile = System.getenv().get(
UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION);
if (localJobTokenFile != null) {
Credentials credentials =
TokenCache.loadTokens(localJobTokenFile, conf);
return TokenCache.getJobToken(credentials);
}
return null;
}
/*end[HADOOP]*/
protected Server getRPCServer(
InetSocketAddress myAddress, int numHandlers, String jobId,
/*if_not[HADOOP]
Object jt) throws IOException {
return RPC.getServer(this, myAddress.getHostName(), myAddress.getPort(),
numHandlers, false, conf);
}
else[HADOOP]*/
Token<JobTokenIdentifier> jt) throws IOException {
@SuppressWarnings("deprecation")
String hadoopSecurityAuthorization =
ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG;
if (conf.getBoolean(
hadoopSecurityAuthorization,
false)) {
ServiceAuthorizationManager.refresh(conf, new BspPolicyProvider());
}
JobTokenSecretManager jobTokenSecretManager =
new JobTokenSecretManager();
if (jt != null) { //could be null in the case of some unit tests
jobTokenSecretManager.addTokenForJob(jobId, jt);
if (LOG.isInfoEnabled()) {
LOG.info("getRPCServer: Added jobToken " + jt);
}
}
return RPC.getServer(this, myAddress.getHostName(), myAddress.getPort(),
numHandlers, false, conf, jobTokenSecretManager);
}
/*end[HADOOP]*/
protected CommunicationsInterface<I, V, E, M> getRPCProxy(
final InetSocketAddress addr,
String jobId,
/*if_not[HADOOP]
Object jt)
else[HADOOP]*/
Token<JobTokenIdentifier> jt)
/*end[HADOOP]*/
throws IOException, InterruptedException {
final Configuration config = new Configuration(conf);
/*if_not[HADOOP]
@SuppressWarnings("unchecked")
CommunicationsInterface<I, V, E, M> proxy =
(CommunicationsInterface<I, V, E, M>)RPC.getProxy(
CommunicationsInterface.class, versionID, addr, config);
return proxy;
else[HADOOP]*/
if (jt == null) {
@SuppressWarnings("unchecked")
CommunicationsInterface<I, V, E, M> proxy =
(CommunicationsInterface<I, V, E, M>)RPC.getProxy(
CommunicationsInterface.class, versionID, addr, config);
return proxy;
}
jt.setService(new Text(addr.getAddress().getHostAddress() + ":"
+ addr.getPort()));
UserGroupInformation current = UserGroupInformation.getCurrentUser();
current.addToken(jt);
UserGroupInformation owner =
UserGroupInformation.createRemoteUser(jobId);
owner.addToken(jt);
@SuppressWarnings("unchecked")
CommunicationsInterface<I, V, E, M> proxy =
owner.doAs(new PrivilegedExceptionAction<
CommunicationsInterface<I, V, E, M>>() {
@Override
public CommunicationsInterface<I, V, E, M> run() throws Exception {
// All methods in CommunicationsInterface will be used for RPC
return (CommunicationsInterface<I, V, E, M> )RPC.getProxy(
CommunicationsInterface.class, versionID, addr, config);
}
});
return proxy;
/*end[HADOOP]*/
}
}
| apache-2.0 |
hmmlopez/citrus | modules/citrus-jms/src/main/java/com/consol/citrus/jms/endpoint/JmsEndpointComponent.java | 2460 | /*
* Copyright 2006-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 com.consol.citrus.jms.endpoint;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.endpoint.*;
import javax.jms.ConnectionFactory;
import java.util.Map;
/**
* Jms endpoint component is able to create jms endpoint from endpoint uri with parameters. Depending on uri creates a
* synchronous or asynchronous endpoint on a queue or topic destination.
*
* Further endpoint parameters such as connectionFactory get passed to the endpoint configuration.
*
* @author Christoph Deppisch
* @since 1.4.1
*/
public class JmsEndpointComponent extends AbstractEndpointComponent {
@Override
protected Endpoint createEndpoint(String resourcePath, Map<String, String> parameters, TestContext context) {
JmsEndpoint endpoint;
if (resourcePath.startsWith("sync:")) {
endpoint = new JmsSyncEndpoint();
} else {
endpoint = new JmsEndpoint();
}
if (resourcePath.contains("topic:")) {
endpoint.getEndpointConfiguration().setPubSubDomain(true);
}
// set destination name
if (resourcePath.indexOf(':') > 0) {
endpoint.getEndpointConfiguration().setDestinationName(resourcePath.substring(resourcePath.lastIndexOf(':') + 1));
} else {
endpoint.getEndpointConfiguration().setDestinationName(resourcePath);
}
// set default jms connection factory
if (context.getApplicationContext() != null && context.getApplicationContext().containsBean("connectionFactory")) {
endpoint.getEndpointConfiguration().setConnectionFactory(context.getApplicationContext().getBean("connectionFactory", ConnectionFactory.class));
}
enrichEndpointConfiguration(endpoint.getEndpointConfiguration(), parameters, context);
return endpoint;
}
}
| apache-2.0 |
Atos-FiwareOps/sla-framework | sla-core/sla-repository/src/test/java/eu/atos/sla/service/jpa/ViolationDAOJpaTest.java | 2415 | package eu.atos.sla.service.jpa;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Date;
import java.util.UUID;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import eu.atos.sla.dao.IAgreementDAO;
import eu.atos.sla.dao.IViolationDAO;
import eu.atos.sla.dao.IViolationDAO.SearchParameters;
import eu.atos.sla.datamodel.IViolation;
import eu.atos.sla.datamodel.bean.Violation;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/sla-repository-db-JPA-test-context.xml")
public class ViolationDAOJpaTest extends
AbstractTransactionalJUnit4SpringContextTests {
@Autowired
IViolationDAO violationDAO;
@Autowired
IAgreementDAO agreementDAO;
@Test
public void notNull() {
if (violationDAO == null)
fail();
}
@Test
public void getById() {
String violationUuid = UUID.randomUUID().toString();
Date dateTime = new Date(2323L);
IViolation violation = new Violation();
IViolation violationSaved = new Violation();
violation.setUuid(violationUuid);
violation.setContractUuid(UUID.randomUUID().toString());
violation.setServiceName("Service name");
violation.setServiceScope("Service scope");
violation.setKpiName("response time");
violation.setDatetime(dateTime);
violation.setExpectedValue("3.0");
violation.setActualValue("5.0");
try {
violationSaved = violationDAO.save(violation);
} catch (Exception e) {
fail();
}
Long id = violationSaved.getId();
violationSaved = violationDAO.getById(id);
assertEquals("response time", violationSaved.getKpiName());
assertEquals("3.0", violationSaved.getExpectedValue());
IViolation nullBreach = violationDAO.getById(new Long(30000));
assertEquals(null, nullBreach);
}
@Test
public void testSearch() {
SearchParameters params = new IViolationDAO.SearchParameters();
params.setAgreementId(null);
params.setGuaranteeTermName(null);
params.setProviderUuid(null);
params.setBegin(null);
params.setEnd(null);
violationDAO.search(params);
}
}
| apache-2.0 |
vipinraj/Spark | core/src/main/java/org/jivesoftware/spark/component/RolloverButton.java | 2619 | /**
* Copyright (C) 2004-2011 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.spark.component;
import org.jivesoftware.Spark;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Button UI for handling of rollover buttons.
*
* @author Derek DeMoro
*/
public class RolloverButton extends JButton {
private static final long serialVersionUID = 6351541211385798436L;
/**
* Create a new RolloverButton.
*/
public RolloverButton() {
decorate();
}
public RolloverButton(String text) {
super(text);
decorate();
}
public RolloverButton(Action action) {
super(action);
decorate();
}
/**
* Create a new RolloverButton.
*
* @param icon the icon to use on the button.
*/
public RolloverButton(Icon icon) {
super(icon);
decorate();
}
/**
* Create a new RolloverButton.
*
* @param text the button text.
* @param icon the button icon.
*/
public RolloverButton(String text, Icon icon) {
super(text, icon);
decorate();
}
/**
* Decorates the button with the approriate UI configurations.
*/
protected void decorate() {
setBorderPainted(false);
setOpaque(true);
setContentAreaFilled(false);
setMargin(new Insets(1, 1, 1, 1));
addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
if (isEnabled()) {
setBorderPainted(true);
// Handle background border on mac.
if (!Spark.isMac()) {
setContentAreaFilled(true);
}
}
}
public void mouseExited(MouseEvent e) {
setBorderPainted(false);
setContentAreaFilled(false);
}
});
}
} | apache-2.0 |
haikuowuya/android_system_code | src/java/util/Vector.java | 45964 | /*
* Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.util;
/**
* The {@code Vector} class implements a growable array of
* objects. Like an array, it contains components that can be
* accessed using an integer index. However, the size of a
* {@code Vector} can grow or shrink as needed to accommodate
* adding and removing items after the {@code Vector} has been created.
*
* <p>Each vector tries to optimize storage management by maintaining a
* {@code capacity} and a {@code capacityIncrement}. The
* {@code capacity} is always at least as large as the vector
* size; it is usually larger because as components are added to the
* vector, the vector's storage increases in chunks the size of
* {@code capacityIncrement}. An application can increase the
* capacity of a vector before inserting a large number of
* components; this reduces the amount of incremental reallocation.
*
* <p><a name="fail-fast"/>
* The iterators returned by this class's {@link #iterator() iterator} and
* {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
* if the vector is structurally modified at any time after the iterator is
* created, in any way except through the iterator's own
* {@link ListIterator#remove() remove} or
* {@link ListIterator#add(Object) add} methods, the iterator will throw a
* {@link ConcurrentModificationException}. Thus, in the face of
* concurrent modification, the iterator fails quickly and cleanly, rather
* than risking arbitrary, non-deterministic behavior at an undetermined
* time in the future. The {@link Enumeration Enumerations} returned by
* the {@link #elements() elements} method are <em>not</em> fail-fast.
*
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification. Fail-fast iterators
* throw {@code ConcurrentModificationException} on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
*
* <p>As of the Java 2 platform v1.2, this class was retrofitted to
* implement the {@link List} interface, making it a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>. Unlike the new collection
* implementations, {@code Vector} is synchronized. If a thread-safe
* implementation is not needed, it is recommended to use {@link
* ArrayList} in place of {@code Vector}.
*
* @author Lee Boynton
* @author Jonathan Payne
* @see Collection
* @see LinkedList
* @since JDK1.0
*/
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* The array buffer into which the components of the vector are
* stored. The capacity of the vector is the length of this array buffer,
* and is at least large enough to contain all the vector's elements.
*
* <p>Any array elements following the last element in the Vector are null.
*
* @serial
*/
protected Object[] elementData;
/**
* The number of valid components in this {@code Vector} object.
* Components {@code elementData[0]} through
* {@code elementData[elementCount-1]} are the actual items.
*
* @serial
*/
protected int elementCount;
/**
* The amount by which the capacity of the vector is automatically
* incremented when its size becomes greater than its capacity. If
* the capacity increment is less than or equal to zero, the capacity
* of the vector is doubled each time it needs to grow.
*
* @serial
*/
protected int capacityIncrement;
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -2767605614048989439L;
/**
* Constructs an empty vector with the specified initial capacity and
* capacity increment.
*
* @param initialCapacity the initial capacity of the vector
* @param capacityIncrement the amount by which the capacity is
* increased when the vector overflows
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
/**
* Constructs an empty vector with the specified initial capacity and
* with its capacity increment equal to zero.
*
* @param initialCapacity the initial capacity of the vector
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
/**
* Constructs an empty vector so that its internal data array
* has size {@code 10} and its standard capacity increment is
* zero.
*/
public Vector() {
this(10);
}
/**
* Constructs a vector containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this
* vector
* @throws NullPointerException if the specified collection is null
* @since 1.2
*/
public Vector(Collection<? extends E> c) {
elementData = c.toArray();
elementCount = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}
/**
* Copies the components of this vector into the specified array.
* The item at index {@code k} in this vector is copied into
* component {@code k} of {@code anArray}.
*
* @param anArray the array into which the components get copied
* @throws NullPointerException if the given array is null
* @throws IndexOutOfBoundsException if the specified array is not
* large enough to hold all the components of this vector
* @throws ArrayStoreException if a component of this vector is not of
* a runtime type that can be stored in the specified array
* @see #toArray(Object[])
*/
public synchronized void copyInto(Object[] anArray) {
System.arraycopy(elementData, 0, anArray, 0, elementCount);
}
/**
* Trims the capacity of this vector to be the vector's current
* size. If the capacity of this vector is larger than its current
* size, then the capacity is changed to equal the size by replacing
* its internal data array, kept in the field {@code elementData},
* with a smaller one. An application can use this operation to
* minimize the storage of a vector.
*/
public synchronized void trimToSize() {
modCount++;
int oldCapacity = elementData.length;
if (elementCount < oldCapacity) {
elementData = Arrays.copyOf(elementData, elementCount);
}
}
/**
* Increases the capacity of this vector, if necessary, to ensure
* that it can hold at least the number of components specified by
* the minimum capacity argument.
*
* <p>If the current capacity of this vector is less than
* {@code minCapacity}, then its capacity is increased by replacing its
* internal data array, kept in the field {@code elementData}, with a
* larger one. The size of the new data array will be the old size plus
* {@code capacityIncrement}, unless the value of
* {@code capacityIncrement} is less than or equal to zero, in which case
* the new capacity will be twice the old capacity; but if this new size
* is still smaller than {@code minCapacity}, then the new capacity will
* be {@code minCapacity}.
*
* @param minCapacity the desired minimum capacity
*/
public synchronized void ensureCapacity(int minCapacity) {
if (minCapacity > 0) {
modCount++;
ensureCapacityHelper(minCapacity);
}
}
/**
* This implements the unsynchronized semantics of ensureCapacity.
* Synchronized methods in this class can internally call this
* method for ensuring capacity without incurring the cost of an
* extra synchronization.
*
* @see #ensureCapacity(int)
*/
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/**
* Sets the size of this vector. If the new size is greater than the
* current size, new {@code null} items are added to the end of
* the vector. If the new size is less than the current size, all
* components at index {@code newSize} and greater are discarded.
*
* @param newSize the new size of this vector
* @throws ArrayIndexOutOfBoundsException if the new size is negative
*/
public synchronized void setSize(int newSize) {
modCount++;
if (newSize > elementCount) {
ensureCapacityHelper(newSize);
} else {
for (int i = newSize ; i < elementCount ; i++) {
elementData[i] = null;
}
}
elementCount = newSize;
}
/**
* Returns the current capacity of this vector.
*
* @return the current capacity (the length of its internal
* data array, kept in the field {@code elementData}
* of this vector)
*/
public synchronized int capacity() {
return elementData.length;
}
/**
* Returns the number of components in this vector.
*
* @return the number of components in this vector
*/
public synchronized int size() {
return elementCount;
}
/**
* Tests if this vector has no components.
*
* @return {@code true} if and only if this vector has
* no components, that is, its size is zero;
* {@code false} otherwise.
*/
public synchronized boolean isEmpty() {
return elementCount == 0;
}
/**
* Returns an enumeration of the components of this vector. The
* returned {@code Enumeration} object will generate all items in
* this vector. The first item generated is the item at index {@code 0},
* then the item at index {@code 1}, and so on.
*
* @return an enumeration of the components of this vector
* @see Iterator
*/
public Enumeration<E> elements() {
return new Enumeration<E>() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
/**
* Returns {@code true} if this vector contains the specified element.
* More formally, returns {@code true} if and only if this vector
* contains at least one element {@code e} such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this vector is to be tested
* @return {@code true} if this vector contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o, 0) >= 0;
}
/**
* Returns the index of the first occurrence of the specified element
* in this vector, or -1 if this vector does not contain the element.
* More formally, returns the lowest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this vector, or -1 if this vector does not contain the element
*/
public int indexOf(Object o) {
return indexOf(o, 0);
}
/**
* Returns the index of the first occurrence of the specified element in
* this vector, searching forwards from {@code index}, or returns -1 if
* the element is not found.
* More formally, returns the lowest index {@code i} such that
* <tt>(i >= index && (o==null ? get(i)==null : o.equals(get(i))))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @param index index to start searching from
* @return the index of the first occurrence of the element in
* this vector at position {@code index} or later in the vector;
* {@code -1} if the element is not found.
* @throws IndexOutOfBoundsException if the specified index is negative
* @see Object#equals(Object)
*/
public synchronized int indexOf(Object o, int index) {
if (o == null) {
for (int i = index ; i < elementCount ; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = index ; i < elementCount ; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified element
* in this vector, or -1 if this vector does not contain the element.
* More formally, returns the highest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this vector, or -1 if this vector does not contain the element
*/
public synchronized int lastIndexOf(Object o) {
return lastIndexOf(o, elementCount-1);
}
/**
* Returns the index of the last occurrence of the specified element in
* this vector, searching backwards from {@code index}, or returns -1 if
* the element is not found.
* More formally, returns the highest index {@code i} such that
* <tt>(i <= index && (o==null ? get(i)==null : o.equals(get(i))))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @param index index to start searching backwards from
* @return the index of the last occurrence of the element at position
* less than or equal to {@code index} in this vector;
* -1 if the element is not found.
* @throws IndexOutOfBoundsException if the specified index is greater
* than or equal to the current size of this vector
*/
public synchronized int lastIndexOf(Object o, int index) {
if (index >= elementCount)
throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
if (o == null) {
for (int i = index; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = index; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
/**
* Returns the component at the specified index.
*
* <p>This method is identical in functionality to the {@link #get(int)}
* method (which is part of the {@link List} interface).
*
* @param index an index into this vector
* @return the component at the specified index
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
*/
public synchronized E elementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
}
return elementData(index);
}
/**
* Returns the first component (the item at index {@code 0}) of
* this vector.
*
* @return the first component of this vector
* @throws NoSuchElementException if this vector has no components
*/
public synchronized E firstElement() {
if (elementCount == 0) {
throw new NoSuchElementException();
}
return elementData(0);
}
/**
* Returns the last component of the vector.
*
* @return the last component of the vector, i.e., the component at index
* <code>size() - 1</code>.
* @throws NoSuchElementException if this vector is empty
*/
public synchronized E lastElement() {
if (elementCount == 0) {
throw new NoSuchElementException();
}
return elementData(elementCount - 1);
}
/**
* Sets the component at the specified {@code index} of this
* vector to be the specified object. The previous component at that
* position is discarded.
*
* <p>The index must be a value greater than or equal to {@code 0}
* and less than the current size of the vector.
*
* <p>This method is identical in functionality to the
* {@link #set(int, Object) set(int, E)}
* method (which is part of the {@link List} interface). Note that the
* {@code set} method reverses the order of the parameters, to more closely
* match array usage. Note also that the {@code set} method returns the
* old value that was stored at the specified position.
*
* @param obj what the component is to be set to
* @param index the specified index
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
*/
public synchronized void setElementAt(E obj, int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
elementData[index] = obj;
}
/**
* Deletes the component at the specified index. Each component in
* this vector with an index greater or equal to the specified
* {@code index} is shifted downward to have an index one
* smaller than the value it had previously. The size of this vector
* is decreased by {@code 1}.
*
* <p>The index must be a value greater than or equal to {@code 0}
* and less than the current size of the vector.
*
* <p>This method is identical in functionality to the {@link #remove(int)}
* method (which is part of the {@link List} interface). Note that the
* {@code remove} method returns the old value that was stored at the
* specified position.
*
* @param index the index of the object to remove
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
*/
public synchronized void removeElementAt(int index) {
modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
/**
* Inserts the specified object as a component in this vector at the
* specified {@code index}. Each component in this vector with
* an index greater or equal to the specified {@code index} is
* shifted upward to have an index one greater than the value it had
* previously.
*
* <p>The index must be a value greater than or equal to {@code 0}
* and less than or equal to the current size of the vector. (If the
* index is equal to the current size of the vector, the new element
* is appended to the Vector.)
*
* <p>This method is identical in functionality to the
* {@link #add(int, Object) add(int, E)}
* method (which is part of the {@link List} interface). Note that the
* {@code add} method reverses the order of the parameters, to more closely
* match array usage.
*
* @param obj the component to insert
* @param index where to insert the new component
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index > size()})
*/
public synchronized void insertElementAt(E obj, int index) {
modCount++;
if (index > elementCount) {
throw new ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
}
ensureCapacityHelper(elementCount + 1);
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index] = obj;
elementCount++;
}
/**
* Adds the specified component to the end of this vector,
* increasing its size by one. The capacity of this vector is
* increased if its size becomes greater than its capacity.
*
* <p>This method is identical in functionality to the
* {@link #add(Object) add(E)}
* method (which is part of the {@link List} interface).
*
* @param obj the component to be added
*/
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
/**
* Removes the first (lowest-indexed) occurrence of the argument
* from this vector. If the object is found in this vector, each
* component in the vector with an index greater or equal to the
* object's index is shifted downward to have an index one smaller
* than the value it had previously.
*
* <p>This method is identical in functionality to the
* {@link #remove(Object)} method (which is part of the
* {@link List} interface).
*
* @param obj the component to be removed
* @return {@code true} if the argument was a component of this
* vector; {@code false} otherwise.
*/
public synchronized boolean removeElement(Object obj) {
modCount++;
int i = indexOf(obj);
if (i >= 0) {
removeElementAt(i);
return true;
}
return false;
}
/**
* Removes all components from this vector and sets its size to zero.
*
* <p>This method is identical in functionality to the {@link #clear}
* method (which is part of the {@link List} interface).
*/
public synchronized void removeAllElements() {
modCount++;
// Let gc do its work
for (int i = 0; i < elementCount; i++)
elementData[i] = null;
elementCount = 0;
}
/**
* Returns a clone of this vector. The copy will contain a
* reference to a clone of the internal data array, not a reference
* to the original internal data array of this {@code Vector} object.
*
* @return a clone of this vector
*/
public synchronized Object clone() {
try {
@SuppressWarnings("unchecked")
Vector<E> v = (Vector<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, elementCount);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
/**
* Returns an array containing all of the elements in this Vector
* in the correct order.
*
* @since 1.2
*/
public synchronized Object[] toArray() {
return Arrays.copyOf(elementData, elementCount);
}
/**
* Returns an array containing all of the elements in this Vector in the
* correct order; the runtime type of the returned array is that of the
* specified array. If the Vector fits in the specified array, it is
* returned therein. Otherwise, a new array is allocated with the runtime
* type of the specified array and the size of this Vector.
*
* <p>If the Vector fits in the specified array with room to spare
* (i.e., the array has more elements than the Vector),
* the element in the array immediately following the end of the
* Vector is set to null. (This is useful in determining the length
* of the Vector <em>only</em> if the caller knows that the Vector
* does not contain any null elements.)
*
* @param a the array into which the elements of the Vector are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the Vector
* @throws ArrayStoreException if the runtime type of a is not a supertype
* of the runtime type of every element in this Vector
* @throws NullPointerException if the given array is null
* @since 1.2
*/
@SuppressWarnings("unchecked")
public synchronized <T> T[] toArray(T[] a) {
if (a.length < elementCount)
return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
System.arraycopy(elementData, 0, a, 0, elementCount);
if (a.length > elementCount)
a[elementCount] = null;
return a;
}
// Positional Access Operations
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* Returns the element at the specified position in this Vector.
*
* @param index index of the element to return
* @return object at the specified index
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
* @since 1.2
*/
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
/**
* Replaces the element at the specified position in this Vector with the
* specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
* @since 1.2
*/
public synchronized E set(int index, E element) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
/**
* Appends the specified element to the end of this Vector.
*
* @param e element to be appended to this Vector
* @return {@code true} (as specified by {@link Collection#add})
* @since 1.2
*/
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
/**
* Removes the first occurrence of the specified element in this Vector
* If the Vector does not contain the element, it is unchanged. More
* formally, removes the element with the lowest index i such that
* {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
* an element exists).
*
* @param o element to be removed from this Vector, if present
* @return true if the Vector contained the specified element
* @since 1.2
*/
public boolean remove(Object o) {
return removeElement(o);
}
/**
* Inserts the specified element at the specified position in this Vector.
* Shifts the element currently at that position (if any) and any
* subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index > size()})
* @since 1.2
*/
public void add(int index, E element) {
insertElementAt(element, index);
}
/**
* Removes the element at the specified position in this Vector.
* Shifts any subsequent elements to the left (subtracts one from their
* indices). Returns the element that was removed from the Vector.
*
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= size()})
* @param index the index of the element to be removed
* @return element that was removed
* @since 1.2
*/
public synchronized E remove(int index) {
modCount++;
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
E oldValue = elementData(index);
int numMoved = elementCount - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--elementCount] = null; // Let gc do its work
return oldValue;
}
/**
* Removes all of the elements from this Vector. The Vector will
* be empty after this call returns (unless it throws an exception).
*
* @since 1.2
*/
public void clear() {
removeAllElements();
}
// Bulk Operations
/**
* Returns true if this Vector contains all of the elements in the
* specified Collection.
*
* @param c a collection whose elements will be tested for containment
* in this Vector
* @return true if this Vector contains all of the elements in the
* specified collection
* @throws NullPointerException if the specified collection is null
*/
public synchronized boolean containsAll(Collection<?> c) {
return super.containsAll(c);
}
/**
* Appends all of the elements in the specified Collection to the end of
* this Vector, in the order that they are returned by the specified
* Collection's Iterator. The behavior of this operation is undefined if
* the specified Collection is modified while the operation is in progress.
* (This implies that the behavior of this call is undefined if the
* specified Collection is this Vector, and this Vector is nonempty.)
*
* @param c elements to be inserted into this Vector
* @return {@code true} if this Vector changed as a result of the call
* @throws NullPointerException if the specified collection is null
* @since 1.2
*/
public synchronized boolean addAll(Collection<? extends E> c) {
modCount++;
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityHelper(elementCount + numNew);
System.arraycopy(a, 0, elementData, elementCount, numNew);
elementCount += numNew;
return numNew != 0;
}
/**
* Removes from this Vector all of its elements that are contained in the
* specified Collection.
*
* @param c a collection of elements to be removed from the Vector
* @return true if this Vector changed as a result of the call
* @throws ClassCastException if the types of one or more elements
* in this vector are incompatible with the specified
* collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this vector contains one or more null
* elements and the specified collection does not support null
* elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @since 1.2
*/
public synchronized boolean removeAll(Collection<?> c) {
return super.removeAll(c);
}
/**
* Retains only the elements in this Vector that are contained in the
* specified Collection. In other words, removes from this Vector all
* of its elements that are not contained in the specified Collection.
*
* @param c a collection of elements to be retained in this Vector
* (all other elements are removed)
* @return true if this Vector changed as a result of the call
* @throws ClassCastException if the types of one or more elements
* in this vector are incompatible with the specified
* collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this vector contains one or more null
* elements and the specified collection does not support null
* elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @since 1.2
*/
public synchronized boolean retainAll(Collection<?> c) {
return super.retainAll(c);
}
/**
* Inserts all of the elements in the specified Collection into this
* Vector at the specified position. Shifts the element currently at
* that position (if any) and any subsequent elements to the right
* (increases their indices). The new elements will appear in the Vector
* in the order that they are returned by the specified Collection's
* iterator.
*
* @param index index at which to insert the first element from the
* specified collection
* @param c elements to be inserted into this Vector
* @return {@code true} if this Vector changed as a result of the call
* @throws ArrayIndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index > size()})
* @throws NullPointerException if the specified collection is null
* @since 1.2
*/
public synchronized boolean addAll(int index, Collection<? extends E> c) {
modCount++;
if (index < 0 || index > elementCount)
throw new ArrayIndexOutOfBoundsException(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityHelper(elementCount + numNew);
int numMoved = elementCount - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
elementCount += numNew;
return numNew != 0;
}
/**
* Compares the specified Object with this Vector for equality. Returns
* true if and only if the specified Object is also a List, both Lists
* have the same size, and all corresponding pairs of elements in the two
* Lists are <em>equal</em>. (Two elements {@code e1} and
* {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
* e1.equals(e2))}.) In other words, two Lists are defined to be
* equal if they contain the same elements in the same order.
*
* @param o the Object to be compared for equality with this Vector
* @return true if the specified Object is equal to this Vector
*/
public synchronized boolean equals(Object o) {
return super.equals(o);
}
/**
* Returns the hash code value for this Vector.
*/
public synchronized int hashCode() {
return super.hashCode();
}
/**
* Returns a string representation of this Vector, containing
* the String representation of each element.
*/
public synchronized String toString() {
return super.toString();
}
/**
* Returns a view of the portion of this List between fromIndex,
* inclusive, and toIndex, exclusive. (If fromIndex and toIndex are
* equal, the returned List is empty.) The returned List is backed by this
* List, so changes in the returned List are reflected in this List, and
* vice-versa. The returned List supports all of the optional List
* operations supported by this List.
*
* <p>This method eliminates the need for explicit range operations (of
* the sort that commonly exist for arrays). Any operation that expects
* a List can be used as a range operation by operating on a subList view
* instead of a whole List. For example, the following idiom
* removes a range of elements from a List:
* <pre>
* list.subList(from, to).clear();
* </pre>
* Similar idioms may be constructed for indexOf and lastIndexOf,
* and all of the algorithms in the Collections class can be applied to
* a subList.
*
* <p>The semantics of the List returned by this method become undefined if
* the backing list (i.e., this List) is <i>structurally modified</i> in
* any way other than via the returned List. (Structural modifications are
* those that change the size of the List, or otherwise perturb it in such
* a fashion that iterations in progress may yield incorrect results.)
*
* @param fromIndex low endpoint (inclusive) of the subList
* @param toIndex high endpoint (exclusive) of the subList
* @return a view of the specified range within this List
* @throws IndexOutOfBoundsException if an endpoint index value is out of range
* {@code (fromIndex < 0 || toIndex > size)}
* @throws IllegalArgumentException if the endpoint indices are out of order
* {@code (fromIndex > toIndex)}
*/
public synchronized List<E> subList(int fromIndex, int toIndex) {
return Collections.synchronizedList(super.subList(fromIndex, toIndex),
this);
}
/**
* Removes from this list all of the elements whose index is between
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
* Shifts any succeeding elements to the left (reduces their index).
* This call shortens the list by {@code (toIndex - fromIndex)} elements.
* (If {@code toIndex==fromIndex}, this operation has no effect.)
*/
protected synchronized void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = elementCount - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// Let gc do its work
int newElementCount = elementCount - (toIndex-fromIndex);
while (elementCount != newElementCount)
elementData[--elementCount] = null;
}
/**
* Save the state of the {@code Vector} instance to a stream (that
* is, serialize it).
* This method performs synchronization to ensure the consistency
* of the serialized data.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
final java.io.ObjectOutputStream.PutField fields = s.putFields();
final Object[] data;
synchronized (this) {
fields.put("capacityIncrement", capacityIncrement);
fields.put("elementCount", elementCount);
data = elementData.clone();
}
fields.put("elementData", data);
s.writeFields();
}
/**
* Returns a list iterator over the elements in this list (in proper
* sequence), starting at the specified position in the list.
* The specified index indicates the first element that would be
* returned by an initial call to {@link ListIterator#next next}.
* An initial call to {@link ListIterator#previous previous} would
* return the element with the specified index minus one.
*
* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public synchronized ListIterator<E> listIterator(int index) {
if (index < 0 || index > elementCount)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
/**
* Returns a list iterator over the elements in this list (in proper
* sequence).
*
* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @see #listIterator(int)
*/
public synchronized ListIterator<E> listIterator() {
return new ListItr(0);
}
/**
* Returns an iterator over the elements in this list in proper sequence.
*
* <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @return an iterator over the elements in this list in proper sequence
*/
public synchronized Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
// Racy but within spec, since modifications are checked
// within or after synchronization in next/previous
return cursor != elementCount;
}
public E next() {
synchronized (Vector.this) {
checkForComodification();
int i = cursor;
if (i >= elementCount)
throw new NoSuchElementException();
cursor = i + 1;
return elementData(lastRet = i);
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
synchronized (Vector.this) {
checkForComodification();
Vector.this.remove(lastRet);
expectedModCount = modCount;
}
cursor = lastRet;
lastRet = -1;
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
/**
* An optimized version of AbstractList.ListItr
*/
final class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public E previous() {
synchronized (Vector.this) {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
cursor = i;
return elementData(lastRet = i);
}
}
public void set(E e) {
if (lastRet == -1)
throw new IllegalStateException();
synchronized (Vector.this) {
checkForComodification();
Vector.this.set(lastRet, e);
}
}
public void add(E e) {
int i = cursor;
synchronized (Vector.this) {
checkForComodification();
Vector.this.add(i, e);
expectedModCount = modCount;
}
cursor = i + 1;
lastRet = -1;
}
}
}
| apache-2.0 |
geliangdashen/Material | app/src/main/java/com/rey/material/demo/MainActivity.java | 10201 | package com.rey.material.demo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.rey.material.app.ToolbarManager;
import com.rey.material.util.ThemeUtil;
import com.rey.material.widget.SnackBar;
import com.rey.material.widget.TabPageIndicator;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener, ToolbarManager.OnToolbarGroupChangedListener {
private DrawerLayout dl_navigator;
private FrameLayout fl_drawer;
private ListView lv_drawer;
private CustomViewPager vp;
private TabPageIndicator tpi;
private DrawerAdapter mDrawerAdapter;
private PagerAdapter mPagerAdapter;
private Toolbar mToolbar;
private ToolbarManager mToolbarManager;
private SnackBar mSnackBar;
private Tab[] mItems = new Tab[]{Tab.PROGRESS, Tab.BUTTONS, Tab.FAB, Tab.SWITCHES, Tab.SLIDERS, Tab.SPINNERS, Tab.TEXTFIELDS, Tab.SNACKBARS, Tab.DIALOGS};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dl_navigator = (DrawerLayout)findViewById(R.id.main_dl);
fl_drawer = (FrameLayout)findViewById(R.id.main_fl_drawer);
lv_drawer = (ListView)findViewById(R.id.main_lv_drawer);
mToolbar = (Toolbar)findViewById(R.id.main_toolbar);
vp = (CustomViewPager)findViewById(R.id.main_vp);
tpi = (TabPageIndicator)findViewById(R.id.main_tpi);
mSnackBar = (SnackBar)findViewById(R.id.main_sn);
mToolbarManager = new ToolbarManager(this, mToolbar, 0, R.style.ToolbarRippleStyle, R.anim.abc_fade_in, R.anim.abc_fade_out);
mToolbarManager.setNavigationManager(new ToolbarManager.BaseNavigationManager(R.style.NavigationDrawerDrawable, this, mToolbar, dl_navigator) {
@Override
public void onNavigationClick() {
if(mToolbarManager.getCurrentGroup() != 0)
mToolbarManager.setCurrentGroup(0);
else
dl_navigator.openDrawer(Gravity.START);
}
@Override
public boolean isBackState() {
return super.isBackState() || mToolbarManager.getCurrentGroup() != 0;
}
@Override
protected boolean shouldSyncDrawerSlidingProgress() {
return super.shouldSyncDrawerSlidingProgress() && mToolbarManager.getCurrentGroup() == 0;
}
});
mToolbarManager.registerOnToolbarGroupChangedListener(this);
mDrawerAdapter = new DrawerAdapter();
lv_drawer.setAdapter(mDrawerAdapter);
lv_drawer.setOnItemClickListener(this);
mPagerAdapter = new PagerAdapter(getSupportFragmentManager(), mItems);
vp.setAdapter(mPagerAdapter);
tpi.setViewPager(vp);
tpi.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
mDrawerAdapter.setSelected(mItems[position]);
mSnackBar.dismiss();
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
@Override
public void onPageScrollStateChanged(int state) {}
});
vp.setCurrentItem(0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mToolbarManager.createMenu(R.menu.menu_main);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
mToolbarManager.onPrepareMenu();
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.tb_contextual:
mToolbarManager.setCurrentGroup(R.id.tb_group_contextual);
break;
case R.id.tb_done:
case R.id.tb_done_all:
mToolbarManager.setCurrentGroup(0);
break;
}
return true;
}
@Override
public void onToolbarGroupChanged(int oldGroupId, int groupId) {
mToolbarManager.notifyNavigationStateChanged();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
vp.setCurrentItem(position);
dl_navigator.closeDrawer(fl_drawer);
}
public SnackBar getSnackBar(){
return mSnackBar;
}
public enum Tab {
PROGRESS ("Progresses"),
BUTTONS ("Buttons"),
FAB ("FABs"),
SWITCHES ("Switches"),
SLIDERS ("Sliders"),
SPINNERS ("Spinners"),
TEXTFIELDS ("TextFields"),
SNACKBARS ("SnackBars"),
DIALOGS ("Dialogs");
private final String name;
private Tab(String s) {
name = s;
}
public boolean equalsName(String otherName){
return (otherName != null) && name.equals(otherName);
}
public String toString(){
return name;
}
}
class DrawerAdapter extends BaseAdapter{
private Tab mSelectedTab;
public void setSelected(Tab tab){
if(tab != mSelectedTab){
mSelectedTab = tab;
notifyDataSetInvalidated();
}
}
public Tab getSelectedTab(){
return mSelectedTab;
}
@Override
public int getCount() {
return mItems.length;
}
@Override
public Object getItem(int position) {
return mItems[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null)
v = LayoutInflater.from(MainActivity.this).inflate(R.layout.row_drawer, null);
Tab tab = (Tab)getItem(position);
((TextView)v).setText(tab.toString());
if(tab == mSelectedTab)
v.setBackgroundColor(ThemeUtil.colorPrimary(MainActivity.this, 0));
else
v.setBackgroundResource(0);
return v;
}
}
private static class PagerAdapter extends FragmentStatePagerAdapter {
Fragment[] mFragments;
Tab[] mTabs;
private static final Field sActiveField;
static {
Field f = null;
try {
Class<?> c = Class.forName("android.support.v4.app.FragmentManagerImpl");
f = c.getDeclaredField("mActive");
f.setAccessible(true);
} catch (Exception e) {}
sActiveField = f;
}
public PagerAdapter(FragmentManager fm, Tab[] tabs) {
super(fm);
mTabs = tabs;
mFragments = new Fragment[mTabs.length];
//dirty way to get reference of cached fragment
try{
ArrayList<Fragment> mActive = (ArrayList<Fragment>)sActiveField.get(fm);
if(mActive != null){
for(Fragment fragment : mActive){
if(fragment instanceof ProgressFragment)
setFragment(Tab.PROGRESS, fragment);
else if(fragment instanceof ButtonFragment)
setFragment(Tab.BUTTONS, fragment);
else if(fragment instanceof FabFragment)
setFragment(Tab.FAB, fragment);
else if(fragment instanceof SwitchesFragment)
setFragment(Tab.SWITCHES, fragment);
else if(fragment instanceof SliderFragment)
setFragment(Tab.SLIDERS, fragment);
else if(fragment instanceof SpinnersFragment)
setFragment(Tab.SPINNERS, fragment);
else if(fragment instanceof TextfieldFragment)
setFragment(Tab.TEXTFIELDS, fragment);
else if(fragment instanceof SnackbarFragment)
setFragment(Tab.SNACKBARS, fragment);
else if(fragment instanceof DialogsFragment)
setFragment(Tab.DIALOGS, fragment);
}
}
}
catch(Exception e){}
}
private void setFragment(Tab tab, Fragment f){
for(int i = 0; i < mTabs.length; i++)
if(mTabs[i] == tab){
mFragments[i] = f;
break;
}
}
@Override
public Fragment getItem(int position) {
if(mFragments[position] == null){
switch (mTabs[position]) {
case PROGRESS:
mFragments[position] = ProgressFragment.newInstance();
break;
case BUTTONS:
mFragments[position] = ButtonFragment.newInstance();
break;
case FAB:
mFragments[position] = FabFragment.newInstance();
break;
case SWITCHES:
mFragments[position] = SwitchesFragment.newInstance();
break;
case SLIDERS:
mFragments[position] = SliderFragment.newInstance();
break;
case SPINNERS:
mFragments[position] = SpinnersFragment.newInstance();
break;
case TEXTFIELDS:
mFragments[position] = TextfieldFragment.newInstance();
break;
case SNACKBARS:
mFragments[position] = SnackbarFragment.newInstance();
break;
case DIALOGS:
mFragments[position] = DialogsFragment.newInstance();
break;
}
}
return mFragments[position];
}
@Override
public CharSequence getPageTitle(int position) {
return mTabs[position].toString().toUpperCase();
}
@Override
public int getCount() {
return mFragments.length;
}
}
}
| apache-2.0 |
richardliaw/ray | java/test/src/main/java/io/ray/benchmark/MaxPressureTest.java | 1141 | package io.ray.benchmark;
import io.ray.api.ActorHandle;
import io.ray.api.ObjectRef;
import io.ray.api.Ray;
import org.testng.annotations.Test;
public class MaxPressureTest extends RayBenchmarkTest {
public static final int clientNum = 2;
public static final int totalNum = 10;
private static final long serialVersionUID = -1684518885171395952L;
public static RemoteResult<Integer> currentTime() {
RemoteResult<Integer> remoteResult = new RemoteResult<>();
remoteResult.setFinishTime(System.nanoTime());
remoteResult.setResult(0);
return remoteResult;
}
@Test
public void test() {
PressureTestParameter pressureTestParameter = new PressureTestParameter();
pressureTestParameter.setClientNum(clientNum);
pressureTestParameter.setTotalNum(totalNum);
pressureTestParameter.setRayBenchmarkTest(this);
super.maxPressureTest(pressureTestParameter);
}
@Override
public ObjectRef<RemoteResult<Integer>> rayCall(ActorHandle rayActor) {
return Ray.task(MaxPressureTest::currentTime).remote();
}
@Override
public boolean checkResult(Object o) {
return (int) o == 0;
}
}
| apache-2.0 |
yukuku/androidbible | Alkitab/src/debug/java/yuku/stethoshim/StethoShim.java | 472 | package yuku.stethoshim;
import android.app.Application;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import okhttp3.OkHttpClient;
public class StethoShim {
public static void initializeWithDefaults(final Application application) {
Stetho.initializeWithDefaults(application);
}
public static void addNetworkInterceptor(final OkHttpClient.Builder builder) {
builder.addNetworkInterceptor(new StethoInterceptor());
}
}
| apache-2.0 |
4treesCH/strolch | li.strolch.xmlpers/src/main/java/li/strolch/xmlpers/api/IoMode.java | 1560 | /*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* 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 li.strolch.xmlpers.api;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public enum IoMode {
DOM {
@Override
public <T> void write(PersistenceContext<T> ctx, FileIo fileIo) {
fileIo.writeDom(ctx);
}
@Override
public <T> void read(PersistenceContext<T> ctx, FileIo fileIo) {
fileIo.readDom(ctx);
}
},
SAX {
@Override
public <T> void write(PersistenceContext<T> ctx, FileIo fileIo) {
fileIo.writeSax(ctx);
}
@Override
public <T> void read(PersistenceContext<T> ctx, FileIo fileIo) {
fileIo.readSax(ctx);
}
};
/**
* @param ctx
* @param fileIo
*/
public <T> void write(PersistenceContext<T> ctx, FileIo fileIo) {
throw new UnsupportedOperationException("Override me!"); //$NON-NLS-1$
}
/**
* @param ctx
* @param fileIo
*/
public <T> void read(PersistenceContext<T> ctx, FileIo fileIo) {
throw new UnsupportedOperationException("Override me!"); //$NON-NLS-1$
}
}
| apache-2.0 |
debop/debop4j | debop4j-data/src/main/java/kr/debop4j/data/model/IAssignedEntity.java | 1029 | /*
* Copyright 2011-2013 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 kr.debop4j.data.model;
import java.io.Serializable;
/**
* Assignable Id 를 가지는 엔티티의 인터페이스입니다.
*
* @author 배성혁 ( sunghyouk.bae@gmail.com )
* @since 13. 1. 27.
*/
public interface IAssignedEntity<TId extends Serializable> {
/**
* 엔티티의 Id 를 설정합니다.
*
* @param newId 새로운 Id 값
*/
void setId(TId newId);
}
| apache-2.0 |
renmeng8875/projects | Hibernate-source/源代码及重要说明/Hibernate相关资料/hibernate-3.2.0.ga/hibernate-3.2/src/org/hibernate/transaction/CacheSynchronization.java | 2682 | //$Id: CacheSynchronization.java 9239 2006-02-08 22:34:34Z steveebersole $
package org.hibernate.transaction;
import javax.transaction.Status;
import javax.transaction.Synchronization;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.TransactionException;
import org.hibernate.jdbc.JDBCContext;
import org.hibernate.util.JTAHelper;
/**
* @author Gavin King
*/
public final class CacheSynchronization implements Synchronization {
private static final Log log = LogFactory.getLog(CacheSynchronization.class);
private final TransactionFactory.Context ctx;
private JDBCContext jdbcContext;
private final Transaction transaction;
private final org.hibernate.Transaction hibernateTransaction;
public CacheSynchronization(
TransactionFactory.Context ctx,
JDBCContext jdbcContext,
Transaction transaction,
org.hibernate.Transaction tx
) {
this.ctx = ctx;
this.jdbcContext = jdbcContext;
this.transaction = transaction;
this.hibernateTransaction = tx;
}
public void beforeCompletion() {
log.trace("transaction before completion callback");
boolean flush;
try {
flush = !ctx.isFlushModeNever() &&
ctx.isFlushBeforeCompletionEnabled() &&
!JTAHelper.isRollback( transaction.getStatus() );
//actually, this last test is probably unnecessary, since
//beforeCompletion() doesn't get called during rollback
}
catch (SystemException se) {
log.error("could not determine transaction status", se);
setRollbackOnly();
throw new TransactionException("could not determine transaction status in beforeCompletion()", se);
}
try {
if (flush) {
log.trace("automatically flushing session");
ctx.managedFlush();
}
}
catch (RuntimeException re) {
setRollbackOnly();
throw re;
}
finally {
jdbcContext.beforeTransactionCompletion(hibernateTransaction);
}
}
private void setRollbackOnly() {
try {
transaction.setRollbackOnly();
}
catch (SystemException se) {
log.error("could not set transaction to rollback only", se);
}
}
public void afterCompletion(int status) {
if ( log.isTraceEnabled() ) {
log.trace("transaction after completion callback, status: " + status);
}
try {
jdbcContext.afterTransactionCompletion(status==Status.STATUS_COMMITTED, hibernateTransaction);
}
finally {
if ( ctx.shouldAutoClose() && !ctx.isClosed() ) {
log.trace("automatically closing session");
ctx.managedClose();
}
}
}
public String toString() {
return CacheSynchronization.class.getName();
}
}
| apache-2.0 |
ibmsoe/hbase | hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestCoprocessorTableEndpoint.java | 6782 | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.coprocessor;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Map;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.ByteStringer;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.coprocessor.Batch;
import org.apache.hadoop.hbase.coprocessor.protobuf.generated.ColumnAggregationProtos;
import org.apache.hadoop.hbase.ipc.BlockingRpcCallback;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import com.google.protobuf.ServiceException;
@Category(MediumTests.class)
public class TestCoprocessorTableEndpoint {
private static final byte[] TEST_FAMILY = Bytes.toBytes("TestFamily");
private static final byte[] TEST_QUALIFIER = Bytes.toBytes("TestQualifier");
private static final byte[] ROW = Bytes.toBytes("testRow");
private static final int ROWSIZE = 20;
private static final int rowSeperator1 = 5;
private static final int rowSeperator2 = 12;
private static final byte[][] ROWS = makeN(ROW, ROWSIZE);
private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
@BeforeClass
public static void setupBeforeClass() throws Exception {
TEST_UTIL.startMiniCluster(2);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
TEST_UTIL.shutdownMiniCluster();
}
@Test
public void testCoprocessorTableEndpoint() throws Throwable {
final TableName tableName = TableName.valueOf("testCoprocessorTableEndpoint");
HTableDescriptor desc = new HTableDescriptor(tableName);
desc.addFamily(new HColumnDescriptor(TEST_FAMILY));
desc.addCoprocessor(org.apache.hadoop.hbase.coprocessor.ColumnAggregationEndpoint.class.getName());
createTable(desc);
verifyTable(tableName);
}
@Test
public void testDynamicCoprocessorTableEndpoint() throws Throwable {
final TableName tableName = TableName.valueOf("testDynamicCoprocessorTableEndpoint");
HTableDescriptor desc = new HTableDescriptor(tableName);
desc.addFamily(new HColumnDescriptor(TEST_FAMILY));
createTable(desc);
desc.addCoprocessor(org.apache.hadoop.hbase.coprocessor.ColumnAggregationEndpoint.class.getName());
updateTable(desc);
verifyTable(tableName);
}
private static byte[][] makeN(byte[] base, int n) {
byte[][] ret = new byte[n][];
for (int i = 0; i < n; i++) {
ret[i] = Bytes.add(base, Bytes.toBytes(String.format("%02d", i)));
}
return ret;
}
private static Map<byte [], Long> sum(final Table table, final byte [] family,
final byte [] qualifier, final byte [] start, final byte [] end)
throws ServiceException, Throwable {
return table.coprocessorService(ColumnAggregationProtos.ColumnAggregationService.class,
start, end,
new Batch.Call<ColumnAggregationProtos.ColumnAggregationService, Long>() {
@Override
public Long call(ColumnAggregationProtos.ColumnAggregationService instance)
throws IOException {
BlockingRpcCallback<ColumnAggregationProtos.SumResponse> rpcCallback =
new BlockingRpcCallback<ColumnAggregationProtos.SumResponse>();
ColumnAggregationProtos.SumRequest.Builder builder =
ColumnAggregationProtos.SumRequest.newBuilder();
builder.setFamily(ByteStringer.wrap(family));
if (qualifier != null && qualifier.length > 0) {
builder.setQualifier(ByteStringer.wrap(qualifier));
}
instance.sum(null, builder.build(), rpcCallback);
return rpcCallback.get().getSum();
}
});
}
private static final void createTable(HTableDescriptor desc) throws Exception {
Admin admin = TEST_UTIL.getHBaseAdmin();
admin.createTable(desc, new byte[][]{ROWS[rowSeperator1], ROWS[rowSeperator2]});
TEST_UTIL.waitUntilAllRegionsAssigned(desc.getTableName());
Table table = TEST_UTIL.getConnection().getTable(desc.getTableName());
try {
for (int i = 0; i < ROWSIZE; i++) {
Put put = new Put(ROWS[i]);
put.addColumn(TEST_FAMILY, TEST_QUALIFIER, Bytes.toBytes(i));
table.put(put);
}
} finally {
table.close();
}
}
private static void updateTable(HTableDescriptor desc) throws Exception {
Admin admin = TEST_UTIL.getHBaseAdmin();
admin.disableTable(desc.getTableName());
admin.modifyTable(desc.getTableName(), desc);
admin.enableTable(desc.getTableName());
}
private static final void verifyTable(TableName tableName) throws Throwable {
Table table = TEST_UTIL.getConnection().getTable(tableName);
try {
Map<byte[], Long> results = sum(table, TEST_FAMILY, TEST_QUALIFIER, ROWS[0],
ROWS[ROWS.length-1]);
int sumResult = 0;
int expectedResult = 0;
for (Map.Entry<byte[], Long> e : results.entrySet()) {
sumResult += e.getValue();
}
for (int i = 0; i < ROWSIZE; i++) {
expectedResult += i;
}
assertEquals("Invalid result", expectedResult, sumResult);
// scan: for region 2 and region 3
results.clear();
results = sum(table, TEST_FAMILY, TEST_QUALIFIER, ROWS[rowSeperator1], ROWS[ROWS.length-1]);
sumResult = 0;
expectedResult = 0;
for (Map.Entry<byte[], Long> e : results.entrySet()) {
sumResult += e.getValue();
}
for (int i = rowSeperator1; i < ROWSIZE; i++) {
expectedResult += i;
}
assertEquals("Invalid result", expectedResult, sumResult);
} finally {
table.close();
}
}
}
| apache-2.0 |
mpoindexter/teavm | teavm-core/src/main/java/org/teavm/model/VariableReader.java | 844 | /*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teavm.model;
import java.util.Set;
/**
*
* @author Alexey Andreev
*/
public interface VariableReader {
int getIndex();
ProgramReader getProgram();
Set<String> readDebugNames();
int getRegister();
}
| apache-2.0 |
0359xiaodong/DroidUIBuilder | src_all/DriodUIBuilder/src/org/droiddraw/widget/AbsoluteLayout.java | 1572 | /*
* Copyright (C) 2015 Jack Jiang(cngeeker.com) The DroidUIBuilder Project.
* All rights reserved.
* Project URL:https://github.com/JackJiang2011/DroidUIBuilder
* Version 1.0
*
* Jack Jiang PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
* AbsoluteLayout.java at 2015-2-6 16:12:02, original version by Jack Jiang.
* You can contact author with jb2011@163.com.
*/
package org.droiddraw.widget;
import java.util.Vector;
import org.droiddraw.AndroidEditor;
import org.droiddraw.property.Property;
import org.droiddraw.property.StringProperty;
public class AbsoluteLayout extends AbstractLayout
{
public static final String TAG_NAME = "AbsoluteLayout";
public AbsoluteLayout()
{
super(TAG_NAME);
// 设置图标,方便ui设计时进行辨识
this.setIconInTools(
org.droiddraw.resource.IconFactory.getInstance().getAbsoluteLayout_small_Icon().getImage());
}
@Override
public void positionWidget(Widget w)
{
apply();
}
@Override
public void repositionAllWidgets()
{
apply();
}
public void addOutputProperties(Widget w, Vector<Property> properties)
{
String unit = AndroidEditor.instance().getScreenUnit();
addOrUpdateProperty(properties, new StringProperty("X Position",
"android:layout_x", w.getX() + unit, false));
addOrUpdateProperty(properties, new StringProperty("Y Position",
"android:layout_y", w.getY() + unit, false));
}
public void addEditableProperties(Widget w)
{
}
public void removeEditableProperties(Widget w)
{
}
@Override
public void apply()
{
super.apply();
}
}
| apache-2.0 |
apache/derby | java/org.apache.derby.tests/org/apache/derbyTesting/functionTests/harness/jdk13.java | 3449 | /*
Derby - Class org.apache.derbyTesting.functionTests.harness.jdk13
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.derbyTesting.functionTests.harness;
import java.util.Vector;
import java.util.StringTokenizer;
import org.apache.derby.shared.common.info.JVMInfo;
/**
<p>This class is for JDK1.3.
*/
public class jdk13 extends jvm {
public String getName(){return "jdk13";}
public jdk13(boolean noasyncgc, boolean verbosegc, boolean noclassgc,
long ss, long oss, long ms, long mx, String classpath, String prof,
boolean verify, boolean noverify, boolean nojit, Vector<String> D) {
super(noasyncgc,verbosegc,noclassgc,ss,oss,ms,mx,classpath,prof,
verify,noverify,nojit,D);
}
// more typical use:
public jdk13(String classpath, Vector<String> D) {
super(classpath,D);
}
// more typical use:
public jdk13(long ms, long mx, String classpath, Vector<String> D) {
super(ms,mx,classpath,D);
}
// actual use
public jdk13() { }
// return the command line to invoke this VM. The caller then adds
// the class and program arguments.
public Vector<String> getCommandLine()
{
StringBuffer sb = new StringBuffer();
Vector<String> v = super.getCommandLine();
appendOtherFlags(sb);
String s = sb.toString();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens())
{
v.addElement(st.nextToken());
}
return v;
}
public void appendOtherFlags(StringBuffer sb)
{
boolean isModuleAware = JVMInfo.isModuleAware();
if (noasyncgc) warn("jdk13 does not support noasyncgc");
if (verbosegc) sb.append(" -verbose:gc");
if (noclassgc) sb.append(" -Xnoclassgc");
if (ss>=0) warn("jdk13 does not support ss");
if (oss>=0) warn("jdk13 does not support oss");
if (ms>=0) {
sb.append(" -ms");
sb.append(ms);
}
if (mx>=0) {
sb.append(" -mx");
sb.append(mx);
}
if (classpath!=null)
{
if (isModuleAware) { sb.append(" -p "); }
else { sb.append(" -classpath "); }
sb.append(classpath);
}
if (prof!=null) warn("jdk13 does not support prof");
if (verify) warn("jdk13 does not support verify");
if (noverify) warn("jdk13 does not support noverify");
if (nojit) sb.append(" -Djava.compiler=NONE");
if (D != null)
for (int i=0; i<D.size();i++) {
sb.append(" -D");
sb.append((String)(D.elementAt(i)));
}
}
public String getDintro() { return "-D"; }
}
| apache-2.0 |
mdunker/usergrid | stack/mongo-emulator/src/test/java/org/apache/usergrid/mongo/AbstractMongoTest.java | 2124 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.usergrid.mongo;
import org.apache.usergrid.mongo.MongoServer;
import java.net.UnknownHostException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.persistence.cassandra.EntityManagerFactoryImpl;
import org.apache.usergrid.services.ServiceManagerFactory;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
public abstract class AbstractMongoTest {
private static final Logger LOG = LoggerFactory.getLogger( AbstractMongoTest.class );
static MongoServer server = null;
static boolean usersSetup = false;
protected static Properties properties;
protected static String access_token;
EntityManagerFactoryImpl emf;
ServiceManagerFactory smf;
public AbstractMongoTest() {
super();
smf = new ServiceManagerFactory( emf, properties, null, null, null );
}
/** Get a db instance for testing */
public static DB getDb() throws UnknownHostException, MongoException {
Mongo m = new Mongo( "localhost", 27017 );
m.setWriteConcern( WriteConcern.SAFE );
DB db = m.getDB( "test-organization/test-app" );
db.authenticate( "test", "test".toCharArray() );
return db;
}
}
| apache-2.0 |
GovernmentCommunicationsHeadquarters/Gaffer | core/operation/src/test/java/uk/gov/gchq/gaffer/generator/TestGeneratorImpl.java | 1606 | /*
* Copyright 2017-2020 Crown Copyright
*
* 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 uk.gov.gchq.gaffer.generator;
import uk.gov.gchq.gaffer.commonutil.TestGroups;
import uk.gov.gchq.gaffer.commonutil.TestPropertyNames;
import uk.gov.gchq.gaffer.data.element.Element;
import uk.gov.gchq.gaffer.data.element.Entity;
import uk.gov.gchq.gaffer.data.generator.OneToManyElementGenerator;
import java.util.Arrays;
public class TestGeneratorImpl implements OneToManyElementGenerator<String> {
@Override
public Iterable<Element> _apply(final String domainObject) {
return Arrays.asList(
new Entity.Builder()
.group(TestGroups.ENTITY)
.vertex(domainObject)
.property(TestPropertyNames.COUNT, 1L)
.build(),
new Entity.Builder()
.group(TestGroups.ENTITY_2)
.vertex(domainObject)
.property(TestPropertyNames.COUNT, 1L)
.build()
);
}
}
| apache-2.0 |
morimekta/android-util | io-util/src/test/java/net/morimekta/util/TupleTest.java | 3334 | package net.morimekta.util;
import org.junit.Test;
import java.util.UUID;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class TupleTest {
@Test
public void testConstructor() {
Tuple tmp = new Tuple("foo");
assertThat(tmp.array().length, is(1));
try {
new Tuple();
fail("no exception");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("Empty tuple"));
}
}
@Test
public void testTuple1() {
Tuple.Tuple1<String> tuple =
Tuple.tuple("foo");
assertThat(tuple.first(), is("foo"));
}
@Test
public void testTuple2() {
Tuple.Tuple2<String,Integer> tuple =
Tuple.tuple("foo", 5);
assertThat(tuple.first(), is("foo"));
assertThat(tuple.second(), is(5));
}
@Test
public void testTuple3() {
Tuple.Tuple3<String,Integer,String> tuple =
Tuple.tuple("foo", 5, "bar");
assertThat(tuple.first(), is("foo"));
assertThat(tuple.second(), is(5));
assertThat(tuple.third(), is("bar"));
}
@Test
public void testTuple4() {
Tuple.Tuple4<String,Integer,String,Long> tuple =
Tuple.tuple("foo", 5, "bar", 42L);
assertThat(tuple.first(), is("foo"));
assertThat(tuple.second(), is(5));
assertThat(tuple.third(), is("bar"));
assertThat(tuple.fourth(), is(42L));
}
@Test
public void testTuple5() {
Tuple.Tuple5<String,Integer,String,Long,Boolean> tuple =
Tuple.tuple("foo", 5, "bar", 42L, false);
assertThat(tuple.first(), is("foo"));
assertThat(tuple.second(), is(5));
assertThat(tuple.third(), is("bar"));
assertThat(tuple.fourth(), is(42L));
assertThat(tuple.fifth(), is(false));
Tuple.Tuple5<String,Integer,String,Long,Boolean> eq =
Tuple.tuple("foo", 5, "bar", 42L, false);
Tuple.Tuple5<String,Integer,String,Long,Boolean> ne =
Tuple.tuple("foo", 5, "bar", 41L, false);
assertThat(tuple, is(tuple));
assertThat(tuple, is(eq));
assertThat(tuple, is(not(ne)));
assertThat(tuple.equals(new Object()), is(false));
assertThat(tuple.equals(Tuple.tuple(44)), is(false));
}
@Test
public void testTuple6() {
Tuple.Tuple6<String,Integer,String,Long,Boolean,UUID> tuple =
Tuple.tuple("foo", 5, "bar", 42L, false, UUID.randomUUID());
assertThat(tuple.first(), is("foo"));
assertThat(tuple.second(), is(5));
assertThat(tuple.third(), is("bar"));
assertThat(tuple.fourth(), is(42L));
assertThat(tuple.fifth(), is(false));
assertThat(tuple.sixth(), is(instanceOf(UUID.class)));
assertThat(tuple.array().length, is(6));
assertThat(tuple.hashCode(), is(not(0)));
assertThat(tuple.iterator().next(), is("foo"));
assertThat(tuple.size(), is(6));
assertThat(tuple.toString(), is("Tuple(\"foo\", 5, \"bar\", 42, false, " + tuple.sixth().toString() + ")"));
}
}
| apache-2.0 |
Yasgur99/GreeleyScheduler | GreeleyScheduler/src/application/elements/Subject.java | 238 | package application.elements;
public enum Subject {
AP_EXAM, ART_AND_LIFESKILLS, ENGLISH, GUIDANCE,
LIFE_SCHOOL, MATHEMATICS, PREFORMING_ARTS, PHYSICAL_EDUCATION,
SCIENCE, SOCIAL_STUDIES, SPECIAL_EDUCATION, ATHLETICS, N_A;
}
| apache-2.0 |
ahmedaljazzar/edx-app-android | android-iconify/src/main/java/com/joanzapata/iconify/internal/IconFontDescriptorWrapper.java | 1829 | package com.joanzapata.iconify.internal;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.joanzapata.iconify.Icon;
import com.joanzapata.iconify.IconFontDescriptor;
import java.util.HashMap;
import java.util.Map;
public class IconFontDescriptorWrapper {
@NonNull
private final IconFontDescriptor iconFontDescriptor;
@NonNull
private final Map<String, Icon> iconsByKey;
@Nullable
private Typeface cachedTypeface;
public IconFontDescriptorWrapper(@NonNull IconFontDescriptor iconFontDescriptor) {
this.iconFontDescriptor = iconFontDescriptor;
iconsByKey = new HashMap<String, Icon>();
Icon[] characters = iconFontDescriptor.characters();
for (int i = 0, charactersLength = characters.length; i < charactersLength; i++) {
Icon icon = characters[i];
iconsByKey.put(icon.key(), icon);
}
}
@CheckResult
@Nullable
public Icon getIcon(@NonNull String key) {
return iconsByKey.get(key);
}
@CheckResult
@NonNull
public IconFontDescriptor getIconFontDescriptor() {
return iconFontDescriptor;
}
@CheckResult
@NonNull
public Typeface getTypeface(@NonNull Context context) {
if (cachedTypeface != null) return cachedTypeface;
synchronized (this) {
if (cachedTypeface != null) return cachedTypeface;
cachedTypeface = Typeface.createFromAsset(context.getAssets(), iconFontDescriptor.ttfFileName());
return cachedTypeface;
}
}
@CheckResult
public boolean hasIcon(@NonNull Icon icon) {
return iconsByKey.values().contains(icon);
}
}
| apache-2.0 |
0359xiaodong/YiBo | YiBo/src/com/shejiaomao/weibo/service/adapter/GroupStatusesListAdapter.java | 6553 | package com.shejiaomao.weibo.service.adapter;
import java.util.ArrayList;
import java.util.List;
import com.cattong.commons.util.ListUtil;
import com.cattong.weibo.entity.Group;
import com.cattong.entity.Status;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;
import com.shejiaomao.maobo.R;
import com.shejiaomao.weibo.common.theme.ThemeUtil;
import com.shejiaomao.weibo.db.LocalAccount;
import com.shejiaomao.weibo.db.LocalStatus;
import com.shejiaomao.weibo.service.task.GroupStatusesPageDownTask;
import com.shejiaomao.weibo.service.task.GroupStatusesPageUpTask;
public class GroupStatusesListAdapter extends CacheAdapter<Status> {
private Group group;
private List<Status> statusList;
public GroupStatusesListAdapter(Context context, LocalAccount account, Group group) {
super(context, account);
this.group = group;
statusList = new ArrayList<Status>();
GroupStatusesPageUpTask task = new GroupStatusesPageUpTask(this);
task.execute();
}
@Override
public int getCount() {
return statusList.size();
}
@Override
public Object getItem(int position) {
if (position < 0 || position >= statusList.size()) {
return null;
}
return statusList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Object obj = getItem(position);
Status status = (Status) obj;
if (status == null) {
return convertView;
}
if (status instanceof LocalStatus
&& ((LocalStatus)status).isDivider()) {
LocalStatus localStatus = (LocalStatus)status;
convertView = fillInDividerView(convertView, localStatus, position);
} else {
convertView = StatusUtil.initConvertView(context, convertView, account.getServiceProvider());
StatusUtil.fillConvertView(convertView, status);
}
return convertView;
}
private View fillInDividerView(View convertView, final LocalStatus status, final int position) {
if (status == null || !status.isDivider()) {
return null;
}
if (getItemViewType(position) == ITEM_VIEW_TYPE_REMOTE_DIVIDER) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_gap, null);
ThemeUtil.setListViewGap(convertView);
}
View llLoadingState = convertView.findViewById(R.id.llLoadingState);
if (status.isLoading()) {
llLoadingState.setVisibility(View.VISIBLE);
} else {
llLoadingState.setVisibility(View.GONE);
}
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setClickable(false);
v.findViewById(R.id.llLoadingState).setVisibility(View.VISIBLE);
Status max = (Status)getItem(position - 1);
Status since = (Status)getItem(position + 1);
GroupStatusesPageDownTask task = new GroupStatusesPageDownTask(
GroupStatusesListAdapter.this, status);
task.execute(max, since);
}
});
} else {
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_more, null);
ThemeUtil.setListViewMore(convertView);
}
if (status.isLoading()) {
convertView.findViewById(R.id.llLoadingState).setVisibility(View.VISIBLE);
convertView.findViewById(R.id.tvFooter).setVisibility(View.GONE);
} else {
convertView.findViewById(R.id.llLoadingState).setVisibility(View.GONE);
convertView.findViewById(R.id.tvFooter).setVisibility(View.VISIBLE);
}
if (paging.hasNext()) {
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setClickable(false);
v.findViewById(R.id.llLoadingState).setVisibility(View.VISIBLE);
v.findViewById(R.id.tvFooter).setVisibility(View.GONE);
Status max = (Status)getItem(position - 1);
Status since = (Status)getItem(position + 1);
GroupStatusesPageDownTask task = new GroupStatusesPageDownTask(
GroupStatusesListAdapter.this, status);
task.execute(max, since);
}
});
} else {
((TextView)convertView.findViewById(R.id.tvFooter)).setText(R.string.label_no_more);
}
}
return convertView;
}
@Override
public boolean addCacheToFirst(List<Status> list) {
if (ListUtil.isEmpty(list)) {
return false;
}
statusList.addAll(0, list);
this.notifyDataSetChanged();
return true;
}
@Override
public boolean addCacheToDivider(Status value, List<Status> list) {
if (value == null || ListUtil.isEmpty(list)) {
return false;
}
int pos = statusList.indexOf(value);
if (pos == -1) {
return false;
}
statusList.remove(pos);
statusList.addAll(pos, list);
this.notifyDataSetChanged();
return false;
}
@Override
public boolean addCacheToLast(List<Status> list) {
if (ListUtil.isEmpty(list)) {
return false;
}
statusList.addAll(list);
this.notifyDataSetChanged();
return true;
}
@Override
public Status getMax() {
if (statusList.size() == 0) {
return null;
}
return statusList.get(0);
}
@Override
public Status getMin() {
if (statusList.size() == 0) {
return null;
}
return statusList.get(getCount() - 1);
}
@Override
public void clear() {
statusList.clear();
}
@Override
public int getItemViewType(int position) {
Status status = (Status)getItem(position);
if (status == null) {
return ITEM_VIEW_TYPE_REMOTE_DIVIDER;
}
if (!(status instanceof LocalStatus)) {
return ITEM_VIEW_TYPE_DATA;
}
LocalStatus localStatus = (LocalStatus)status;
if (!localStatus.isDivider()) {
return ITEM_VIEW_TYPE_DATA;
}
if (localStatus.isLocalDivider()) {
return ITEM_VIEW_TYPE_LOCAL_DIVIDER;
}
return ITEM_VIEW_TYPE_REMOTE_DIVIDER;
}
@Override
public int getViewTypeCount() {
return 3;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
if (group == null || group.equals(this.group)) {
return;
}
this.group = group;
clear();
this.notifyDataSetChanged();
}
}
| apache-2.0 |
dain/presto | lib/trino-parquet/src/main/java/io/trino/parquet/predicate/TupleDomainParquetPredicate.java | 24584 | /*
* 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.trino.parquet.predicate;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.trino.parquet.DictionaryPage;
import io.trino.parquet.ParquetCorruptionException;
import io.trino.parquet.ParquetDataSourceId;
import io.trino.parquet.RichColumnDescriptor;
import io.trino.parquet.dictionary.Dictionary;
import io.trino.spi.predicate.Domain;
import io.trino.spi.predicate.Range;
import io.trino.spi.predicate.TupleDomain;
import io.trino.spi.predicate.ValueSet;
import io.trino.spi.type.DecimalType;
import io.trino.spi.type.TimestampType;
import io.trino.spi.type.Type;
import io.trino.spi.type.VarcharType;
import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.column.statistics.Statistics;
import org.apache.parquet.filter2.predicate.FilterApi;
import org.apache.parquet.filter2.predicate.FilterPredicate;
import org.apache.parquet.filter2.predicate.UserDefinedPredicate;
import org.apache.parquet.hadoop.metadata.ColumnPath;
import org.apache.parquet.internal.column.columnindex.ColumnIndex;
import org.apache.parquet.internal.filter2.columnindex.ColumnIndexStore;
import org.apache.parquet.io.api.Binary;
import org.apache.parquet.schema.PrimitiveType;
import org.joda.time.DateTimeZone;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import static com.google.common.base.Preconditions.checkArgument;
import static io.trino.parquet.ParquetTimestampUtils.decode;
import static io.trino.parquet.ParquetTypeUtils.getLongDecimalValue;
import static io.trino.parquet.ParquetTypeUtils.getShortDecimalValue;
import static io.trino.parquet.predicate.PredicateUtils.isStatisticsOverflow;
import static io.trino.plugin.base.type.TrinoTimestampEncoderFactory.createTimestampEncoder;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.BooleanType.BOOLEAN;
import static io.trino.spi.type.DateType.DATE;
import static io.trino.spi.type.DoubleType.DOUBLE;
import static io.trino.spi.type.IntegerType.INTEGER;
import static io.trino.spi.type.RealType.REAL;
import static io.trino.spi.type.SmallintType.SMALLINT;
import static io.trino.spi.type.TinyintType.TINYINT;
import static java.lang.Float.floatToRawIntBits;
import static java.lang.String.format;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
import static java.util.Objects.requireNonNull;
public class TupleDomainParquetPredicate
implements Predicate
{
private final TupleDomain<ColumnDescriptor> effectivePredicate;
private final List<RichColumnDescriptor> columns;
private final DateTimeZone timeZone;
public TupleDomainParquetPredicate(TupleDomain<ColumnDescriptor> effectivePredicate, List<RichColumnDescriptor> columns, DateTimeZone timeZone)
{
this.effectivePredicate = requireNonNull(effectivePredicate, "effectivePredicate is null");
this.columns = ImmutableList.copyOf(requireNonNull(columns, "columns is null"));
this.timeZone = requireNonNull(timeZone, "timeZone is null");
}
@Override
public boolean matches(long numberOfRows, Map<ColumnDescriptor, Statistics<?>> statistics, ParquetDataSourceId id)
throws ParquetCorruptionException
{
if (numberOfRows == 0) {
return false;
}
if (effectivePredicate.isNone()) {
return false;
}
Map<ColumnDescriptor, Domain> effectivePredicateDomains = effectivePredicate.getDomains()
.orElseThrow(() -> new IllegalStateException("Effective predicate other than none should have domains"));
for (RichColumnDescriptor column : columns) {
Domain effectivePredicateDomain = effectivePredicateDomains.get(column);
if (effectivePredicateDomain == null) {
continue;
}
Statistics<?> columnStatistics = statistics.get(column);
if (columnStatistics == null || columnStatistics.isEmpty()) {
// no stats for column
continue;
}
Domain domain = getDomain(effectivePredicateDomain.getType(), numberOfRows, columnStatistics, id, column.toString(), timeZone);
if (!effectivePredicateDomain.overlaps(domain)) {
return false;
}
}
return true;
}
@Override
public boolean matches(DictionaryDescriptor dictionary)
{
requireNonNull(dictionary, "dictionary is null");
if (effectivePredicate.isNone()) {
return false;
}
Map<ColumnDescriptor, Domain> effectivePredicateDomains = effectivePredicate.getDomains()
.orElseThrow(() -> new IllegalStateException("Effective predicate other than none should have domains"));
Domain effectivePredicateDomain = effectivePredicateDomains.get(dictionary.getColumnDescriptor());
return effectivePredicateDomain == null || effectivePredicateMatches(effectivePredicateDomain, dictionary);
}
@Override
public boolean matches(long numberOfRows, ColumnIndexStore columnIndexStore, ParquetDataSourceId id)
throws ParquetCorruptionException
{
requireNonNull(columnIndexStore, "columnIndexStore is null");
if (numberOfRows == 0) {
return false;
}
if (effectivePredicate.isNone()) {
return false;
}
Map<ColumnDescriptor, Domain> effectivePredicateDomains = effectivePredicate.getDomains()
.orElseThrow(() -> new IllegalStateException("Effective predicate other than none should have domains"));
for (RichColumnDescriptor column : columns) {
Domain effectivePredicateDomain = effectivePredicateDomains.get(column);
if (effectivePredicateDomain == null) {
continue;
}
ColumnIndex columnIndex = columnIndexStore.getColumnIndex(ColumnPath.get(column.getPath()));
if (columnIndex == null || isEmptyColumnIndex(columnIndex)) {
continue;
}
Domain domain = getDomain(effectivePredicateDomain.getType(), numberOfRows, columnIndex, id, column);
if (!effectivePredicateDomain.overlaps(domain)) {
return false;
}
}
return true;
}
@Override
public Optional<FilterPredicate> toParquetFilter(DateTimeZone timeZone)
{
return Optional.ofNullable(convertToParquetFilter(timeZone));
}
private boolean effectivePredicateMatches(Domain effectivePredicateDomain, DictionaryDescriptor dictionary)
{
return effectivePredicateDomain.overlaps(getDomain(effectivePredicateDomain.getType(), dictionary, timeZone));
}
@VisibleForTesting
public static Domain getDomain(
Type type,
long rowCount,
Statistics<?> statistics,
ParquetDataSourceId id,
String column,
DateTimeZone timeZone)
throws ParquetCorruptionException
{
if (statistics == null || statistics.isEmpty()) {
return Domain.all(type);
}
if (statistics.isNumNullsSet() && statistics.getNumNulls() == rowCount) {
return Domain.onlyNull(type);
}
boolean hasNullValue = !statistics.isNumNullsSet() || statistics.getNumNulls() != 0L;
if (!statistics.hasNonNullValue() || statistics.genericGetMin() == null || statistics.genericGetMax() == null) {
return Domain.create(ValueSet.all(type), hasNullValue);
}
try {
return getDomain(type, ImmutableList.of(statistics.genericGetMin()), ImmutableList.of(statistics.genericGetMax()), hasNullValue, timeZone);
}
catch (Exception e) {
throw corruptionException(column, id, statistics, e);
}
}
/**
* Get a domain for the ranges defined by each pair of elements from {@code minimums} and {@code maximums}.
* Both arrays must have the same length.
*/
private static Domain getDomain(
Type type,
List<Object> minimums,
List<Object> maximums,
boolean hasNullValue,
DateTimeZone timeZone)
{
checkArgument(minimums.size() == maximums.size(), "Expected minimums and maximums to have the same size");
if (type.equals(BOOLEAN)) {
boolean hasTrueValues = minimums.stream().anyMatch(value -> (boolean) value) || maximums.stream().anyMatch(value -> (boolean) value);
boolean hasFalseValues = minimums.stream().anyMatch(value -> !(boolean) value) || maximums.stream().anyMatch(value -> !(boolean) value);
if (hasTrueValues && hasFalseValues) {
return Domain.all(type);
}
if (hasTrueValues) {
return Domain.create(ValueSet.of(type, true), hasNullValue);
}
if (hasFalseValues) {
return Domain.create(ValueSet.of(type, false), hasNullValue);
}
// All nulls case is handled earlier
throw new VerifyException("Impossible boolean statistics");
}
if (type.equals(BIGINT) || type.equals(INTEGER) || type.equals(DATE) || type.equals(SMALLINT) || type.equals(TINYINT)) {
List<Range> ranges = new ArrayList<>();
for (int i = 0; i < minimums.size(); i++) {
long min = asLong(minimums.get(i));
long max = asLong(maximums.get(i));
if (isStatisticsOverflow(type, min, max)) {
return Domain.create(ValueSet.all(type), hasNullValue);
}
ranges.add(Range.range(type, min, true, max, true));
}
return Domain.create(ValueSet.ofRanges(ranges), hasNullValue);
}
if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
List<Range> ranges = new ArrayList<>();
if (decimalType.isShort()) {
for (int i = 0; i < minimums.size(); i++) {
Object min = minimums.get(i);
Object max = maximums.get(i);
long minValue = min instanceof Binary ? getShortDecimalValue(((Binary) min).getBytes()) : asLong(min);
long maxValue = min instanceof Binary ? getShortDecimalValue(((Binary) max).getBytes()) : asLong(max);
if (isStatisticsOverflow(type, minValue, maxValue)) {
return Domain.create(ValueSet.all(type), hasNullValue);
}
ranges.add(Range.range(type, minValue, true, maxValue, true));
}
}
else {
for (int i = 0; i < minimums.size(); i++) {
Slice min = getLongDecimalValue(((Binary) minimums.get(i)).getBytes());
Slice max = getLongDecimalValue(((Binary) maximums.get(i)).getBytes());
ranges.add(Range.range(type, min, true, max, true));
}
}
return Domain.create(ValueSet.ofRanges(ranges), hasNullValue);
}
if (type.equals(REAL)) {
List<Range> ranges = new ArrayList<>();
for (int i = 0; i < minimums.size(); i++) {
Float min = (Float) minimums.get(i);
Float max = (Float) maximums.get(i);
if (min.isNaN() || max.isNaN()) {
return Domain.create(ValueSet.all(type), hasNullValue);
}
ranges.add(Range.range(type, (long) floatToRawIntBits(min), true, (long) floatToRawIntBits(max), true));
}
return Domain.create(ValueSet.ofRanges(ranges), hasNullValue);
}
if (type.equals(DOUBLE)) {
List<Range> ranges = new ArrayList<>();
for (int i = 0; i < minimums.size(); i++) {
Double min = (Double) minimums.get(i);
Double max = (Double) maximums.get(i);
if (min.isNaN() || max.isNaN()) {
return Domain.create(ValueSet.all(type), hasNullValue);
}
ranges.add(Range.range(type, min, true, max, true));
}
return Domain.create(ValueSet.ofRanges(ranges), hasNullValue);
}
if (type instanceof VarcharType) {
List<Range> ranges = new ArrayList<>();
for (int i = 0; i < minimums.size(); i++) {
Slice min = Slices.wrappedBuffer(((Binary) minimums.get(i)).toByteBuffer());
Slice max = Slices.wrappedBuffer(((Binary) maximums.get(i)).toByteBuffer());
ranges.add(Range.range(type, min, true, max, true));
}
return Domain.create(ValueSet.ofRanges(ranges), hasNullValue);
}
if (type instanceof TimestampType) {
List<Object> values = new ArrayList<>();
for (int i = 0; i < minimums.size(); i++) {
Object min = minimums.get(i);
Object max = maximums.get(i);
// Parquet INT96 timestamp values were compared incorrectly for the purposes of producing statistics by older parquet writers, so
// PARQUET-1065 deprecated them. The result is that any writer that produced stats was producing unusable incorrect values, except
// the special case where min == max and an incorrect ordering would not be material to the result. PARQUET-1026 made binary stats
// available and valid in that special case
if (!(min instanceof Binary) || !(max instanceof Binary) || !min.equals(max)) {
return Domain.create(ValueSet.all(type), hasNullValue);
}
values.add(createTimestampEncoder((TimestampType) type, timeZone).getTimestamp(decode((Binary) min)));
}
return Domain.multipleValues(type, values, hasNullValue);
}
return Domain.create(ValueSet.all(type), hasNullValue);
}
@VisibleForTesting
public Domain getDomain(Type type, long rowCount, ColumnIndex columnIndex, ParquetDataSourceId id, RichColumnDescriptor descriptor)
throws ParquetCorruptionException
{
if (columnIndex == null) {
return Domain.all(type);
}
String columnName = descriptor.getPrimitiveType().getName();
if (isCorruptedColumnIndex(columnIndex)) {
throw corruptionException(columnName, id, columnIndex, null);
}
if (isEmptyColumnIndex(columnIndex)) {
return Domain.all(type);
}
long totalNullCount = columnIndex.getNullCounts().stream()
.mapToLong(value -> value)
.sum();
boolean hasNullValue = totalNullCount > 0;
if (hasNullValue && totalNullCount == rowCount) {
return Domain.onlyNull(type);
}
try {
int pageCount = columnIndex.getMinValues().size();
ColumnIndexValueConverter converter = new ColumnIndexValueConverter();
Function<ByteBuffer, Object> converterFunction = converter.getConverter(descriptor.getPrimitiveType());
List<Object> min = new ArrayList<>();
List<Object> max = new ArrayList<>();
for (int i = 0; i < pageCount; i++) {
min.add(converterFunction.apply(columnIndex.getMinValues().get(i)));
max.add(converterFunction.apply(columnIndex.getMaxValues().get(i)));
}
return getDomain(type, min, max, hasNullValue, timeZone);
}
catch (Exception e) {
throw corruptionException(columnName, id, columnIndex, e);
}
}
@VisibleForTesting
public static Domain getDomain(Type type, DictionaryDescriptor dictionaryDescriptor)
{
return getDomain(type, dictionaryDescriptor, DateTimeZone.getDefault());
}
private static Domain getDomain(Type type, DictionaryDescriptor dictionaryDescriptor, DateTimeZone timeZone)
{
if (dictionaryDescriptor == null) {
return Domain.all(type);
}
ColumnDescriptor columnDescriptor = dictionaryDescriptor.getColumnDescriptor();
Optional<DictionaryPage> dictionaryPage = dictionaryDescriptor.getDictionaryPage();
if (dictionaryPage.isEmpty()) {
return Domain.all(type);
}
Dictionary dictionary;
try {
dictionary = dictionaryPage.get().getEncoding().initDictionary(columnDescriptor, dictionaryPage.get());
}
catch (Exception e) {
// In case of exception, just continue reading the data, not using dictionary page at all
// OK to ignore exception when reading dictionaries
return Domain.all(type);
}
int dictionarySize = dictionaryPage.get().getDictionarySize();
DictionaryValueConverter converter = new DictionaryValueConverter(dictionary);
Function<Integer, Object> convertFunction = converter.getConverter(columnDescriptor.getPrimitiveType());
List<Object> values = new ArrayList<>();
for (int i = 0; i < dictionarySize; i++) {
values.add(convertFunction.apply(i));
}
// TODO: when min == max (i.e., singleton ranges, the construction of Domains can be done more efficiently
return getDomain(type, values, values, true, timeZone);
}
private static ParquetCorruptionException corruptionException(String column, ParquetDataSourceId id, Statistics<?> statistics, Exception cause)
{
return new ParquetCorruptionException(cause, format("Corrupted statistics for column \"%s\" in Parquet file \"%s\": [%s]", column, id, statistics));
}
private static ParquetCorruptionException corruptionException(String column, ParquetDataSourceId id, ColumnIndex columnIndex, Exception cause)
{
return new ParquetCorruptionException(cause, format("Corrupted statistics for column \"%s\" in Parquet file \"%s\". Corrupted column index: [%s]", column, id, columnIndex));
}
private boolean isCorruptedColumnIndex(ColumnIndex columnIndex)
{
if (columnIndex.getMaxValues() == null
|| columnIndex.getMinValues() == null
|| columnIndex.getNullCounts() == null
|| columnIndex.getNullPages() == null) {
return true;
}
if (columnIndex.getMaxValues().size() != columnIndex.getMinValues().size()
|| columnIndex.getMaxValues().size() != columnIndex.getNullPages().size()
|| columnIndex.getMaxValues().size() != columnIndex.getNullCounts().size()) {
return true;
}
return false;
}
public static long asLong(Object value)
{
if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) {
return ((Number) value).longValue();
}
throw new IllegalArgumentException("Can't convert value to long: " + value.getClass().getName());
}
// Caller should verify isCorruptedColumnIndex is false first
private boolean isEmptyColumnIndex(ColumnIndex columnIndex)
{
return columnIndex.getMaxValues().size() == 0;
}
private FilterPredicate convertToParquetFilter(DateTimeZone timeZone)
{
FilterPredicate filter = null;
for (RichColumnDescriptor column : columns) {
Domain domain = effectivePredicate.getDomains().get().get(column);
if (domain == null || domain.isNone()) {
continue;
}
if (domain.isAll()) {
continue;
}
FilterPredicate columnFilter = FilterApi.userDefined(FilterApi.intColumn(ColumnPath.get(column.getPath()).toDotString()), new DomainUserDefinedPredicate(domain, timeZone));
if (filter == null) {
filter = columnFilter;
}
else {
filter = FilterApi.and(filter, columnFilter);
}
}
return filter;
}
/**
* This class implements methods defined in UserDefinedPredicate based on the page statistic and tuple domain(for a column).
*/
static class DomainUserDefinedPredicate<T extends Comparable<T>>
extends UserDefinedPredicate<T>
implements Serializable // Required by argument of FilterApi.userDefined call
{
private final Domain columnDomain;
private final DateTimeZone timeZone;
public DomainUserDefinedPredicate(Domain domain, DateTimeZone timeZone)
{
this.columnDomain = domain;
this.timeZone = timeZone;
}
@Override
public boolean keep(T value)
{
if (value == null && !columnDomain.isNullAllowed()) {
return false;
}
return true;
}
@Override
public boolean canDrop(org.apache.parquet.filter2.predicate.Statistics<T> statistic)
{
if (statistic == null) {
return false;
}
Domain domain = getDomain(columnDomain.getType(), ImmutableList.of(statistic.getMin()), ImmutableList.of(statistic.getMax()), true, timeZone);
return !columnDomain.overlaps(domain);
}
@Override
public boolean inverseCanDrop(org.apache.parquet.filter2.predicate.Statistics<T> statistics)
{
// Since we don't use LogicalNotUserDefined, this method is not called.
// To be safe, we just keep the record by returning false.
return false;
}
}
private static class ColumnIndexValueConverter
{
private ColumnIndexValueConverter()
{
}
private Function<ByteBuffer, Object> getConverter(PrimitiveType primitiveType)
{
switch (primitiveType.getPrimitiveTypeName()) {
case BOOLEAN:
return (buffer) -> buffer.get(0) != 0;
case INT32:
return (buffer) -> buffer.order(LITTLE_ENDIAN).getInt(0);
case INT64:
return (buffer) -> buffer.order(LITTLE_ENDIAN).getLong(0);
case FLOAT:
return (buffer) -> buffer.order(LITTLE_ENDIAN).getFloat(0);
case DOUBLE:
return (buffer) -> buffer.order(LITTLE_ENDIAN).getDouble(0);
case FIXED_LEN_BYTE_ARRAY:
case BINARY:
case INT96:
default:
return (buffer) -> Binary.fromReusedByteBuffer(buffer);
}
}
}
private static class DictionaryValueConverter
{
private final Dictionary dictionary;
private DictionaryValueConverter(Dictionary dictionary)
{
this.dictionary = dictionary;
}
private Function<Integer, Object> getConverter(PrimitiveType primitiveType)
{
switch (primitiveType.getPrimitiveTypeName()) {
case INT32:
return (i) -> dictionary.decodeToInt(i);
case INT64:
return (i) -> dictionary.decodeToLong(i);
case FLOAT:
return (i) -> dictionary.decodeToFloat(i);
case DOUBLE:
return (i) -> dictionary.decodeToDouble(i);
case FIXED_LEN_BYTE_ARRAY:
case BINARY:
case INT96:
default:
return (i) -> dictionary.decodeToBinary(i);
}
}
}
}
| apache-2.0 |
lyncodev/jtwig-core | src/main/java/org/jtwig/environment/EnvironmentFactory.java | 4693 | package org.jtwig.environment;
import org.jtwig.environment.initializer.EnvironmentInitializer;
import org.jtwig.escape.environment.EscapeEnvironmentFactory;
import org.jtwig.extension.Extension;
import org.jtwig.functions.environment.FunctionResolverFactory;
import org.jtwig.parser.JtwigParserFactory;
import org.jtwig.property.environment.PropertyResolverEnvironmentFactory;
import org.jtwig.render.environment.RenderEnvironmentFactory;
import org.jtwig.render.expression.calculator.enumerated.environment.EnumerationListStrategyFactory;
import org.jtwig.resource.environment.ResourceEnvironmentFactory;
import org.jtwig.value.environment.ValueEnvironmentFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Stateless and thread-safe implementation of a Environment factory.
*/
public class EnvironmentFactory {
private static final Logger log = LoggerFactory.getLogger(EnvironmentFactory.class);
private final JtwigParserFactory jtwigParserFactory;
private final ResourceEnvironmentFactory resourceEnvironmentFactory;
private final RenderEnvironmentFactory renderEnvironmentFactory;
private final FunctionResolverFactory functionResolverFactory;
private final PropertyResolverEnvironmentFactory propertyResolverFactory;
private final ValueEnvironmentFactory valueEnvironmentFactory;
private final EnumerationListStrategyFactory enumerationListStrategyFactory;
private final EscapeEnvironmentFactory escapeEnvironmentFactory;
public EnvironmentFactory () {
this(new JtwigParserFactory(), new ResourceEnvironmentFactory(),
new RenderEnvironmentFactory(),
new FunctionResolverFactory(),
new PropertyResolverEnvironmentFactory(),
new ValueEnvironmentFactory(),
new EnumerationListStrategyFactory(),
new EscapeEnvironmentFactory());
}
public EnvironmentFactory(JtwigParserFactory jtwigParserFactory, ResourceEnvironmentFactory resourceEnvironmentFactory, RenderEnvironmentFactory renderEnvironmentFactory, FunctionResolverFactory functionResolverFactory, PropertyResolverEnvironmentFactory propertyResolverFactory, ValueEnvironmentFactory valueEnvironmentFactory, EnumerationListStrategyFactory enumerationListStrategyFactory, EscapeEnvironmentFactory escapeEnvironmentFactory) {
this.jtwigParserFactory = jtwigParserFactory;
this.resourceEnvironmentFactory = resourceEnvironmentFactory;
this.renderEnvironmentFactory = renderEnvironmentFactory;
this.functionResolverFactory = functionResolverFactory;
this.propertyResolverFactory = propertyResolverFactory;
this.enumerationListStrategyFactory = enumerationListStrategyFactory;
this.valueEnvironmentFactory = valueEnvironmentFactory;
this.escapeEnvironmentFactory = escapeEnvironmentFactory;
}
public Environment create(EnvironmentConfiguration environmentConfiguration) {
EnvironmentConfiguration configuration = environmentConfiguration;
if (!environmentConfiguration.getExtensions().isEmpty()) {
log.info("Jtwig base configuration extended with:");
EnvironmentConfigurationBuilder builder = new EnvironmentConfigurationBuilder(environmentConfiguration);
for (Extension extension : environmentConfiguration.getExtensions()) {
log.info("- {}", extension.getClass().getSimpleName());
extension.configure(builder);
}
configuration = builder.build();
}
Environment instance = new Environment(
jtwigParserFactory.create(configuration.getJtwigParserConfiguration()),
configuration.getParameters(),
resourceEnvironmentFactory.create(configuration.getResourceConfiguration()),
functionResolverFactory.create(configuration.getFunctions()),
propertyResolverFactory.create(configuration.getPropertyResolverConfiguration()),
renderEnvironmentFactory.create(configuration.getRenderConfiguration()),
valueEnvironmentFactory.create(configuration.getValueConfiguration()),
enumerationListStrategyFactory.create(configuration.getEnumerationStrategies()),
escapeEnvironmentFactory.create(configuration.getEscapeConfiguration()));
if (!configuration.getInitializers().isEmpty()) {
log.info("Jtwig pre-loading resources");
for (EnvironmentInitializer initializer : configuration.getInitializers()) {
initializer.initialize(instance);
}
}
return instance;
}
}
| apache-2.0 |
alanfgates/hive | standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/MsckPartitionExpressionProxy.java | 3124 | package org.apache.hadoop.hive.metastore;
/*
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.FileMetadataExprType;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.ql.io.sarg.SearchArgument;
// This is added as part of moving MSCK code from ql to standalone-metastore. There is a metastore API to drop
// partitions by name but we cannot use it because msck typically will contain partition value (year=2014). We almost
// never drop partition by name (year). So we need to construct expression filters, the current
// PartitionExpressionProxy implementations (PartitionExpressionForMetastore and HCatClientHMSImpl.ExpressionBuilder)
// all depend on ql code to build ExprNodeDesc for the partition expressions. It also depends on kryo for serializing
// the expression objects to byte[]. For MSCK drop partition, we don't need complex expression generator. For now,
// all we do is split the partition spec (year=2014/month=24) into filter expression year='2014' and month='24' and
// rely on metastore database to deal with type conversions. Ideally, PartitionExpressionProxy default implementation
// should use SearchArgument (storage-api) to construct the filter expression and not depend on ql, but the usecase
// for msck is pretty simple and this specific implementation should suffice.
public class MsckPartitionExpressionProxy implements PartitionExpressionProxy {
@Override
public String convertExprToFilter(final byte[] exprBytes, final String defaultPartitionName) throws MetaException {
return new String(exprBytes, StandardCharsets.UTF_8);
}
@Override
public boolean filterPartitionsByExpr(List<FieldSchema> partColumns, byte[] expr, String
defaultPartitionName, List<String> partitionNames) throws MetaException {
return false;
}
@Override
public FileMetadataExprType getMetadataType(String inputFormat) {
throw new UnsupportedOperationException();
}
@Override
public FileFormatProxy getFileFormatProxy(FileMetadataExprType type) {
throw new UnsupportedOperationException();
}
@Override
public SearchArgument createSarg(byte[] expr) {
throw new UnsupportedOperationException();
}
}
| apache-2.0 |
sblommers/guice-vaadin-mvp | src/main/java/com/google/code/vaadin/application/ui/ScopedUIProvider.java | 6090 | /*
* Copyright (C) 2013 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.code.vaadin.application.ui;
import com.google.code.vaadin.application.MVPApplicationInitParameters;
import com.google.code.vaadin.application.uiscope.UIKey;
import com.google.code.vaadin.application.uiscope.UIScope;
import com.google.code.vaadin.components.eventhandling.configuration.EventBusBinder;
import com.google.code.vaadin.internal.eventhandling.AbstractEventBusModule;
import com.google.code.vaadin.internal.eventhandling.sharedmodel.SharedEventBusSubscribersRegistry;
import com.google.code.vaadin.internal.uiscope.UIKeyProvider;
import com.google.code.vaadin.mvp.eventhandling.EventBus;
import com.google.code.vaadin.mvp.eventhandling.EventBusTypes;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.vaadin.server.ClientConnector;
import com.vaadin.server.UIClassSelectionEvent;
import com.vaadin.server.UICreateEvent;
import com.vaadin.server.UIProvider;
import com.vaadin.ui.UI;
import com.vaadin.util.CurrentInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Named;
import static com.vaadin.server.ClientConnector.DetachListener;
/**
* A Vaadin UI provider adapted to Guice-Vaadin-MVP specifics.
* It always returns UI class specified in webapp descriptor with {@link MVPApplicationInitParameters#P_APPLICATION_UI_CLASS}
* context parameter.
*
* @author Alexey Krylov
* @since 08.02.13
*/
public class ScopedUIProvider extends UIProvider {
/*===========================================[ STATIC VARIABLES ]=============*/
private static final long serialVersionUID = -5773777009877153344L;
/*===========================================[ INSTANCE VARIABLES ]====!=======*/
protected Logger logger;
protected UIKeyProvider uiKeyProvider;
protected Injector injector;
protected Class uiClass;
protected EventBusBinder eventBusBinder;
/*===========================================[ CONSTRUCTORS ]=================*/
@Inject
protected void init(Injector injector,
@Named(MVPApplicationInitParameters.P_APPLICATION_UI_CLASS) Class uiClass,
UIKeyProvider uiKeyProvider,
EventBusBinder eventBusBinder) {
Preconditions.checkArgument(ScopedUI.class.isAssignableFrom(uiClass), String.format("ERROR: %s is not subclass of ScopedUI", uiClass.getName()));
logger = LoggerFactory.getLogger(getClass());
this.injector = injector;
this.uiClass = uiClass;
this.uiKeyProvider = uiKeyProvider;
this.eventBusBinder = eventBusBinder;
}
/*===========================================[ CLASS METHODS ]================*/
@Override
public UI createInstance(UICreateEvent event) {
return createInstance(event.getUIClass());
}
@Override
public Class<? extends UI> getUIClass(UIClassSelectionEvent event) {
return uiClass;
}
public UI createInstance(Class<? extends UI> uiClass) {
Preconditions.checkArgument(ScopedUI.class.isAssignableFrom(uiClass), "ERROR: Invalid configuration - using ScopedUIProvider to instantiate no ScopedUI subclass");
UIKey uiKey = uiKeyProvider.get();
// hold the key while UI is created
CurrentInstance.set(UIKey.class, uiKey);
// and set up the scope
UIScope scope = UIScope.getCurrent();
scope.startScope(uiKey);
// create the UI
ScopedUI ui = (ScopedUI) injector.getInstance(uiClass);
ui.setInstanceKey(uiKey);
ui.setScope(scope);
ui.addDetachListener(createScopedUIDetachListener(uiClass, uiKey));
logger.debug(String.format("Returning instance of [%s] with key [%s]", uiClass.getName(), uiKey));
return ui;
}
protected DetachListener createScopedUIDetachListener(final Class<? extends UI> uiClass, final UIKey uiKey) {
return new DetachListener() {
private static final long serialVersionUID = -3087386509047842913L;
@Override
public void detach(ClientConnector.DetachEvent event) {
logger.debug(String.format("Detaching [%s] with key [%s]", uiClass.getName(), uiKey));
// If Shared Model EventBus is present
if (eventBusBinder.getBinding(EventBusTypes.SHARED_MODEL) != null) {
SharedEventBusSubscribersRegistry subscribersRegistry = injector.getInstance(SharedEventBusSubscribersRegistry.class);
Iterable<Object> uiScopedSubscribers = subscribersRegistry.removeAndGetSubscribers(uiKey);
EventBus sharedEventBus = injector.getInstance(Key.get(EventBus.class, AbstractEventBusModule.eventBusType(EventBusTypes.SHARED_MODEL)));
// Unsubscribe all non-singletons (UIScoped, nonscoped, etc) from SharedEventBus
for (Object subscriber : uiScopedSubscribers) {
sharedEventBus.unsubscribe(subscriber);
}
}
logger.info(String.format("Detached [%s] with key [%s]", uiClass.getName(), uiKey));
}
};
}
} | apache-2.0 |
levanhien8/SokkerViewer | src/main/java/pl/pronux/sokker/actions/PlayersManager.java | 13309 | package pl.pronux.sokker.actions;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import pl.pronux.sokker.data.sql.SQLQuery;
import pl.pronux.sokker.data.sql.SQLSession;
import pl.pronux.sokker.data.sql.dao.AssistantDao;
import pl.pronux.sokker.data.sql.dao.PlayersArchiveDao;
import pl.pronux.sokker.data.sql.dao.PlayersDao;
import pl.pronux.sokker.interfaces.DateConst;
import pl.pronux.sokker.model.Club;
import pl.pronux.sokker.model.Date;
import pl.pronux.sokker.model.Junior;
import pl.pronux.sokker.model.NtSkills;
import pl.pronux.sokker.model.Player;
import pl.pronux.sokker.model.PlayerArchive;
import pl.pronux.sokker.model.PlayerInterface;
import pl.pronux.sokker.model.PlayerSkills;
import pl.pronux.sokker.model.PlayerStats;
import pl.pronux.sokker.model.Training;
import pl.pronux.sokker.model.Transfer;
public final class PlayersManager {
private static PlayersManager instance = new PlayersManager();
private PlayersManager() {
}
public static PlayersManager getInstance() {
return instance;
}
public void updatePlayerArchive(PlayerArchive playerArchive) throws SQLException {
try {
SQLSession.connect();
new PlayersArchiveDao(SQLSession.getConnection()).updatePlayerArchive(playerArchive);
} finally {
SQLSession.close();
}
}
public void addPlayerArchive(PlayerArchive playerArchive) throws SQLException {
PlayersArchiveDao playersArchiveDao = new PlayersArchiveDao(SQLSession.getConnection());
if (playersArchiveDao.getPlayerArchive(playerArchive.getId()) == null) {
playersArchiveDao.addPlayer(playerArchive);
} else {
playersArchiveDao.updatePlayerArchive(playerArchive);
}
}
public void importPlayers(List<Player> players, Training training) throws SQLException {
PlayersDao playersDao = new PlayersDao(SQLSession.getConnection());
AssistantDao assistantDao = new AssistantDao(SQLSession.getConnection());
for (Player player : players) {
if (!playersDao.existsPlayer(player.getId())) {
playersDao.addPlayer(player);
player.getSkills()[0].setPassTraining(true);
playersDao.addPlayerSkills(player.getId(), player.getSkills()[0], training.getDate(), training.getId());
if (player.getNtSkills() != null && player.getNtSkills().length > 0) {
playersDao.addNtPlayerSkills(player.getId(), player.getNtSkills()[0], training.getDate());
}
player.setPositionTable(this.calculatePosition(player, assistantDao.getAssistantData()));
player.setPosition(player.getBestPosition());
this.updatePlayersPositions(player);
} else {
if (playersDao.existsPlayerHistory(player.getId())) {
playersDao.movePlayer(player.getId(), Player.STATUS_INCLUB);
}
if ((training.getStatus() & Training.NEW_TRAINING) != 0) {
playersDao.addPlayerSkills(player.getId(), player.getSkills()[0], training.getDate(), training.getId());
} else if ((training.getStatus() & Training.UPDATE_PLAYERS) != 0) {
playersDao.updatePlayerSkills(player.getId(), player.getSkills()[0], training);
playersDao.updatePlayer(player);
}
}
}
// FIXME instead of creating list of player in club get clubs and remove
// all (do everything on collections)
// sTemp = "(";
// for (int i = 0; i < players.size(); i++) {
// // warunek dla ostatniego stringa zeby nie dodawac na koncu ','
// if (i == players.size() - 1) {
// sTemp += players.get(i).getId();
// break;
// }
// sTemp += players.get(i).getId() + ",";
// }
//
// sTemp += ")";
// if (players.size() > 0) {
// SQLQuery.removeSoldPlayer(sTemp);
// } else {
// SQLQuery.removeSoldPlayer();
// }
}
public void addPlayers(List<Player> players, Training training) throws SQLException {
PlayersDao playersDao = new PlayersDao(SQLSession.getConnection());
AssistantDao assistantDao = new AssistantDao(SQLSession.getConnection());
for (Player player : players) {
if (!playersDao.existsPlayer(player.getId())) {
playersDao.addPlayer(player);
player.getSkills()[0].setPassTraining(true);
playersDao.addPlayerSkills(player.getId(), player.getSkills()[0], training.getDate(), training.getId());
if (player.getNtSkills() != null && player.getNtSkills().length > 0) {
playersDao.addNtPlayerSkills(player.getId(), player.getNtSkills()[0], training.getDate());
}
player.setPositionTable(this.calculatePosition(player, assistantDao.getAssistantData()));
player.setPosition(player.getBestPosition());
this.updatePlayersPositions(player);
} else {
if (playersDao.existsPlayerHistory(player.getId())) {
playersDao.movePlayer(player.getId(), Player.STATUS_INCLUB);
}
if ((training.getStatus() & Training.NEW_TRAINING) != 0 || playersDao.getPlayerSkills(player, training) == null) {
playersDao.addPlayerSkills(player.getId(), player.getSkills()[0], training.getDate(), training.getId());
} else {
playersDao.updatePlayerSkills(player.getId(), player.getSkills()[0], training.getDate());
}
playersDao.updatePlayer(player);
if (player.getNtSkills() != null && player.getNtSkills().length > 0
&& playersDao.getNumberOfNtMatch(player.getId()) < player.getNtSkills()[0].getNtMatches()) {
playersDao.addNtPlayerSkills(player.getId(), player.getNtSkills()[0], training.getDate());
}
}
}
// FIXME instead of creating list of player in club get clubs and remove
// all (do everything on collections)
String sTemp = "(";
for (int i = 0; i < players.size(); i++) {
// warunek dla ostatniego stringa zeby nie dodawac na koncu ','
if (i == players.size() - 1) {
sTemp += players.get(i).getId();
break;
}
sTemp += players.get(i).getId() + ",";
}
sTemp += ")";
if (players.size() > 0) {
playersDao.removeSoldPlayer(sTemp);
} else {
playersDao.removeSoldPlayer();
}
}
public void importPlayer(PlayerInterface player) throws SQLException {
try {
PlayerSkills[] skills = player.getSkills();
Calendar cal = Calendar.getInstance();
SQLSession.connect();
PlayersDao playersDao = new PlayersDao(SQLSession.getConnection());
List<Long> alMillis = playersDao.getTrainingDates(player.getId());
for (int i = 0; i < skills.length; i++) {
cal.setTimeInMillis(skills[i].getDate().getMillis());
Date date = new Date(cal.getTimeInMillis());
int day = date.thursdayFirstDayOfWeek();
Date date1 = new Date(cal.getTimeInMillis() - day * (DateConst.DAY));
date1.getCalendar().set(Calendar.HOUR_OF_DAY, 0);
date1.getCalendar().set(Calendar.MINUTE, 0);
date1.getCalendar().set(Calendar.SECOND, 0);
date1.getCalendar().set(Calendar.MILLISECOND, 0);
Date date2 = new Date(cal.getTimeInMillis() + (7 - day) * (DateConst.DAY));
date2.getCalendar().set(Calendar.HOUR_OF_DAY, 0);
date2.getCalendar().set(Calendar.MINUTE, 0);
date2.getCalendar().set(Calendar.SECOND, 0);
date2.getCalendar().set(Calendar.MILLISECOND, 0);
if (alMillis.size() > 0) {
boolean found = false;
for (Iterator<Long> itr = alMillis.iterator(); itr.hasNext();) {
Long lDate = itr.next();
if (lDate >= date1.getMillis() && lDate < date2.getMillis()) {
if (lDate < cal.getTimeInMillis()) {
playersDao.updatePlayerSkills(player.getId(), skills[i], date);
}
itr.remove();
// alMillis.remove(lDate);
found = true;
}
}
if (!found) {
playersDao.addPlayerSkills(player.getId(), skills[i], date);
}
}
}
} finally {
SQLSession.close();
}
}
public List<Player> getPlayers(int status, Club team, Map<Integer, Junior> juniorTrainedMap, Map<Integer, Training> trainingMap,
Map<Integer, Transfer> transfersSellMap, Map<Integer, Transfer> transfersBuyMap) throws SQLException {
boolean newConnection = SQLQuery.connect();
// pobieranie graczy
PlayersDao playersDao = new PlayersDao(SQLSession.getConnection());
List<Player> players = playersDao.getPlayers(status, juniorTrainedMap);
for (Player player : players) {
player.setTeam(team);
if (transfersBuyMap.get(player.getId()) != null) {
player.setTransferBuy(transfersBuyMap.get(player.getId()));
transfersBuyMap.get(player.getId()).setPlayer(player);
}
if (transfersSellMap.get(player.getId()) != null) {
player.setTransferSell(transfersSellMap.get(player.getId()));
transfersSellMap.get(player.getId()).setPlayer(player);
}
PlayerSkills[] skills = playersDao.getPlayerSkills(player, trainingMap);
NtSkills[] ntSkills = playersDao.getPlayerNtSkills(player);
player.setNtSkills(ntSkills);
Junior junior = juniorTrainedMap.get(player.getJuniorId());
player.setJunior(junior);
if (junior != null) {
junior.setPlayer(player);
}
player.setSkills(skills);
}
SQLSession.close(newConnection);
return players;
}
public List<Player> getPlayers(Club team, Map<Integer, Junior> juniorTrainedMap, Map<Integer, Training> trainingMap,
Map<Integer, Transfer> transfersSellMap, Map<Integer, Transfer> transfersBuyMap) throws SQLException {
return getPlayers(Player.STATUS_INCLUB, team, juniorTrainedMap, trainingMap, transfersSellMap, transfersBuyMap);
}
public Map<Integer, PlayerArchive> getPlayersArchive() throws SQLException {
boolean newConnection = SQLQuery.connect();
PlayersArchiveDao playersArchiveDao = new PlayersArchiveDao(SQLSession.getConnection());
Map<Integer, PlayerArchive> players = playersArchiveDao.getPlayers();
SQLSession.close(newConnection);
return players;
}
public String getPlayerArchiveNote(int playerID) throws SQLException {
PlayersArchiveDao playersArchiveDao = new PlayersArchiveDao(SQLSession.getConnection());
return playersArchiveDao.getPlayerArchiveNote(playerID);
}
public List<Player> getPlayersFromTrashData(Club team, Map<Integer, Junior> juniorTrainedMap, Map<Integer, Training> trainingMap,
Map<Integer, Transfer> transfersSellMap, Map<Integer, Transfer> transfersBuyMap) throws SQLException {
return getPlayers(Player.STATUS_TRASH, team, juniorTrainedMap, trainingMap, transfersSellMap, transfersBuyMap);
}
public List<Player> getPlayersHistoryData(Club team, Map<Integer, Junior> juniorTrainedMap, Map<Integer, Training> trainingMap,
Map<Integer, Transfer> transfersSellMap, Map<Integer, Transfer> transfersBuyMap) throws SQLException {
return getPlayers(Player.STATUS_HISTORY, team, juniorTrainedMap, trainingMap, transfersSellMap, transfersBuyMap);
}
public void updatePlayerStatsInjury(PlayerStats stats) throws SQLException {
try {
SQLSession.connect();
new PlayersDao(SQLSession.getConnection()).updatePlayerStatsInjuryDays(stats);
} finally {
SQLSession.close();
}
}
public void changePlayerPassTraining(PlayerSkills playerSkills) throws SQLException {
try {
SQLSession.connect();
playerSkills.setPassTraining(!playerSkills.isPassTraining());
new PlayersDao(SQLSession.getConnection()).updatePlayerPassTraining(playerSkills);
} finally {
SQLSession.close();
}
}
public void updatePlayersBuyPrice(Player player) throws SQLException {
try {
SQLSession.connect();
new PlayersDao(SQLSession.getConnection()).updatePlayerBuyPrice(player);
} finally {
SQLSession.close();
}
}
public void updatePlayersPositions(List<Player> players) throws SQLException {
boolean newConnection = false;
try {
if (SQLSession.getConnection().isClosed()) {
SQLSession.connect();
newConnection = true;
}
for (Player player : players) {
new PlayersDao(SQLSession.getConnection()).updatePlayerPosition(player);
}
if (newConnection) {
SQLSession.close();
}
} catch (SQLException e) {
SQLSession.close();
throw e;
}
}
public void updatePlayersPositions(Player player) throws SQLException {
boolean connect = true;
try {
if (SQLSession.getConnection() != null) {
if (SQLSession.getConnection().isClosed()) {
SQLSession.connect();
connect = false;
}
} else {
SQLSession.connect();
}
new PlayersDao(SQLSession.getConnection()).updatePlayerPosition(player);
} finally {
if (!connect) {
SQLSession.close();
}
}
}
public void updatePlayersSoldPrice(Player player) throws SQLException {
try {
SQLSession.connect();
new PlayersDao(SQLSession.getConnection()).updatePlayerSoldPrice(player);
} finally {
SQLSession.close();
}
}
public void calculatePositionForAllPlayer(List<Player> players, int[][] data) {
for (Player player : players) {
player.setPositionTable(calculatePosition(player, data));
player.setPosition(player.getBestPosition());
}
}
public double[] calculatePosition(Player player, int[][] data) {
double[] table = new double[data.length];
for (int j = 0; j < data.length; j++) {
double sum = 0.0;
for (int i = 1; i < data[j].length; i++) {
sum += data[j][i] * player.getSkills()[player.getSkills().length - 1].getStatsTable()[i + 2];
}
table[j] = sum / 100;
}
return table;
}
public void updateAssistantData(int[][] data) throws SQLException {
try {
SQLSession.connect();
AssistantDao assistantDao = new AssistantDao(SQLSession.getConnection());
assistantDao.updateAssistantData(data);
} finally {
SQLSession.close();
}
}
}
| apache-2.0 |
SilverThings/SilverWare | microservices/src/main/java/io/silverware/microservices/util/Utils.java | 5686 | /*
* -----------------------------------------------------------------------\
* SilverWare
*
* Copyright (C) 2015 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 io.silverware.microservices.util;
import io.silverware.microservices.Context;
import io.silverware.microservices.silver.CdiSilverService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
/**
* Generic utilities.
*
* @author <a href="mailto:marvenec@gmail.com">Martin Večeřa</a>
*/
public class Utils {
/**
* Logger.
*/
private static final Logger log = LogManager.getLogger(Utils.class);
/**
* Maximum number of attempts to wait for an URL to become available.
*/
private static final int MAX_WAIT_TRIES = 60;
/**
* Logs a shutdown message with the given exception.
*
* @param log
* A logger where to log the message to.
* @param ie
* An exception causing the shutdown.
*/
public static void shutdownLog(final Logger log, final InterruptedException ie) {
log.info("Execution interrupted, exiting.");
if (log.isTraceEnabled()) {
log.trace("Interrupted from: ", ie);
}
}
/**
* Waits for the URL to become available.
*
* @param urlString
* The URL to check for.
* @param code
* The expected HTTP response code.
* @return Returns true if the URL was available, false otherwise.
* @throws Exception
* When it was not possible to check the URL.
*/
public static boolean waitForHttp(String urlString, int code) throws Exception {
final URL url = new URL(urlString);
int lastCode = -1;
for (int i = 0; i < MAX_WAIT_TRIES; ++i) {
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
lastCode = conn.getResponseCode();
if (lastCode == code) {
conn.disconnect();
return true;
}
conn.disconnect();
} catch (IOException x) {
// Continue waiting
}
Thread.sleep(1000);
}
return false;
}
/**
* This methods wait for CDI providers to startup
*
* @param context
* context where the provider will be stored
* @throws InterruptedException
* if thread was interrupted during sleep
*/
public static void waitForCDIProvider(Context context) throws InterruptedException {
for (int i = 0; i < MAX_WAIT_TRIES; ++i) {
if (context.getProvider(CdiSilverService.class) != null && ((CdiSilverService) context.getProvider(CdiSilverService.class)).isDeployed()) {
return;
}
Thread.sleep(200);
}
throw new RuntimeException("Cdi provider was not started");
}
/**
* Completely reads the content of the given URL as a string.
*
* @param urlString
* The URL to read from.
* @return The content of the given URL.
* @throws IOException
* When it was not possible to read from the URL.
*/
public static String readFromUrl(String urlString) throws IOException {
return new Scanner(new URL(urlString).openStream(), "UTF-8").useDelimiter("\\A").next();
}
/**
* Gets the manifest entry for the given class.
*
* @param clazz
* The class I want to obtain entry for.
* @param entryName
* The name of the entry to obtain.
* @return The entry from manifest, null if there is no such entry or the manifest file does not exists.
* @throws IOException
* When it was not possible to get the manifest file.
*/
public static String getManifestEntry(final Class clazz, final String entryName) throws IOException {
Enumeration<URL> resources = clazz.getClassLoader().getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
try (final InputStream is = resources.nextElement().openStream()) {
Manifest manifest = new Manifest(is);
Attributes attr = manifest.getMainAttributes();
String value = attr.getValue(entryName);
if (value != null && value.length() > 0) {
return value;
}
}
}
return null;
}
/**
* Do the best to sleep for the given time. Ignores {@link InterruptedException}.
*
* @param ms
* The number of milliseconds to sleep for.
*/
public static void sleep(final long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ie) {
// ignored
}
}
public static String toLowerCamelCase(String upperCamelCase) {
return upperCamelCase.substring(0, 1).toLowerCase() + upperCamelCase.substring(1);
}
}
| apache-2.0 |
tking/BGP4J | lib/netty-bgp4/src/test/java/org/bgp4j/netty/MockPeerConnectionInformation.java | 3088 | /**
* Copyright 2012 Rainer Bieniek (Rainer.Bieniek@web.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* File: org.bgp4j.netty.MockPeerConnectionInformation.java
*/
package org.bgp4j.netty;
import org.bgp4j.net.ASType;
/**
* @author Rainer Bieniek (Rainer.Bieniek@web.de)
*
*/
public class MockPeerConnectionInformation implements PeerConnectionInformation {
private ASType asTypeInUse;
private int localAS;
private int remoteAS;
private long localBgpIdentifier;
private long remoteBgpIdentifier;
/* (non-Javadoc)
* @see org.bgp4j.netty.PeerConnectionInformation#getAsTypeInUse()
*/
@Override
public ASType getAsTypeInUse() {
return asTypeInUse;
}
/* (non-Javadoc)
* @see org.bgp4j.netty.PeerConnectionInformation#getLocalAS()
*/
@Override
public int getLocalAS() {
return localAS;
}
/* (non-Javadoc)
* @see org.bgp4j.netty.PeerConnectionInformation#getRemoteAS()
*/
@Override
public int getRemoteAS() {
// TODO Auto-generated method stub
return remoteAS;
}
/* (non-Javadoc)
* @see org.bgp4j.netty.PeerConnectionInformation#isIBGPConnection()
*/
@Override
public boolean isIBGPConnection() {
return (localAS == remoteAS);
}
/* (non-Javadoc)
* @see org.bgp4j.netty.PeerConnectionInformation#isEBGPConnection()
*/
@Override
public boolean isEBGPConnection() {
return (localAS != remoteAS);
}
/* (non-Javadoc)
* @see org.bgp4j.netty.PeerConnectionInformation#isAS4OctetsInUse()
*/
@Override
public boolean isAS4OctetsInUse() {
return (asTypeInUse == ASType.AS_NUMBER_4OCTETS);
}
/**
* @return the localBGPIdentifier
*/
public long getLocalBgpIdentifier() {
return localBgpIdentifier;
}
/**
* @param localBGPIdentifier the localBGPIdentifier to set
*/
public void setLocalBgpIdentifier(long localBGPIdentifier) {
this.localBgpIdentifier = localBGPIdentifier;
}
/**
* @return the remoteBGPIdentifier
*/
public long getRemoteBgpIdentifier() {
return remoteBgpIdentifier;
}
/**
* @param remoteBGPIdentifier the remoteBGPIdentifier to set
*/
public void setRemoteBgpIdentifier(long remoteBGPIdentifier) {
this.remoteBgpIdentifier = remoteBGPIdentifier;
}
/**
* @param asTypeInUse the asTypeInUse to set
*/
public void setAsTypeInUse(ASType asTypeInUse) {
this.asTypeInUse = asTypeInUse;
}
/**
* @param localAS the localAS to set
*/
public void setLocalAS(int localAS) {
this.localAS = localAS;
}
/**
* @param remoteAS the remoteAS to set
*/
public void setRemoteAS(int remoteAS) {
this.remoteAS = remoteAS;
}
}
| apache-2.0 |
atomix/atomix | core/src/main/java/io/atomix/core/transaction/impl/SingletonTransactionalSet.java | 1770 | /*
* Copyright 2019-present Open Networking Foundation
*
* 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.atomix.core.transaction.impl;
import java.util.concurrent.CompletableFuture;
import io.atomix.core.set.impl.SetUpdate;
import io.atomix.core.transaction.TransactionLog;
import io.atomix.core.transaction.TransactionParticipant;
/**
* Singleton transactional set.
*/
public class SingletonTransactionalSet<E> extends DelegatingTransactionalSet<E> implements TransactionParticipant<SetUpdate<E>> {
private final TransactionalSetParticipant<E> set;
public SingletonTransactionalSet(TransactionalSetParticipant<E> set) {
super(set);
this.set = set;
}
@Override
public TransactionLog<SetUpdate<E>> log() {
return set.log();
}
@Override
public CompletableFuture<Boolean> prepare() {
return set.prepare();
}
@Override
public CompletableFuture<Void> commit() {
return set.commit();
}
@Override
public CompletableFuture<Void> rollback() {
return set.rollback();
}
@Override
public CompletableFuture<Void> close() {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<Void> delete() {
return CompletableFuture.completedFuture(null);
}
}
| apache-2.0 |
cbeams-archive/spring-framework-2.5.x | src/org/springframework/web/struts/AutowiringRequestProcessor.java | 7692 | /*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.struts;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.RequestProcessor;
import org.apache.struts.config.ModuleConfig;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.context.WebApplicationContext;
/**
* Subclass of Struts's default RequestProcessor that autowires Struts Actions
* with Spring beans defined in ContextLoaderPlugIn's WebApplicationContext
* or - in case of general service layer beans - in the root WebApplicationContext.
*
* <p>In the Struts config file, you simply continue to specify the original
* Action class. The instance created for that class will automatically get
* wired with matching service layer beans, that is, bean property setters
* will automatically be called if a service layer bean matches the property.
*
* <pre>
* <action path="/login" type="myapp.MyAction"/></pre>
*
* There are two autowire modes available: "byType" and "byName". The default
* is "byType", matching service layer beans with the Action's bean property
* argument types. This behavior can be changed through specifying an "autowire"
* init-param for the Struts ActionServlet with the value "byName", which will
* match service layer bean names with the Action's bean property <i>names</i>.
*
* <p>Dependency checking is turned off by default: If no matching service
* layer bean can be found, the setter in question will simply not get invoked.
* To enforce matching service layer beans, consider specify the "dependencyCheck"
* init-param for the Struts ActionServlet with the value "true".
*
* <p>If you also need the Tiles setup functionality of the original
* TilesRequestProcessor, use AutowiringTilesRequestProcessor. As there's just
* a single central class to customize in Struts, we have to provide another
* subclass here, covering both the Tiles and the Spring delegation aspect.
*
* <p>The default implementation delegates to the DelegatingActionUtils
* class as fas as possible, to reuse as much code as possible despite
* the need to provide two RequestProcessor subclasses. If you need to
* subclass yet another RequestProcessor, take this class as a template,
* delegating to DelegatingActionUtils just like it.
*
* @author Juergen Hoeller
* @since 2.0
* @see AutowiringTilesRequestProcessor
* @see ContextLoaderPlugIn
* @see DelegatingActionUtils
*/
public class AutowiringRequestProcessor extends RequestProcessor {
private WebApplicationContext webApplicationContext;
private int autowireMode = AutowireCapableBeanFactory.AUTOWIRE_NO;
private boolean dependencyCheck = false;
public void init(ActionServlet actionServlet, ModuleConfig moduleConfig) throws ServletException {
super.init(actionServlet, moduleConfig);
if (actionServlet != null) {
this.webApplicationContext = initWebApplicationContext(actionServlet, moduleConfig);
this.autowireMode = initAutowireMode(actionServlet, moduleConfig);
this.dependencyCheck = initDependencyCheck(actionServlet, moduleConfig);
}
}
/**
* Fetch ContextLoaderPlugIn's WebApplicationContext from the ServletContext,
* falling back to the root WebApplicationContext. This context is supposed
* to contain the service layer beans to wire the Struts Actions with.
* @param actionServlet the associated ActionServlet
* @param moduleConfig the associated ModuleConfig
* @return the WebApplicationContext
* @throws IllegalStateException if no WebApplicationContext could be found
* @see DelegatingActionUtils#findRequiredWebApplicationContext
* @see ContextLoaderPlugIn#SERVLET_CONTEXT_PREFIX
*/
protected WebApplicationContext initWebApplicationContext(
ActionServlet actionServlet, ModuleConfig moduleConfig) throws IllegalStateException {
WebApplicationContext wac =
DelegatingActionUtils.findRequiredWebApplicationContext(actionServlet, moduleConfig);
if (wac instanceof ConfigurableApplicationContext) {
((ConfigurableApplicationContext) wac).getBeanFactory().ignoreDependencyType(ActionServlet.class);
}
return wac;
}
/**
* Determine the autowire mode to use for wiring Struts Actions.
* <p>The default implementation checks the "autowire" init-param of the
* Struts ActionServlet, falling back to "AUTOWIRE_BY_TYPE" as default.
* @param actionServlet the associated ActionServlet
* @param moduleConfig the associated ModuleConfig
* @return the autowire mode to use
* @see DelegatingActionUtils#getAutowireMode
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#autowireBeanProperties
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#AUTOWIRE_BY_TYPE
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#AUTOWIRE_BY_NAME
*/
protected int initAutowireMode(ActionServlet actionServlet, ModuleConfig moduleConfig) {
return DelegatingActionUtils.getAutowireMode(actionServlet);
}
/**
* Determine whether to apply a dependency check after wiring Struts Actions.
* <p>The default implementation checks the "dependencyCheck" init-param of the
* Struts ActionServlet, falling back to no dependency check as default.
* @param actionServlet the associated ActionServlet
* @param moduleConfig the associated ModuleConfig
* @return whether to enforce a dependency check or not
* @see DelegatingActionUtils#getDependencyCheck
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#autowireBeanProperties
*/
protected boolean initDependencyCheck(ActionServlet actionServlet, ModuleConfig moduleConfig) {
return DelegatingActionUtils.getDependencyCheck(actionServlet);
}
/**
* Return the current Spring WebApplicationContext.
*/
protected final WebApplicationContext getWebApplicationContext() {
return this.webApplicationContext;
}
/**
* Return the autowire mode to use for wiring Struts Actions.
*/
protected final int getAutowireMode() {
return autowireMode;
}
/**
* Return whether to apply a dependency check after wiring Struts Actions.
*/
protected final boolean getDependencyCheck() {
return dependencyCheck;
}
/**
* Extend the base class method to autowire each created Action instance.
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#autowireBeanProperties
*/
protected Action processActionCreate(
HttpServletRequest request, HttpServletResponse response, ActionMapping mapping)
throws IOException {
Action action = super.processActionCreate(request, response, mapping);
getWebApplicationContext().getAutowireCapableBeanFactory().autowireBeanProperties(
action, getAutowireMode(), getDependencyCheck());
return action;
}
}
| apache-2.0 |
lastfm/moji | src/test/java/fm/last/moji/tracker/impl/TrackerImplTest.java | 9473 | /**
* Copyright (C) 2012-2017 Last.fm & The "mogilefs-moji" committers
*
* 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 fm.last.moji.tracker.impl;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import fm.last.moji.tracker.Destination;
import fm.last.moji.tracker.KeyExistsAlreadyException;
import fm.last.moji.tracker.TrackerException;
import fm.last.moji.tracker.UnknownCommandException;
import fm.last.moji.tracker.UnknownKeyException;
@RunWith(MockitoJUnitRunner.class)
public class TrackerImplTest {
private static final String STORAGE_CLASS = "storageClass";
private static final String KEY = "key";
private static final String DOMAIN = "domain";
private static final long SIZE = 0;
private static final String NEW_KEY = "newKey";
@Mock
private Socket mockSocket;
@Mock
private RequestHandler mockRequestHandler;
@Mock
private Response mockResponse;
private TrackerImpl tracker;
private final ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class);
@Before
public void setUp() throws IOException {
tracker = new TrackerImpl(mockSocket, mockRequestHandler);
when(mockResponse.getStatus()).thenReturn(ResponseStatus.OK);
when(mockRequestHandler.performRequest(requestCaptor.capture())).thenReturn(mockResponse);
}
@Test
public void getPaths() throws Exception {
// See: GetPathsOperationTest
when(mockResponse.getValue("paths")).thenReturn("0");
List<URL> paths = tracker.getPaths(KEY, DOMAIN);
assertThat(paths.size(), is(0));
}
@Test
public void fileInfoRequest() throws Exception {
Map<String, String> attributes = tracker.fileInfo(KEY, DOMAIN);
Request request = requestCaptor.getValue();
assertThat(request.getCommand(), is("file_info"));
assertThat(request.getArguments().size(), is(2));
assertThat(request.getArguments().get("domain"), is(DOMAIN));
assertThat(request.getArguments().get("key"), is(KEY));
assertThat(attributes.isEmpty(), is(true));
}
@Test(expected = UnknownCommandException.class)
public void fileInfoOldMogileVersion() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("unknown_command");
tracker.fileInfo(KEY, DOMAIN);
}
@Test(expected = UnknownKeyException.class)
public void fileInfoUnknownKey() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("unknown_key");
tracker.fileInfo(KEY, DOMAIN);
}
@Test
public void createOpen() throws Exception {
// See: CreateOpenOperationTest
when(mockResponse.getValue("dev_count")).thenReturn("0");
when(mockResponse.getValue("fid")).thenReturn("0");
List<Destination> destinations = tracker.createOpen(KEY, DOMAIN, STORAGE_CLASS);
assertThat(destinations.size(), is(0));
}
@Test
public void deleteRequest() throws Exception {
tracker.delete(KEY, DOMAIN);
Request request = requestCaptor.getValue();
assertThat(request.getCommand(), is("delete"));
assertThat(request.getArguments().size(), is(2));
assertThat(request.getArguments().get("domain"), is(DOMAIN));
assertThat(request.getArguments().get("key"), is(KEY));
}
@Test(expected = UnknownKeyException.class)
public void deleteUnknownKey() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("unknown_key");
tracker.delete(KEY, DOMAIN);
}
@Test(expected = TrackerException.class)
public void deleteFails() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("something else");
try {
tracker.delete(KEY, DOMAIN);
} catch (UnknownKeyException ignored) {
}
}
@Test
public void updateStorageClassRequest() throws Exception {
tracker.updateStorageClass(KEY, DOMAIN, STORAGE_CLASS);
Request request = requestCaptor.getValue();
assertThat(request.getCommand(), is("updateclass"));
assertThat(request.getArguments().size(), is(3));
assertThat(request.getArguments().get("domain"), is(DOMAIN));
assertThat(request.getArguments().get("key"), is(KEY));
assertThat(request.getArguments().get("class"), is(STORAGE_CLASS));
}
@Test(expected = UnknownKeyException.class)
public void updateStorageClassUnknownKey() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("unknown_key");
tracker.updateStorageClass(KEY, DOMAIN, STORAGE_CLASS);
}
@Test(expected = TrackerException.class)
public void updateStorageClassFails() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("something else");
try {
tracker.updateStorageClass(KEY, DOMAIN, STORAGE_CLASS);
} catch (UnknownKeyException ignored) {
}
}
@Test
public void renameRequest() throws Exception {
tracker.rename(KEY, DOMAIN, NEW_KEY);
Request request = requestCaptor.getValue();
assertThat(request.getCommand(), is("rename"));
assertThat(request.getArguments().size(), is(3));
assertThat(request.getArguments().get("domain"), is(DOMAIN));
assertThat(request.getArguments().get("from_key"), is(KEY));
assertThat(request.getArguments().get("to_key"), is(NEW_KEY));
}
@Test(expected = UnknownKeyException.class)
public void renameUnknownKey() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("unknown_key");
tracker.rename(KEY, DOMAIN, NEW_KEY);
}
@Test(expected = KeyExistsAlreadyException.class)
public void renameKeyExists() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("key_exists");
tracker.rename(KEY, DOMAIN, NEW_KEY);
}
@Test(expected = TrackerException.class)
public void renameFails() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("something else");
try {
tracker.rename(KEY, DOMAIN, NEW_KEY);
} catch (UnknownKeyException ignored) {
} catch (KeyExistsAlreadyException ignored) {
}
}
@Test
public void noopRequest() throws Exception {
tracker.noop();
Request request = requestCaptor.getValue();
assertThat(request.getCommand(), is("noop"));
assertThat(request.getArguments().size(), is(0));
}
@Test(expected = TrackerException.class)
public void noopFails() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("unknown_key");
tracker.noop();
}
@Test
public void createCloseRequest() throws Exception {
Destination destination = new Destination(new URL("http://www.last.fm/1/"), 23, 32L);
tracker.createClose(KEY, DOMAIN, destination, SIZE);
Request request = requestCaptor.getValue();
assertThat(request.getCommand(), is("create_close"));
assertThat(request.getArguments().size(), is(6));
assertThat(request.getArguments().get("domain"), is(DOMAIN));
assertThat(request.getArguments().get("key"), is(KEY));
assertThat(request.getArguments().get("size"), is(Long.toString(SIZE)));
assertThat(request.getArguments().get("devid"), is("23"));
assertThat(request.getArguments().get("path"), is("http://www.last.fm/1/"));
assertThat(request.getArguments().get("fid"), is("32"));
}
@Test(expected = TrackerException.class)
public void createCloseFails() throws Exception {
when(mockResponse.getStatus()).thenReturn(ResponseStatus.ERROR);
when(mockResponse.getMessage()).thenReturn("unknown_key");
tracker.noop();
}
@Test
public void close() throws IOException {
tracker.close();
verify(mockSocket).close();
verify(mockRequestHandler).close();
}
@Test
public void deviceStatusesRequest() throws Exception {
Map<String, Map<String, String>> deviceStatuses = tracker.getDeviceStatuses(DOMAIN);
Request request = requestCaptor.getValue();
assertThat(request.getCommand(), is("get_devices"));
assertThat(request.getArguments().size(), is(1));
assertThat(request.getArguments().get("domain"), is(DOMAIN));
assertThat(deviceStatuses.isEmpty(), is(true));
}
}
| apache-2.0 |
hasinitg/airavata | modules/integration-tests/src/test/java/org/apache/airavata/integration/tools/DocumentCreatorNew.java | 50520 | /*
*
* 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.airavata.integration.tools;
import org.apache.airavata.registry.cpi.AppCatalog;
import org.apache.airavata.registry.cpi.AppCatalogException;
import org.apache.airavata.api.Airavata;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationModule;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationParallelismType;
import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription;
import org.apache.airavata.model.appcatalog.appinterface.DataType;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
import org.apache.airavata.model.appcatalog.computeresource.JobManagerCommand;
import org.apache.airavata.model.appcatalog.computeresource.LOCALDataMovement;
import org.apache.airavata.model.appcatalog.computeresource.LOCALSubmission;
import org.apache.airavata.model.appcatalog.computeresource.ResourceJobManager;
import org.apache.airavata.model.appcatalog.computeresource.ResourceJobManagerType;
import org.apache.airavata.model.appcatalog.computeresource.SCPDataMovement;
import org.apache.airavata.model.appcatalog.computeresource.SSHJobSubmission;
import org.apache.airavata.model.appcatalog.computeresource.SecurityProtocol;
import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference;
import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile;
import org.apache.airavata.model.error.AiravataClientException;
import org.apache.airavata.model.error.AiravataSystemException;
import org.apache.airavata.model.error.InvalidRequestException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
public class DocumentCreatorNew {
private final static Logger log = LoggerFactory.getLogger(DocumentCreatorNew.class);
private static final String DEFAULT_GATEWAY = "php_reference_gateway";
private AppCatalog appcatalog = null;
private String trestleshpcHostAddress = "trestles.sdsc.edu";
private String lonestarHostAddress = "lonestar.tacc.utexas.edu";
private String stampedeHostAddress = "stampede.tacc.xsede.org";
private String gridftpAddress = "gsiftp://trestles-dm1.sdsc.edu:2811";
private String gramAddress = "trestles-login1.sdsc.edu:2119/jobmanager-pbstest2";
private String bigRed2HostAddress = "bigred2.uits.iu.edu";
//App Module Id's
private static String echoModuleId;
private static String amberModuleId;
private static String autoDockModuleId;
private static String espressoModuleId;
private static String gromacsModuleId;
private static String lammpsModuleId;
private static String nwChemModuleId;
private static String trinityModuleId;
private static String wrfModuleId;
private Airavata.Client client;
private GatewayResourceProfile gatewayResourceProfile;
public DocumentCreatorNew(Airavata.Client client) throws AppCatalogException {
this.client = client;
}
public String createLocalHostDocs() throws AppCatalogException, InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
//Define compute resource host
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription(
"localhost", new ArrayList<String>(Arrays.asList(new String[]{"127.0.0.1"})), new ArrayList<String>(Arrays.asList(new String[]{"127.0.0.1"})));
// host.setIsEmpty(true);
host.setComputeResourceId(client.registerComputeResource(host));
LOCALSubmission localSubmission = new LOCALSubmission();
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.FORK, null, null, null);
localSubmission.setResourceJobManager(resourceJobManager);
client.addLocalSubmissionDetails(host.getComputeResourceId(), 1, localSubmission);
LOCALDataMovement localDataMovement = new LOCALDataMovement();
client.addLocalDataMovementDetails(host.getComputeResourceId(), 1, localDataMovement);
//Define application module
ApplicationModule module = DocumentCreatorUtils.createApplicationModule("echo", "1.0.0", "Local host echo applications");
module.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, module));
//Define application interfaces
ApplicationInterfaceDescription application = new ApplicationInterfaceDescription();
// application.setIsEmpty(false);
application.setApplicationName("SimpleEcho0");
application.addToApplicationModules(module.getAppModuleId());
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("echo_input", "echo_input", "Echo Input Data", null, DataType.STRING));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("echo_output", null, DataType.STRING));
application.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application));
//Define application deployment
ApplicationDeploymentDescription deployment = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), module.getAppModuleId(), "/bin/echo", ApplicationParallelismType.SERIAL, "Local echo app depoyment");
deployment.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment));
//Define gateway profile
ComputeResourcePreference computeResourcePreference = DocumentCreatorUtils.createComputeResourcePreference(
host.getComputeResourceId(), "/tmp", null,
false, null,
null, null);
gatewayResourceProfile = new GatewayResourceProfile();
// gatewayResourceProfile.setGatewayID("default");
gatewayResourceProfile.setGatewayID(DEFAULT_GATEWAY);
gatewayResourceProfile.addToComputeResourcePreferences(computeResourcePreference);
String gatewayId = client.registerGatewayResourceProfile(gatewayResourceProfile);
gatewayResourceProfile.setGatewayID(gatewayId);
client.addGatewayComputeResourcePreference(gatewayResourceProfile.getGatewayID(), host.getComputeResourceId(), computeResourcePreference);
return host.getComputeResourceId() + "," + application.getApplicationInterfaceId();
}
private GatewayResourceProfile getGatewayResourceProfile() throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
// if (gatewayResourceProfile==null){
// try {
// gatewayResourceProfile = client.getGatewayResourceProfile(ga);
// } catch (Exception e) {
//
// }
if (gatewayResourceProfile == null) {
gatewayResourceProfile = new GatewayResourceProfile();
// gatewayResourceProfile.setGatewayID("default");
gatewayResourceProfile.setGatewayID(DEFAULT_GATEWAY);
gatewayResourceProfile.setGatewayID(client.registerGatewayResourceProfile(gatewayResourceProfile));
}
// }
return gatewayResourceProfile;
}
public String createSSHHostDocs() throws AppCatalogException, InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription("gw111.iu.xsede.org", null, null);
host.addToIpAddresses("gw111.iu.xsede.org");
host.addToHostAliases("gw111.iu.xsede.org");
host.setResourceDescription("gw111 ssh access");
host.setComputeResourceId(client.registerComputeResource(host));
SSHJobSubmission jobSubmission = new SSHJobSubmission();
jobSubmission.setSshPort(22);
jobSubmission.setSecurityProtocol(SecurityProtocol.SSH_KEYS);
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.FORK, null, null, null);
jobSubmission.setResourceJobManager(resourceJobManager);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, jobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.SSH_KEYS);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
ApplicationModule module = DocumentCreatorUtils.createApplicationModule("echo", "1.1", null);
module.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, module));
ApplicationDeploymentDescription deployment = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), module.getAppModuleId(), "/bin/echo", ApplicationParallelismType.SERIAL, "SSHEchoApplication");
client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment);
ApplicationInterfaceDescription application = new ApplicationInterfaceDescription();
// application.setIsEmpty(false);
application.setApplicationName("SSHEcho1");
application.addToApplicationModules(module.getAppModuleId());
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("echo_input", "echo_input", null, null, DataType.STRING));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("echo_output", null, DataType.STRING));
client.registerApplicationInterface(DEFAULT_GATEWAY, application);
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), "/tmp", null, false, null, null, null));
return host.getComputeResourceId() + "," + application.getApplicationInterfaceId();
}
//
// public void createGramDocs() {
//// /*
//// creating host descriptor for gram
//// */
//// HostDescription host = new HostDescription(GlobusHostType.type);
//// host.getType().setHostAddress(trestleshpcHostAddress);
//// host.getType().setHostName(trestleshpcHostAddress);
//// ((GlobusHostType) host.getType()).setGlobusGateKeeperEndPointArray(new String[]{gramAddress});
//// ((GlobusHostType) host.getType()).setGridFTPEndPointArray(new String[]{gridftpAddress});
//// try {
//// airavataAPI.getApplicationManager().saveHostDescription(host);
//// } catch (AiravataAPIInvocationException e) {
//// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
//// }
////
////
//// /*
//// * Service Description creation and saving
//// */
//// String serviceName = "SimpleEcho1";
//// ServiceDescription serv = new ServiceDescription();
//// serv.getType().setName(serviceName);
////
//// List<InputParameterType> inputList = new ArrayList<InputParameterType>();
//// List<OutputParameterType> outputList = new ArrayList<OutputParameterType>();
////
//// InputParameterType input = InputParameterType.Factory.newInstance();
//// input.setParameterName("echo_input");
//// ParameterType parameterType = input.addNewParameterType();
//// parameterType.setType(DataType.STRING);
//// parameterType.setName("String");
////
//// OutputParameterType output = OutputParameterType.Factory.newInstance();
//// output.setParameterName("echo_output");
//// ParameterType parameterType1 = output.addNewParameterType();
//// parameterType1.setType(DataType.STRING);
//// parameterType1.setName("String");
////
//// inputList.add(input);
//// outputList.add(output);
////
//// InputParameterType[] inputParamList = inputList.toArray(new InputParameterType[inputList.size()]);
//// OutputParameterType[] outputParamList = outputList.toArray(new OutputParameterType[outputList.size()]);
////
//// serv.getType().setInputParametersArray(inputParamList);
//// serv.getType().setOutputParametersArray(outputParamList);
//// try {
//// airavataAPI.getApplicationManager().saveServiceDescription(serv);
//// } catch (AiravataAPIInvocationException e) {
//// e.printStackTrace();
//// }
////
//// /*
//// Application descriptor creation and saving
//// */
//// ApplicationDescription appDesc = new ApplicationDescription(HpcApplicationDeploymentType.type);
//// HpcApplicationDeploymentType app = (HpcApplicationDeploymentType) appDesc.getType();
//// ApplicationDeploymentDescriptionType.ApplicationName name = ApplicationDeploymentDescriptionType.ApplicationName.Factory.newInstance();
//// name.setStringValue("EchoLocal");
//// app.setApplicationName(name);
//// ProjectAccountType projectAccountType = app.addNewProjectAccount();
//// projectAccountType.setProjectAccountNumber("sds128");
////
//// QueueType queueType = app.addNewQueue();
//// queueType.setQueueName("normal");
////
//// app.setCpuCount(1);
//// app.setJobType(JobTypeType.SERIAL);
//// app.setNodeCount(1);
//// app.setProcessorsPerNode(1);
////
//// /*
//// * Use bat file if it is compiled on Windows
//// */
//// app.setExecutableLocation("/bin/echo");
////
//// /*
//// * Default tmp location
//// */
//// String tempDir = "/home/ogce/scratch";
//// app.setScratchWorkingDirectory(tempDir);
//// app.setMaxMemory(10);
////
////
//// try {
//// airavataAPI.getApplicationManager().saveApplicationDescription(serviceName, trestleshpcHostAddress, appDesc);
//// } catch (AiravataAPIInvocationException e) {
//// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
//// }
// }
//
public String createPBSDocsForOGCE_Echo() throws AppCatalogException, InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription(trestleshpcHostAddress, null, null);
host.addToIpAddresses(trestleshpcHostAddress);
host.addToHostAliases(trestleshpcHostAddress);
host.setComputeResourceId(client.registerComputeResource(host));
SSHJobSubmission sshJobSubmission = new SSHJobSubmission();
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.PBS, "/opt/torque/bin/", null, null);
sshJobSubmission.setResourceJobManager(resourceJobManager);
sshJobSubmission.setSecurityProtocol(SecurityProtocol.GSI);
sshJobSubmission.setSshPort(22);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, sshJobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.GSI);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
ApplicationModule module1 = DocumentCreatorUtils.createApplicationModule("echo", "1.2", null);
module1.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, module1));
ApplicationInterfaceDescription application = new ApplicationInterfaceDescription();
// application.setIsEmpty(false);
application.setApplicationName("SimpleEcho2");
application.addToApplicationModules(module1.getAppModuleId());
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("echo_input", "echo_input", "echo_input", null, DataType.STRING));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("echo_output", null, DataType.STRING));
application.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application));
ApplicationDeploymentDescription deployment = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), module1.getAppModuleId(), "/home/ogce/echo.sh", ApplicationParallelismType.SERIAL, "Echo application");
deployment.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment));
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), "/oasis/scratch/trestles/ogce/temp_project/", "sds128", false, null, null, null));
return host.getComputeResourceId() + "," + application.getApplicationInterfaceId();
}
public String createPBSDocsForOGCE_WRF() throws AppCatalogException, InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription(trestleshpcHostAddress, null, null);
host.addToIpAddresses(trestleshpcHostAddress);
host.addToHostAliases(trestleshpcHostAddress);
host.setComputeResourceId(client.registerComputeResource(host));
SSHJobSubmission sshJobSubmission = new SSHJobSubmission();
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.PBS, "/opt/torque/bin/", null, null);
sshJobSubmission.setResourceJobManager(resourceJobManager);
sshJobSubmission.setSecurityProtocol(SecurityProtocol.GSI);
sshJobSubmission.setSshPort(22);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, sshJobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.GSI);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), "/oasis/scratch/trestles/ogce/temp_project/", "sds128", false, null, null, null));
ApplicationModule module2 = DocumentCreatorUtils.createApplicationModule("wrf", "1.0.0", null);
module2.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, module2));
ApplicationInterfaceDescription application2 = new ApplicationInterfaceDescription();
// application2.setIsEmpty(false);
application2.setApplicationName("WRF");
application2.addToApplicationModules(module2.getAppModuleId());
application2.addToApplicationInputs(DocumentCreatorUtils.createAppInput("WRF_Namelist", "WRF_Namelist", null, null, DataType.URI));
application2.addToApplicationInputs(DocumentCreatorUtils.createAppInput("WRF_Boundary_File", "WRF_Boundary_File", null, null, DataType.URI));
application2.addToApplicationInputs(DocumentCreatorUtils.createAppInput("WRF_Input_File", "WRF_Input_File", null, null, DataType.URI));
application2.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("WRF_Output", null, DataType.URI));
application2.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("WRF_Execution_Log", null, DataType.URI));
application2.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application2));
ApplicationDeploymentDescription deployment2 = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), module2.getAppModuleId(), "/home/ogce/production/app_wrappers/wrf_wrapper.sh", ApplicationParallelismType.MPI, "WRF");
deployment2.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment2));
return host.getComputeResourceId() + "," + application2.getApplicationInterfaceId();
}
public String createSlumWRFDocs() throws AppCatalogException, TException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription(stampedeHostAddress, null, null);
host.addToHostAliases(stampedeHostAddress);
host.addToIpAddresses(stampedeHostAddress);
host.setComputeResourceId(client.registerComputeResource(host));
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.SLURM, "/usr/bin/", null, "push");
SSHJobSubmission sshJobSubmission = new SSHJobSubmission();
sshJobSubmission.setResourceJobManager(resourceJobManager);
sshJobSubmission.setSecurityProtocol(SecurityProtocol.GSI);
sshJobSubmission.setSshPort(2222);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, sshJobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.GSI);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), "/home1/01437/ogce", "TG-STA110014S", false, null, null, null));
ApplicationModule module2 = DocumentCreatorUtils.createApplicationModule("wrf", "1.0.0", null);
module2.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, module2));
ApplicationInterfaceDescription application2 = new ApplicationInterfaceDescription();
// application2.setIsEmpty(false);
application2.setApplicationName("WRF");
application2.addToApplicationModules(module2.getAppModuleId());
application2.addToApplicationInputs(DocumentCreatorUtils.createAppInput("WRF_Namelist", "WRF_Namelist", null, null, DataType.URI));
application2.addToApplicationInputs(DocumentCreatorUtils.createAppInput("WRF_Boundary_File", "WRF_Boundary_File", null, null, DataType.URI));
application2.addToApplicationInputs(DocumentCreatorUtils.createAppInput("WRF_Input_File", "WRF_Input_File", null, null, DataType.URI));
application2.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("WRF_Output", null, DataType.URI));
application2.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("WRF_Execution_Log", null, DataType.URI));
application2.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application2));
ApplicationDeploymentDescription deployment2 = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), module2.getAppModuleId(), "/home1/01437/ogce/production/app_wrappers/wrf_wrapper.sh", ApplicationParallelismType.MPI, "WRF");
deployment2.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment2));
return host.getComputeResourceId() + "," + application2.getApplicationInterfaceId();
}
public String createSlurmDocs() throws AppCatalogException, InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription(stampedeHostAddress, null, null);
host.addToHostAliases(stampedeHostAddress);
host.addToIpAddresses(stampedeHostAddress);
host.setComputeResourceId(client.registerComputeResource(host));
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.SLURM, "/usr/bin/", null, "push");
SSHJobSubmission sshJobSubmission = new SSHJobSubmission();
sshJobSubmission.setResourceJobManager(resourceJobManager);
sshJobSubmission.setSecurityProtocol(SecurityProtocol.GSI);
sshJobSubmission.setSshPort(2222);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, sshJobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.GSI);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
ApplicationModule module = DocumentCreatorUtils.createApplicationModule("echo", "1.3", null);
module.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, module));
ApplicationInterfaceDescription application = new ApplicationInterfaceDescription();
// application.setIsEmpty(false);
application.setApplicationName("SimpleEcho3");
application.addToApplicationModules(module.getAppModuleId());
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("echo_input", "echo_input", null, null, DataType.STRING));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("echo_output", null, DataType.STRING));
application.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application));
ApplicationDeploymentDescription deployment = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), module.getAppModuleId(), "/bin/echo", ApplicationParallelismType.SERIAL, "EchoLocal");
deployment.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment));
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), "/home1/01437/ogce", "TG-STA110014S", false, null, null, null));
return host.getComputeResourceId() + "," + application.getApplicationInterfaceId();
}
public String createSGEDocs() throws AppCatalogException, InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription(lonestarHostAddress, null, null);
host.addToHostAliases(lonestarHostAddress);
host.addToIpAddresses(lonestarHostAddress);
host.setComputeResourceId(client.registerComputeResource(host));
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.UGE, "/opt/sge6.2/bin/lx24-amd64/", null, null);
SSHJobSubmission sshJobSubmission = new SSHJobSubmission();
sshJobSubmission.setResourceJobManager(resourceJobManager);
sshJobSubmission.setSecurityProtocol(SecurityProtocol.GSI);
sshJobSubmission.setSshPort(22);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, sshJobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.GSI);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
ApplicationModule module = DocumentCreatorUtils.createApplicationModule("echo", "1.4", null);
module.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, module));
ApplicationInterfaceDescription application = new ApplicationInterfaceDescription();
// application.setIsEmpty(false);
application.setApplicationName("SimpleEcho4");
application.addToApplicationModules(module.getAppModuleId());
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("echo_input", "echo_input", null, null, DataType.STRING));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("echo_output", null, DataType.STRING));
application.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application));
ApplicationDeploymentDescription deployment = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), module.getAppModuleId(), "/bin/echo", ApplicationParallelismType.SERIAL, "EchoLocal");
deployment.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment));
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), "/home1/01437/ogce", "TG-STA110014S", false, null, null, null));
return host.getComputeResourceId() + "," + application.getApplicationInterfaceId();
}
// public void createEchoHostDocs() {
// String serviceName = "Echo";
// ServiceDescription serviceDescription = new ServiceDescription();
// List<InputParameterType> inputParameters = new ArrayList<InputParameterType>();
// List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>();
// serviceDescription.getType().setName(serviceName);
// serviceDescription.getType().setDescription("Echo service");
// // Creating input parameters
// InputParameterType parameter = InputParameterType.Factory.newInstance();
// parameter.setParameterName("echo_input");
// parameter.setParameterDescription("echo input");
// ParameterType parameterType = parameter.addNewParameterType();
// parameterType.setType(DataType.STRING);
// parameterType.setName("String");
// inputParameters.add(parameter);
//
// // Creating output parameters
// OutputParameterType outputParameter = OutputParameterType.Factory.newInstance();
// outputParameter.setParameterName("echo_output");
// outputParameter.setParameterDescription("Echo output");
// ParameterType outputParaType = outputParameter.addNewParameterType();
// outputParaType.setType(DataType.STRING);
// outputParaType.setName("String");
// outputParameters.add(outputParameter);
//
// // Setting input and output parameters to serviceDescriptor
// serviceDescription.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[] {}));
// serviceDescription.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[] {}));
//
// try {
// airavataAPI.getApplicationManager().saveServiceDescription(serviceDescription);
// } catch (AiravataAPIInvocationException e) {
// e.printStackTrace(); // To change body of catch statement use File |
// // Settings | File Templates.
// }
// // Localhost
// ApplicationDescription applicationDeploymentDescription = new ApplicationDescription();
// ApplicationDeploymentDescriptionType applicationDeploymentDescriptionType = applicationDeploymentDescription.getType();
// applicationDeploymentDescriptionType.addNewApplicationName().setStringValue(serviceName);
// applicationDeploymentDescriptionType.setExecutableLocation("/bin/echo");
// applicationDeploymentDescriptionType.setScratchWorkingDirectory("/tmp");
//
// try {
// airavataAPI.getApplicationManager().saveApplicationDescription(serviceName, "localhost", applicationDeploymentDescription);
// } catch (AiravataAPIInvocationException e) {
// e.printStackTrace(); // To change body of catch statement use File |
// // Settings | File Templates.
// }
// // Stampede
// /*
// * Application descriptor creation and saving
// */
// ApplicationDescription appDesc1 = new ApplicationDescription(HpcApplicationDeploymentType.type);
// HpcApplicationDeploymentType app1 = (HpcApplicationDeploymentType) appDesc1.getType();
// ApplicationDeploymentDescriptionType.ApplicationName name = ApplicationDeploymentDescriptionType.ApplicationName.Factory.newInstance();
// name.setStringValue(serviceName);
// app1.setApplicationName(name);
// ProjectAccountType projectAccountType = app1.addNewProjectAccount();
// projectAccountType.setProjectAccountNumber("TG-STA110014S");
//
// QueueType queueType = app1.addNewQueue();
// queueType.setQueueName("normal");
//
// app1.setCpuCount(1);
// app1.setJobType(JobTypeType.SERIAL);
// app1.setNodeCount(1);
// app1.setProcessorsPerNode(1);
// app1.setMaxWallTime(10);
// /*
// * Use bat file if it is compiled on Windows
// */
// app1.setExecutableLocation("/bin/echo");
//
// /*
// * Default tmp location
// */
// String tempDir = "/home1/01437/ogce";
//
// app1.setScratchWorkingDirectory(tempDir);
// app1.setInstalledParentPath("/usr/bin/");
//
// try {
// airavataAPI.getApplicationManager().saveApplicationDescription(serviceName, stampedeHostAddress, appDesc1);
// } catch (AiravataAPIInvocationException e) {
// e.printStackTrace(); // To change body of catch statement use File |
// // Settings | File Templates.
// }
// // Trestles
// /*
// * Application descriptor creation and saving
// */
// ApplicationDescription appDesc2 = new ApplicationDescription(HpcApplicationDeploymentType.type);
// HpcApplicationDeploymentType app2 = (HpcApplicationDeploymentType) appDesc2.getType();
// ApplicationDeploymentDescriptionType.ApplicationName name2 = ApplicationDeploymentDescriptionType.ApplicationName.Factory.newInstance();
// name2.setStringValue(serviceName);
// app2.setApplicationName(name);
// ProjectAccountType projectAccountType2 = app2.addNewProjectAccount();
// projectAccountType2.setProjectAccountNumber("sds128");
//
// QueueType queueType2 = app2.addNewQueue();
// queueType2.setQueueName("normal");
//
// app2.setCpuCount(1);
// app2.setJobType(JobTypeType.SERIAL);
// app2.setNodeCount(1);
// app2.setProcessorsPerNode(1);
// app2.setMaxWallTime(10);
// /*
// * Use bat file if it is compiled on Windows
// */
// app2.setExecutableLocation("/bin/echo");
//
// /*
// * Default tmp location
// */
// String tempDir2 = "/home/ogce/scratch";
//
// app2.setScratchWorkingDirectory(tempDir2);
// app2.setInstalledParentPath("/opt/torque/bin/");
//
// try {
// airavataAPI.getApplicationManager().saveApplicationDescription(serviceName, trestleshpcHostAddress, appDesc2);
// } catch (AiravataAPIInvocationException e) {
// e.printStackTrace(); // To change body of catch statement use File |
// // Settings | File Templates.
// }
// // Lonestar
// /*
// * Application descriptor creation and saving
// */
// ApplicationDescription appDesc3 = new ApplicationDescription(HpcApplicationDeploymentType.type);
// HpcApplicationDeploymentType app3 = (HpcApplicationDeploymentType) appDesc3.getType();
// ApplicationDeploymentDescriptionType.ApplicationName name3 = ApplicationDeploymentDescriptionType.ApplicationName.Factory.newInstance();
// name3.setStringValue(serviceName);
// app3.setApplicationName(name);
// ProjectAccountType projectAccountType3 = app3.addNewProjectAccount();
// projectAccountType3.setProjectAccountNumber("TG-STA110014S");
//
// QueueType queueType3 = app3.addNewQueue();
// queueType3.setQueueName("normal");
//
// app3.setCpuCount(1);
// app3.setJobType(JobTypeType.SERIAL);
// app3.setNodeCount(1);
// app3.setProcessorsPerNode(1);
// app3.setMaxWallTime(10);
// /*
// * Use bat file if it is compiled on Windows
// */
// app3.setExecutableLocation("/bin/echo");
//
// /*
// * Default tmp location
// */
// String tempDir3 = "/home1/01437/ogce";
//
// app3.setScratchWorkingDirectory(tempDir3);
// app3.setInstalledParentPath("/opt/sge6.2/bin/lx24-amd64/");
//
// try {
// airavataAPI.getApplicationManager().saveApplicationDescription(serviceName, lonestarHostAddress, appDesc3);
// } catch (AiravataAPIInvocationException e) {
// e.printStackTrace(); // To change body of catch statement use File |
// // Settings | File Templates.
// }
//
// }
public String createBigRedDocs() throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException, AppCatalogException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription("bigred2", null, null);
host.addToHostAliases(bigRed2HostAddress);
host.addToIpAddresses(bigRed2HostAddress);
host.setComputeResourceId(client.registerComputeResource(host));
Map<JobManagerCommand, String> commands = new HashMap<JobManagerCommand, String>();
commands.put(JobManagerCommand.SUBMISSION, "aprun -n");
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.UGE, "/opt/torque/torque-4.2.3.1/bin/", commands, null);
SSHJobSubmission sshJobSubmission = new SSHJobSubmission();
sshJobSubmission.setResourceJobManager(resourceJobManager);
sshJobSubmission.setSecurityProtocol(SecurityProtocol.SSH_KEYS);
sshJobSubmission.setSshPort(22);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, sshJobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.SSH_KEYS);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
ApplicationModule module = DocumentCreatorUtils.createApplicationModule("echo", "1.5", null);
module.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, module));
ApplicationInterfaceDescription application = new ApplicationInterfaceDescription();
application.setApplicationName("SimpleEchoBR");
application.addToApplicationModules(module.getAppModuleId());
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("echo_input", "echo_input", null, null, DataType.STRING));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("echo_output", null, DataType.STRING));
application.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application));
ApplicationDeploymentDescription deployment = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), module.getAppModuleId(), "/N/u/lginnali/BigRed2/myjob/test.sh", ApplicationParallelismType.SERIAL, "EchoLocal");
deployment.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment));
String date = (new Date()).toString();
date = date.replaceAll(" ", "_");
date = date.replaceAll(":", "_");
String tempDir = "/N/u/lginnali/BigRed2/myjob";
tempDir = tempDir + File.separator + "SimpleEcho" + "_" + date + "_" + UUID.randomUUID();
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), tempDir, "TG-STA110014S", false, null, null, null));
return host.getComputeResourceId() + "," + application.getApplicationInterfaceId();
}
public String createBigRedAmberDocs() throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException, AppCatalogException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription("bigred2", null, null);
host.addToHostAliases(bigRed2HostAddress);
host.addToIpAddresses(bigRed2HostAddress);
host.setComputeResourceId(client.registerComputeResource(host));
Map<JobManagerCommand, String> commands = new HashMap<JobManagerCommand, String>();
commands.put(JobManagerCommand.SUBMISSION, "aprun -n 4");
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.UGE, "/opt/torque/torque-4.2.3.1/bin/", commands, null);
SSHJobSubmission sshJobSubmission = new SSHJobSubmission();
sshJobSubmission.setResourceJobManager(resourceJobManager);
sshJobSubmission.setSecurityProtocol(SecurityProtocol.SSH_KEYS);
sshJobSubmission.setSshPort(22);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, sshJobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.SSH_KEYS);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
ApplicationModule amodule = DocumentCreatorUtils.createApplicationModule("Amber", "12.0", null);
amodule.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, amodule));
ApplicationInterfaceDescription application = new ApplicationInterfaceDescription();
application.setApplicationName("AmberBR2");
application.addToApplicationModules(amodule.getAppModuleId());
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("AMBER_HEAT_RST", "AMBER_HEAT_RST", null, null, DataType.URI));
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("AMBER_PROD_IN", "AMBER_PROD_IN", null, null, DataType.URI));
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("AMBER_PRMTOP", "AMBER_PRMTOP", null, null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.info", null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.mdcrd", null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.out", null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.rst", null, DataType.URI));
application.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application));
ApplicationDeploymentDescription deployment = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), amodule.getAppModuleId(), "/N/u/cgateway/BigRed2/sandbox/amber_wrapper.sh", ApplicationParallelismType.SERIAL, "AmberBR2");
deployment.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment));
String date = (new Date()).toString();
date = date.replaceAll(" ", "_");
date = date.replaceAll(":", "_");
String tempDir = "/N/u/cgateway/BigRed2/sandbox/jobs";
tempDir = tempDir + File.separator +
"Amber";
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), tempDir, null, false, null, null, null));
return host.getComputeResourceId() + "," + application.getApplicationInterfaceId();
}
public String createStampedeAmberDocs() throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException, AppCatalogException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription(stampedeHostAddress, null, null);
host.addToHostAliases(stampedeHostAddress);
host.addToIpAddresses(stampedeHostAddress);
host.setComputeResourceId(client.registerComputeResource(host));
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.SLURM, "/usr/bin/", null, "push");
SSHJobSubmission sshJobSubmission = new SSHJobSubmission();
sshJobSubmission.setResourceJobManager(resourceJobManager);
sshJobSubmission.setSecurityProtocol(SecurityProtocol.GSI);
sshJobSubmission.setSshPort(2222);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, sshJobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.GSI);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
ApplicationModule amodule = DocumentCreatorUtils.createApplicationModule("Amber", "12.0", null);
amodule.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, amodule));
ApplicationInterfaceDescription application = new ApplicationInterfaceDescription();
application.setApplicationName("AmberBR2");
application.addToApplicationModules(amodule.getAppModuleId());
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("AMBER_HEAT_RST", "AMBER_HEAT_RST", null, null, DataType.URI));
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("AMBER_PROD_IN", "AMBER_PROD_IN", null, null, DataType.URI));
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("AMBER_PRMTOP", "AMBER_PRMTOP", null, null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.info", null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.mdcrd", null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.out", null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.rst", null, DataType.URI));
application.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application));
ApplicationDeploymentDescription deployment = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), amodule.getAppModuleId(), "/home1/01437/ogce/production/app_wrappers/amber_wrapper.sh", ApplicationParallelismType.SERIAL, "AmberStampede");
deployment.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment));
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), "/home1/01437/ogce", "TG-STA110014S", false, null, null, null));
return host.getComputeResourceId() + "," + application.getApplicationInterfaceId();
}
public String createTrestlesAmberDocs() throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException, AppCatalogException {
ComputeResourceDescription host = DocumentCreatorUtils.createComputeResourceDescription(trestleshpcHostAddress, null, null);
host.addToIpAddresses(trestleshpcHostAddress);
host.addToHostAliases(trestleshpcHostAddress);
host.setComputeResourceId(client.registerComputeResource(host));
SSHJobSubmission sshJobSubmission = new SSHJobSubmission();
ResourceJobManager resourceJobManager = DocumentCreatorUtils.createResourceJobManager(ResourceJobManagerType.PBS, "/opt/torque/bin/", null, null);
sshJobSubmission.setResourceJobManager(resourceJobManager);
sshJobSubmission.setSecurityProtocol(SecurityProtocol.GSI);
sshJobSubmission.setSshPort(22);
client.addSSHJobSubmissionDetails(host.getComputeResourceId(), 1, sshJobSubmission);
SCPDataMovement scpDataMovement = new SCPDataMovement();
scpDataMovement.setSecurityProtocol(SecurityProtocol.GSI);
scpDataMovement.setSshPort(22);
client.addSCPDataMovementDetails(host.getComputeResourceId(), 1, scpDataMovement);
ApplicationModule amodule = DocumentCreatorUtils.createApplicationModule("Amber", "12.0", null);
amodule.setAppModuleId(client.registerApplicationModule(DEFAULT_GATEWAY, amodule));
ApplicationInterfaceDescription application = new ApplicationInterfaceDescription();
application.setApplicationName("AmberTrestles");
application.addToApplicationModules(amodule.getAppModuleId());
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("AMBER_HEAT_RST", "AMBER_HEAT_RST", null, null, DataType.URI));
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("AMBER_PROD_IN", "AMBER_PROD_IN", null, null, DataType.URI));
application.addToApplicationInputs(DocumentCreatorUtils.createAppInput("AMBER_PRMTOP", "AMBER_PRMTOP", null, null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.info", null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.mdcrd", null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.out", null, DataType.URI));
application.addToApplicationOutputs(DocumentCreatorUtils.createAppOutput("AMBER_Prod.rst", null, DataType.URI));
application.setApplicationInterfaceId(client.registerApplicationInterface(DEFAULT_GATEWAY, application));
ApplicationDeploymentDescription deployment = DocumentCreatorUtils.createApplicationDeployment(host.getComputeResourceId(), amodule.getAppModuleId(), "/home/ogce/production/app_wrappers/amber_wrapper.sh", ApplicationParallelismType.SERIAL, "AmberStampede");
deployment.setAppDeploymentId(client.registerApplicationDeployment(DEFAULT_GATEWAY, deployment));
client.addGatewayComputeResourcePreference(getGatewayResourceProfile().getGatewayID(), host.getComputeResourceId(), DocumentCreatorUtils.createComputeResourcePreference(host.getComputeResourceId(), "/oasis/scratch/trestles/ogce/temp_project/", "sds128", false, null, null, null));
return host.getComputeResourceId() + "," + application.getApplicationInterfaceId();
}
}
| apache-2.0 |
MaTriXy/android-db-commons | library/src/main/java/com/getbase/android/db/provider/ConvertibleToOperation.java | 316 | package com.getbase.android.db.provider;
import android.content.ContentProviderOperation;
public interface ConvertibleToOperation {
ContentProviderOperation.Builder toContentProviderOperationBuilder(UriDecorator uriDecorator);
ContentProviderOperation toContentProviderOperation(UriDecorator uriDecorator);
}
| apache-2.0 |
apache/npanday | components/dotnet-executable/src/main/java/npanday/executable/compiler/InvalidArtifactException.java | 2278 | package npanday.executable.compiler;
/*
* 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 npanday.executable.ExecutionException;
/**
* Exception thrown when the framework either does not recognize the target artifact (module, library, exe, winexe) or
* the target artifact is not valid for the compiler.
*
* @author Shane Isbell
*/
public class InvalidArtifactException
extends ExecutionException
{
static final long serialVersionUID = -3214341783478731432L;
/**
* Constructs an <code>InvalidArtifactException</code> with no exception message.
*/
public InvalidArtifactException()
{
super();
}
/**
* Constructs an <code>InvalidArtifactException</code> with the specified exception message.
*
* @param message the exception message
*/
public InvalidArtifactException( String message )
{
super( message );
}
/**
* Constructs an <code>InvalidArtifactException</code> with the specified exception message and cause of the exception.
*
* @param message the exception message
* @param cause the cause of the exception
*/
public InvalidArtifactException( String message, Throwable cause )
{
super( message, cause );
}
/**
* Constructs an <code>InvalidArtifactException</code> with the cause of the exception.
*
* @param cause the cause of the exception
*/
public InvalidArtifactException( Throwable cause )
{
super( cause );
}
}
| apache-2.0 |
Carbonado/Carbonado | src/main/java/com/amazon/carbonado/capability/RemoteProcedure.java | 8703 | /*
* Copyright 2010-2012 Amazon Technologies, Inc. or its affiliates.
* Amazon, Amazon.com and Carbonado are trademarks or registered trademarks
* of Amazon Technologies, Inc. or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.amazon.carbonado.capability;
import java.io.Serializable;
import java.util.Collection;
import com.amazon.carbonado.Cursor;
import com.amazon.carbonado.Repository;
import com.amazon.carbonado.RepositoryException;
/**
* Defines a remote procedure which can be executed by {@link
* RemoteProcedureCapability}. Any data within the procedure instance is
* serialized to the remote host, and possibly the class definition
* too. Execution might have security restrictions applied.
*
* <p>The RemoteProcedure instance is Serializable, and so any serializable
* parameters can be passed with it. Storables and extra data can be sent
* through the {@link Request} object. Any data returned by procedure
* implementation must be sent through the {@link Reply} object.
*
* @param <R> reply object type
* @param <D> request data object type
* @author Brian S O'Neill
*/
public interface RemoteProcedure<R, D> extends Serializable {
/**
* Request handler for remote procedure implementation.
*
* @param repo repository as seen by host that procedure is running from
* @param request non-null request object
* @return false if request is still active when this method returns;
* request must eventually be explicitly finished
*/
boolean handleRequest(Repository repo, Request<R, D> request) throws RepositoryException;
/**
* Client-side call into a remote procedure. To avoid leaking resources,
* the finish method must be invoked or all reply data be fully read. If an
* exception is thrown by a method defined in this interface, resources are
* automatically released.
*
* @param <R> reply object type
* @param <D> request data object type
* @see RemoteProcedureCapability#beginCall
*/
public static interface Call<R, D> {
/**
* Send data to the remote procedure.
*
* @return this Call instance
* @throws IllegalArgumentException if data is null
* @throws IllegalStateException if a call has been executed
*/
Call<R, D> send(D data) throws RepositoryException;
/**
* Send all data from the given iterable to the remote procedure.
*
* @return this Call instance
* @throws IllegalArgumentException if data is null
* @throws IllegalStateException if a call has been executed
*/
Call<R, D> sendAll(Iterable<? extends D> iterable) throws RepositoryException;
/**
* Send all data from the given cursor to the remote procedure.
*
* @return this Call instance
* @throws IllegalArgumentException if data is null
* @throws IllegalStateException if a call has been executed
*/
Call<R, D> sendAll(Cursor<? extends D> cursor) throws RepositoryException;
/**
* Reset the internal object stream of the call, allowing cached
* objects to get freed.
*
* @return this Call instance
* @throws IllegalStateException if a call has been executed
*/
Call<R, D> reset() throws RepositoryException;
/**
* Flushes all the data sent so far. Flush is invoked automatically
* when call is executed.
*/
void flush() throws RepositoryException;
/**
* Executes the call and receive a reply. Calling this method does not
* block, but methods on the returned Cursor may block waiting for
* data.
*
* @throws IllegalStateException if a call has been executed
*/
Cursor<R> fetchReply() throws RepositoryException;
/**
* Executes the call without expecting a reply. Method blocks waiting
* for procedure to finish.
*
* @throws IllegalStateException if a call has been executed
*/
void execute() throws RepositoryException;
/**
* Executes the call without expecting a reply. Method does not block
* waiting for procedure to finish. Asynchronous execution is not
* allowed if the current thread is in a transaction. This is because
* transaction ownership becomes ambiguous.
*
* @throws IllegalStateException if a call has been executed or if
* current thread is in a transaction
*/
void executeAsync() throws RepositoryException;
}
/**
* Request into a remote procedure, as seen by procedure implementation. To
* avoid leaking resources, the request or reply object must always be
* finished. If an exception is thrown by a method defined in this
* interface, resources are automatically released.
*
* @param <R> reply object type
* @param <D> request data object type
*/
public static interface Request<R, D> {
/**
* Receive data from caller.
*
* @return null if no more data
*/
D receive() throws RepositoryException;
/**
* Receive all remaining data from caller.
*
* @param c collection to receive data
* @return amount received
*/
int receiveInto(Collection<? super D> c) throws RepositoryException;
/**
* Begin a reply after receiving all data. If no data is expected,
* reply can be made without calling receive.
*
* @throws IllegalStateException if reply was already begun, or if
* request is finished, or if more data must be received
*/
Reply<R> beginReply() throws RepositoryException;
/**
* Reply and immediately finish, without sending any data to caller.
*
* @throws IllegalStateException if a reply was already begun or if
* more data must be received
*/
void finish() throws RepositoryException;
}
/**
* Reply from remote procedure implementation. To avoid leaking resources,
* the finish method must always be invoked. If an exception is thrown by a
* method defined in this interface, resources are automatically released.
*
* @param <R> reply object type
*/
public static interface Reply<R> {
/**
* Send reply data to the caller.
*
* @return this Reply instance
* @throws IllegalStateException if reply is finished
*/
Reply<R> send(R data) throws RepositoryException;
/**
* Reply with all data from the given iterable to the caller.
*
* @return this Reply instance
* @throws IllegalStateException if reply is finished
*/
Reply<R> sendAll(Iterable<? extends R> iterable) throws RepositoryException;
/**
* Reply with all data from the given cursor to the caller.
*
* @return this Reply instance
* @throws IllegalStateException if reply is finished
*/
Reply<R> sendAll(Cursor<? extends R> cursor) throws RepositoryException;
/**
* Reset the internal object stream of the reply, allowing cached
* objects to get freed.
*
* @return this Reply instance
* @throws IllegalStateException if reply is finished
*/
Reply<R> reset() throws RepositoryException;
/**
* Flushes all the data sent so far. Flush is invoked automatically
* when reply is finished.
*/
void flush() throws RepositoryException;
/**
* Finish the reply.
*/
void finish() throws RepositoryException;
}
}
| apache-2.0 |
gocd/gocd | common/src/main/java/com/thoughtworks/go/config/UpdateConfigCommand.java | 749 | /*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.config;
public interface UpdateConfigCommand {
CruiseConfig update(CruiseConfig cruiseConfig) throws Exception;
}
| apache-2.0 |
GJL/flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/utils/LogicalTypeCasts.java | 19100 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.types.logical.utils;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.types.logical.DateType;
import org.apache.flink.table.types.logical.DistinctType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.LogicalTypeFamily;
import org.apache.flink.table.types.logical.LogicalTypeRoot;
import org.apache.flink.table.types.logical.StructuredType;
import org.apache.flink.table.types.logical.VarBinaryType;
import org.apache.flink.table.types.logical.VarCharType;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.BINARY_STRING;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.CHARACTER_STRING;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.CONSTRUCTED;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.DATETIME;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.EXACT_NUMERIC;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.INTERVAL;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.NUMERIC;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.PREDEFINED;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.TIME;
import static org.apache.flink.table.types.logical.LogicalTypeFamily.TIMESTAMP;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.BIGINT;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.BINARY;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.BOOLEAN;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.CHAR;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.DATE;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.DECIMAL;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.DISTINCT_TYPE;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.DOUBLE;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.FLOAT;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.INTEGER;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.INTERVAL_DAY_TIME;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.INTERVAL_YEAR_MONTH;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.NULL;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.RAW;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.SMALLINT;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.STRUCTURED_TYPE;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.SYMBOL;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.TIMESTAMP_WITH_TIME_ZONE;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.TINYINT;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.VARBINARY;
import static org.apache.flink.table.types.logical.LogicalTypeRoot.VARCHAR;
import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.getLength;
import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.hasFamily;
import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.hasRoot;
import static org.apache.flink.table.types.logical.utils.LogicalTypeChecks.isSingleFieldInterval;
/**
* Utilities for casting {@link LogicalType}.
*
* <p>This class aims to be compatible with the SQL standard. It is inspired by Apache Calcite's
* {@code SqlTypeUtil#canCastFrom} method.
*
* <p>Casts can be performed in two ways: implicit or explicit.
*
* <p>Explicit casts correspond to the SQL cast specification and represent the logic behind a
* {@code CAST(sourceType AS targetType)} operation. For example, it allows for converting most types
* of the {@link LogicalTypeFamily#PREDEFINED} family to types of the {@link LogicalTypeFamily#CHARACTER_STRING}
* family.
*
* <p>Implicit casts are used for safe type widening and type generalization (finding a common supertype
* for a set of types) without loss of information. Implicit casts are similar to the Java semantics
* (e.g. this is not possible: {@code int x = (String) z}).
*
* <p>Conversions that are defined by the {@link LogicalType} (e.g. interpreting a {@link DateType}
* as integer value) are not considered here. They are an internal bridging feature that is not
* standard compliant. If at all, {@code CONVERT} methods should make such conversions available.
*/
@Internal
public final class LogicalTypeCasts {
private static final Map<LogicalTypeRoot, Set<LogicalTypeRoot>> implicitCastingRules;
private static final Map<LogicalTypeRoot, Set<LogicalTypeRoot>> explicitCastingRules;
static {
implicitCastingRules = new HashMap<>();
explicitCastingRules = new HashMap<>();
// identity casts
for (LogicalTypeRoot typeRoot : allTypes()) {
castTo(typeRoot)
.implicitFrom(typeRoot)
.build();
}
// cast specification
castTo(CHAR)
.implicitFrom(CHAR)
.explicitFromFamily(PREDEFINED)
.explicitNotFromFamily(BINARY_STRING)
.build();
castTo(VARCHAR)
.implicitFromFamily(CHARACTER_STRING)
.explicitFromFamily(PREDEFINED)
.explicitNotFromFamily(BINARY_STRING)
.build();
castTo(BOOLEAN)
.implicitFrom(BOOLEAN)
.explicitFromFamily(CHARACTER_STRING)
.build();
castTo(BINARY)
.implicitFrom(BINARY)
.build();
castTo(VARBINARY)
.implicitFromFamily(BINARY_STRING)
.build();
castTo(DECIMAL)
.implicitFromFamily(NUMERIC)
.explicitFromFamily(CHARACTER_STRING)
.build();
castTo(TINYINT)
.implicitFrom(TINYINT)
.explicitFromFamily(NUMERIC, CHARACTER_STRING)
.build();
castTo(SMALLINT)
.implicitFrom(TINYINT, SMALLINT)
.explicitFromFamily(NUMERIC, CHARACTER_STRING)
.build();
castTo(INTEGER)
.implicitFrom(TINYINT, SMALLINT, INTEGER)
.explicitFromFamily(NUMERIC, CHARACTER_STRING)
.build();
castTo(BIGINT)
.implicitFrom(TINYINT, SMALLINT, INTEGER, BIGINT)
.explicitFromFamily(NUMERIC, CHARACTER_STRING)
.build();
castTo(FLOAT)
.implicitFrom(TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, DECIMAL)
.explicitFromFamily(NUMERIC, CHARACTER_STRING)
.build();
castTo(DOUBLE)
.implicitFromFamily(NUMERIC)
.explicitFromFamily(CHARACTER_STRING)
.build();
castTo(DATE)
.implicitFrom(DATE, TIMESTAMP_WITHOUT_TIME_ZONE)
.explicitFromFamily(TIMESTAMP, CHARACTER_STRING)
.build();
castTo(TIME_WITHOUT_TIME_ZONE)
.implicitFrom(TIME_WITHOUT_TIME_ZONE, TIMESTAMP_WITHOUT_TIME_ZONE)
.explicitFromFamily(TIME, TIMESTAMP, CHARACTER_STRING)
.build();
castTo(TIMESTAMP_WITHOUT_TIME_ZONE)
.implicitFrom(TIMESTAMP_WITHOUT_TIME_ZONE)
.explicitFromFamily(DATETIME, CHARACTER_STRING)
.build();
castTo(TIMESTAMP_WITH_TIME_ZONE)
.implicitFrom(TIMESTAMP_WITH_TIME_ZONE)
.explicitFromFamily(DATETIME, CHARACTER_STRING)
.build();
castTo(TIMESTAMP_WITH_LOCAL_TIME_ZONE)
.implicitFrom(TIMESTAMP_WITH_LOCAL_TIME_ZONE)
.explicitFromFamily(DATETIME, CHARACTER_STRING)
.build();
castTo(INTERVAL_YEAR_MONTH)
.implicitFrom(INTERVAL_YEAR_MONTH)
.explicitFromFamily(EXACT_NUMERIC, CHARACTER_STRING)
.build();
castTo(INTERVAL_DAY_TIME)
.implicitFrom(INTERVAL_DAY_TIME)
.explicitFromFamily(EXACT_NUMERIC, CHARACTER_STRING)
.build();
}
/**
* Returns whether the source type can be safely interpreted as the target type. This allows avoiding
* casts by ignoring some logical properties. This is basically a relaxed {@link LogicalType#equals(Object)}.
*
* <p>In particular this means:
*
* <p>Atomic, non-string types (INT, BOOLEAN, ...) and user-defined structured types must be fully
* equal (i.e. {@link LogicalType#equals(Object)}). However, a NOT NULL type can be stored in NULL
* type but not vice versa.
*
* <p>Atomic, string types must be contained in the target type (e.g. CHAR(2) is contained in VARCHAR(3),
* but VARCHAR(2) is not contained in CHAR(3)). Same for binary strings.
*
* <p>Constructed types (ARRAY, ROW, MAP, etc.) and user-defined distinct type must be of same kind
* but ignore field names and other logical attributes. However, all the children types
* ({@link LogicalType#getChildren()}) must be compatible.
*/
public static boolean supportsAvoidingCast(LogicalType sourceType, LogicalType targetType) {
final CastAvoidanceChecker checker = new CastAvoidanceChecker(sourceType);
return targetType.accept(checker);
}
/**
* See {@link #supportsAvoidingCast(LogicalType, LogicalType)}.
*/
public static boolean supportsAvoidingCast(List<LogicalType> sourceTypes, List<LogicalType> targetTypes) {
if (sourceTypes.size() != targetTypes.size()) {
return false;
}
for (int i = 0; i < sourceTypes.size(); i++) {
if (!supportsAvoidingCast(sourceTypes.get(i), targetTypes.get(i))) {
return false;
}
}
return true;
}
/**
* Returns whether the source type can be safely casted to the target type without loosing information.
*
* <p>Implicit casts are used for type widening and type generalization (finding a common supertype
* for a set of types). Implicit casts are similar to the Java semantics (e.g. this is not possible:
* {@code int x = (String) z}).
*/
public static boolean supportsImplicitCast(LogicalType sourceType, LogicalType targetType) {
return supportsCasting(sourceType, targetType, false);
}
/**
* Returns whether the source type can be casted to the target type.
*
* <p>Explicit casts correspond to the SQL cast specification and represent the logic behind a
* {@code CAST(sourceType AS targetType)} operation. For example, it allows for converting most types
* of the {@link LogicalTypeFamily#PREDEFINED} family to types of the {@link LogicalTypeFamily#CHARACTER_STRING}
* family.
*/
public static boolean supportsExplicitCast(LogicalType sourceType, LogicalType targetType) {
return supportsCasting(sourceType, targetType, true);
}
// --------------------------------------------------------------------------------------------
private static boolean supportsCasting(
LogicalType sourceType,
LogicalType targetType,
boolean allowExplicit) {
if (sourceType.isNullable() && !targetType.isNullable()) {
return false;
}
// ignore nullability during compare
if (sourceType.copy(true).equals(targetType.copy(true))) {
return true;
}
final LogicalTypeRoot sourceRoot = sourceType.getTypeRoot();
final LogicalTypeRoot targetRoot = targetType.getTypeRoot();
if (hasFamily(sourceType, INTERVAL) && hasFamily(targetType, EXACT_NUMERIC)) {
// cast between interval and exact numeric is only supported if interval has a single field
return isSingleFieldInterval(sourceType);
} else if (hasFamily(sourceType, EXACT_NUMERIC) && hasFamily(targetType, INTERVAL)) {
// cast between interval and exact numeric is only supported if interval has a single field
return isSingleFieldInterval(targetType);
} else if (hasFamily(sourceType, CONSTRUCTED) || hasFamily(targetType, CONSTRUCTED)) {
return supportsConstructedCasting(sourceType, targetType, allowExplicit);
} else if (sourceRoot == DISTINCT_TYPE && targetRoot == DISTINCT_TYPE) {
// the two distinct types are not equal (from initial invariant), casting is not possible
return false;
} else if (sourceRoot == DISTINCT_TYPE) {
return supportsCasting(((DistinctType) sourceType).getSourceType(), targetType, allowExplicit);
} else if (targetRoot == DISTINCT_TYPE) {
return supportsCasting(sourceType, ((DistinctType) targetType).getSourceType(), allowExplicit);
} else if (sourceRoot == STRUCTURED_TYPE || targetRoot == STRUCTURED_TYPE) {
// inheritance is not supported yet, so structured type must be fully equal
return false;
} else if (sourceRoot == NULL) {
// null can be cast to an arbitrary type
return true;
} else if (sourceRoot == RAW || targetRoot == RAW) {
// the two raw types are not equal (from initial invariant), casting is not possible
return false;
} else if (sourceRoot == SYMBOL || targetRoot == SYMBOL) {
// the two symbol types are not equal (from initial invariant), casting is not possible
return false;
}
if (implicitCastingRules.get(targetRoot).contains(sourceRoot)) {
return true;
}
if (allowExplicit) {
return explicitCastingRules.get(targetRoot).contains(sourceRoot);
}
return false;
}
private static boolean supportsConstructedCasting(
LogicalType sourceType,
LogicalType targetType,
boolean allowExplicit) {
final LogicalTypeRoot sourceRoot = sourceType.getTypeRoot();
final LogicalTypeRoot targetRoot = targetType.getTypeRoot();
// all constructed types can only be casted within the same type root
if (sourceRoot == targetRoot) {
final List<LogicalType> sourceChildren = sourceType.getChildren();
final List<LogicalType> targetChildren = targetType.getChildren();
if (sourceChildren.size() != targetChildren.size()) {
return false;
}
for (int i = 0; i < sourceChildren.size(); i++) {
if (!supportsCasting(sourceChildren.get(i), targetChildren.get(i), allowExplicit)) {
return false;
}
}
return true;
}
return false;
}
private static CastingRuleBuilder castTo(LogicalTypeRoot sourceType) {
return new CastingRuleBuilder(sourceType);
}
private static LogicalTypeRoot[] allTypes() {
return LogicalTypeRoot.values();
}
private static class CastingRuleBuilder {
private final LogicalTypeRoot targetType;
private Set<LogicalTypeRoot> implicitSourceTypes = new HashSet<>();
private Set<LogicalTypeRoot> explicitSourceTypes = new HashSet<>();
CastingRuleBuilder(LogicalTypeRoot targetType) {
this.targetType = targetType;
}
CastingRuleBuilder implicitFrom(LogicalTypeRoot... sourceTypes) {
this.implicitSourceTypes.addAll(Arrays.asList(sourceTypes));
return this;
}
CastingRuleBuilder implicitFromFamily(LogicalTypeFamily... sourceFamilies) {
for (LogicalTypeFamily family : sourceFamilies) {
for (LogicalTypeRoot root : LogicalTypeRoot.values()) {
if (root.getFamilies().contains(family)) {
this.implicitSourceTypes.add(root);
}
}
}
return this;
}
CastingRuleBuilder explicitFrom(LogicalTypeRoot... sourceTypes) {
this.explicitSourceTypes.addAll(Arrays.asList(sourceTypes));
return this;
}
CastingRuleBuilder explicitFromFamily(LogicalTypeFamily... sourceFamilies) {
for (LogicalTypeFamily family : sourceFamilies) {
for (LogicalTypeRoot root : LogicalTypeRoot.values()) {
if (root.getFamilies().contains(family)) {
this.explicitSourceTypes.add(root);
}
}
}
return this;
}
/**
* Should be called after {@link #explicitFromFamily(LogicalTypeFamily...)} to remove previously
* added types.
*/
CastingRuleBuilder explicitNotFromFamily(LogicalTypeFamily... sourceFamilies) {
for (LogicalTypeFamily family : sourceFamilies) {
for (LogicalTypeRoot root : LogicalTypeRoot.values()) {
if (root.getFamilies().contains(family)) {
this.explicitSourceTypes.remove(root);
}
}
}
return this;
}
void build() {
implicitCastingRules.put(targetType, implicitSourceTypes);
explicitCastingRules.put(targetType, explicitSourceTypes);
}
}
// --------------------------------------------------------------------------------------------
/**
* Checks if a source type can safely be interpreted as the target type.
*/
private static class CastAvoidanceChecker extends LogicalTypeDefaultVisitor<Boolean> {
private final LogicalType sourceType;
private CastAvoidanceChecker(LogicalType sourceType) {
this.sourceType = sourceType;
}
@Override
public Boolean visit(VarCharType targetType) {
if (sourceType.isNullable() && !targetType.isNullable()) {
return false;
}
// CHAR and VARCHAR are very compatible within bounds
if ((hasRoot(sourceType, LogicalTypeRoot.CHAR) || hasRoot(sourceType, LogicalTypeRoot.VARCHAR)) &&
getLength(sourceType) <= targetType.getLength()) {
return true;
}
return defaultMethod(targetType);
}
@Override
public Boolean visit(VarBinaryType targetType) {
if (sourceType.isNullable() && !targetType.isNullable()) {
return false;
}
// BINARY and VARBINARY are very compatible within bounds
if ((hasRoot(sourceType, LogicalTypeRoot.BINARY) || hasRoot(sourceType, LogicalTypeRoot.VARBINARY)) &&
getLength(sourceType) <= targetType.getLength()) {
return true;
}
return defaultMethod(targetType);
}
@Override
public Boolean visit(StructuredType targetType) {
if (sourceType.isNullable() && !targetType.isNullable()) {
return false;
}
// structured types should be equal (modulo nullability)
return sourceType.equals(targetType) || sourceType.copy(true).equals(targetType);
}
@Override
protected Boolean defaultMethod(LogicalType targetType) {
// quick path
if (sourceType == targetType) {
return true;
}
if (sourceType.isNullable() && !targetType.isNullable() ||
sourceType.getClass() != targetType.getClass() || // TODO drop this line once we remove legacy types
sourceType.getTypeRoot() != targetType.getTypeRoot()) {
return false;
}
final List<LogicalType> sourceChildren = sourceType.getChildren();
final List<LogicalType> targetChildren = targetType.getChildren();
if (sourceChildren.isEmpty()) {
// handles all types that are not of family CONSTRUCTED or USER DEFINED
return sourceType.equals(targetType) || sourceType.copy(true).equals(targetType);
} else {
// handles all types of CONSTRUCTED family as well as distinct types
return supportsAvoidingCast(sourceChildren, targetChildren);
}
}
}
private LogicalTypeCasts() {
// no instantiation
}
}
| apache-2.0 |
p3et/gradoop | gradoop-flink/src/main/java/org/gradoop/flink/model/impl/operators/matching/common/tuples/package-info.java | 792 | /**
* Copyright © 2014 - 2017 Leipzig University (Database Research Group)
*
* 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.
*/
/**
* Contains tuples that are used by all pattern matching implementations.
*/
package org.gradoop.flink.model.impl.operators.matching.common.tuples;
| apache-2.0 |
jgaupp/arx | src/gui/org/deidentifier/arx/gui/view/impl/wizard/ImportWizardModelColumn.java | 2592 | /*
* ARX: Powerful Data Anonymization
* Copyright 2012 - 2017 Fabian Prasser, Florian Kohlmayer and contributors
*
* 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.deidentifier.arx.gui.view.impl.wizard;
import org.deidentifier.arx.io.ImportColumn;
/**
* Wrapper for {@link ImportColumn} used in the wizard context
*
* This is a wrapper for {@link ImportColumn}. It essentially adds an property
* indicating whether a column is enabled {@link #enabled}.
*
* @author Karol Babioch
* @author Fabian Prasser
*/
public class ImportWizardModelColumn {
/**
* Indicates whether the given column is enabled
*
* Columns can be disabled by the user. Once disabled they won't be
* imported.
*/
private boolean enabled = true;
/** The actual column this wraps around. */
private ImportColumn column;
/**
* Creates a new instance for the given column.
*
* @param column Column that should be wrapped around
* @note This implicitly assumes that the column should be enabled.
*/
public ImportWizardModelColumn(ImportColumn column) {
this(column, true);
}
/**
* Creates a new instance for the given column.
*
* @param column Column that should be wrapped around
* @param enabled
*/
public ImportWizardModelColumn(ImportColumn column, boolean enabled) {
setEnabled(enabled);
setColumn(column);
}
/**
* @return {@link #column}
*/
public ImportColumn getColumn() {
return column;
}
/**
* @return {@link #enabled}
*/
public boolean isEnabled() {
return enabled;
}
/**
*
*
* @param column
*/
public void setColumn(ImportColumn column) {
this.column = column;
}
/**
* @param enabled
* {@link #enabled}
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| apache-2.0 |
mdunker/usergrid | stack/services/src/test/java/org/apache/usergrid/corepersistence/migration/AppInfoMigrationPluginTest.java | 9539 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.usergrid.corepersistence.migration;
import com.google.common.base.Optional;
import org.apache.usergrid.NewOrgAppAdminRule;
import org.apache.usergrid.ServiceITSetup;
import org.apache.usergrid.ServiceITSetupImpl;
import org.apache.usergrid.cassandra.ClearShiroSubject;
import org.apache.usergrid.corepersistence.util.CpNamingUtils;
import org.apache.usergrid.management.AppInfoMigrationPlugin;
import org.apache.usergrid.management.ManagementService;
import org.apache.usergrid.management.OrganizationOwnerInfo;
import org.apache.usergrid.persistence.*;
import org.apache.usergrid.persistence.cassandra.CassandraService;
import org.apache.usergrid.persistence.collection.EntityCollectionManagerFactory;
import org.apache.usergrid.persistence.core.migration.data.MigrationInfoSerialization;
import org.apache.usergrid.persistence.core.migration.data.ProgressObserver;
import org.apache.usergrid.persistence.entities.Application;
import org.apache.usergrid.persistence.graph.GraphManagerFactory;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import java.util.*;
import static org.apache.usergrid.TestHelper.*;
import static org.junit.Assert.*;
/**
* Really a Core module test but it needs to be here so that it can use
* ManagementService's application and organization logic.
*/
public class AppInfoMigrationPluginTest {
private static final Logger logger = LoggerFactory.getLogger(AppInfoMigrationPluginTest.class);
@Rule
public ClearShiroSubject clearShiroSubject = new ClearShiroSubject();
@ClassRule
public static ServiceITSetup setup = new ServiceITSetupImpl();
@Rule
public NewOrgAppAdminRule orgAppRule = new NewOrgAppAdminRule( setup );
@Test
public void testRun() throws Exception {
MigrationInfoSerialization serialization = Mockito.mock(MigrationInfoSerialization.class);
Mockito.when(serialization.getVersion(Mockito.any())).thenReturn(0);
EntityCollectionManagerFactory ecmf = setup.getInjector().getInstance(EntityCollectionManagerFactory.class);
GraphManagerFactory gmf = setup.getInjector().getInstance(GraphManagerFactory.class);
ManagementService managementService = setup.getMgmtSvc();
AppInfoMigrationPlugin appInfoMigrationPlugin = new AppInfoMigrationPlugin(setup.getEmf(),serialization,ecmf,gmf,managementService);
// create 10 applications, each with 10 entities
logger.debug("\n\nCreate 10 apps each with 10 entities");
final String orgName = uniqueOrg();
OrganizationOwnerInfo organization = orgAppRule.createOwnerAndOrganization(
orgName, uniqueUsername(), uniqueEmail(),"Ed Anuff", "test" );
List<UUID> appIds = new ArrayList<>();
/***
* Create all 10 apps in the new format
*/
for ( int i=0; i<10; i++ ) {
UUID appId = setup.getMgmtSvc().createApplication(
organization.getOrganization().getUuid(), "application" + i ).getId();
appIds.add( appId );
EntityManager em = setup.getEmf().getEntityManager( appId );
for ( int j=0; j<10; j++ ) {
final String entityName = "thing" + j;
em.create("thing", new HashMap<String, Object>() {{
put("name", entityName );
}});
}
}
UUID mgmtAppId = setup.getEmf().getManagementAppId();
setup.refreshIndex(mgmtAppId);
EntityManager rootEm = setup.getEmf().getEntityManager( mgmtAppId );
checkApplicationsOk( orgName );
// create corresponding 10 appinfo entities in Management app
// and delete the application_info entities from the Management app
logger.debug("\n\nCreate old-style appinfo entities to be migrated\n");
List<Entity> deletedApps = new ArrayList<>();
setup.getEmf().initializeApplicationV2(
CassandraService.DEFAULT_ORGANIZATION, AppInfoMigrationPlugin.SYSTEM_APP_ID, "systemapp", null, false);
EntityManager systemAppEm = setup.getEmf().getEntityManager( AppInfoMigrationPlugin.SYSTEM_APP_ID );
int count = 0;
/**
* Now to ensure the process is idempotent, we "move" half of our app infos into the old system and remove them.
* Once they're migrated, we should get all 10
*/
for ( UUID appId : appIds ) {
final Entity applicationInfo = getApplicationInfo( appId );
final String appName = applicationInfo.getName();
final String finalOrgId = organization.getOrganization().getUuid().toString();
final String finalAppId = applicationInfo.asId().getUuid().toString();
systemAppEm.create("appinfo", new HashMap<String, Object>() {{
put("name", appName );
put("organizationUuid", finalOrgId );
put("applicationUuid", finalAppId );
}});
// delete some but not all of the application_info entities
// so that we cover both create and update cases
if ( count++ % 2 == 0 ) {
rootEm.delete( applicationInfo );
deletedApps.add( applicationInfo );
}
}
setup.refreshIndex(mgmtAppId);
setup.getEmf().flushEntityManagerCaches();
Thread.sleep(1000);
// test that applications are now broken
checkApplicationsBroken(deletedApps);
// run the migration, which should restore the application_info entities
logger.debug("\n\nRun the migration\n");
ProgressObserver po = Mockito.mock(ProgressObserver.class);
appInfoMigrationPlugin.run(po);
logger.debug("\n\nVerify migration results\n");
// test that expected calls were made the to progress observer (use mock library)
Mockito.verify( po, Mockito.times(10) ).update( Mockito.anyInt(), Mockito.anyString() );
setup.refreshIndex(mgmtAppId);
final Results appInfoResults = rootEm.searchCollection(
new SimpleEntityRef("application", mgmtAppId), "appinfos", Query.fromQL("select *"));
assertEquals( 0, appInfoResults.size() );
final Results applicationInfoResults = rootEm.searchCollection(
new SimpleEntityRef("application", mgmtAppId), CpNamingUtils.APPLICATION_INFOS, Query.fromQL("select *"));
int appCount = Observable.from( applicationInfoResults.getEntities() ).filter(
entity -> !entity.getName().startsWith( "org." ) ).doOnNext(
entity -> logger.info("counting entity {}", entity) ).count().toBlocking().last();
assertEquals( appIds.size() ,appCount );
// test that 10 applications are no longer broken
checkApplicationsOk( orgName );
}
private void checkApplicationsBroken( List<Entity> deletedApps ) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("\n\nChecking applications broken\n");
}
for ( Entity applicationInfo : deletedApps ) {
String appName = applicationInfo.getName();
boolean isPresent = setup.getEmf().lookupApplication( appName ) != null;
// missing application_info does not completely break applications, but we...
assertFalse("Should not be able to lookup deleted application by name" + appName, isPresent);
}
}
private void checkApplicationsOk( String orgName) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("\n\nChecking applications OK\n");
}
for (int i=0; i<10; i++) {
String appName = orgName + "/application" + i;
UUID uuid = setup.getEmf().lookupApplication(appName);
assertTrue ("Should be able to get application", uuid != null );
EntityManager em = setup.getEmf().getEntityManager( uuid );
Application app = em.getApplication();
assertEquals( appName, app.getName() );
Results results = em.searchCollection(
em.getApplicationRef(), "things", Query.fromQL("select *"));
assertEquals( "Should have 10 entities", 10, results.size() );
}
}
private Entity getApplicationInfo( UUID appId ) throws Exception {
Map<String, UUID> apps = setup.getEmf().getApplications();
if(apps.containsValue(appId)){
return setup.getEmf().getManagementEntityManager().get(appId);
}else{
fail("no app " + appId);
return null;
}
}
}
| apache-2.0 |
ptupitsyn/ignite | modules/ml/src/main/java/org/apache/ignite/ml/multiclass/MultiClassModel.java | 3594 | /*
* 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.ignite.ml.multiclass;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeMap;
import org.apache.ignite.ml.Exportable;
import org.apache.ignite.ml.Exporter;
import org.apache.ignite.ml.IgniteModel;
import org.apache.ignite.ml.math.primitives.vector.Vector;
/** Base class for multi-classification model for set of classifiers. */
public class MultiClassModel<M extends IgniteModel<Vector, Double>> implements IgniteModel<Vector, Double>, Exportable<MultiClassModel>, Serializable {
/** */
private static final long serialVersionUID = -114986533359917L;
/** List of models associated with each class. */
private Map<Double, M> models;
/** */
public MultiClassModel() {
this.models = new HashMap<>();
}
/**
* Adds a specific binary classifier to the bunch of same classifiers.
*
* @param clsLb The class label for the added model.
* @param mdl The model.
*/
public void add(double clsLb, M mdl) {
models.put(clsLb, mdl);
}
/**
* @param clsLb Class label.
* @return model for class label if it exists.
*/
public Optional<M> getModel(Double clsLb) {
return Optional.ofNullable(models.get(clsLb));
}
/** {@inheritDoc} */
@Override public Double predict(Vector input) {
TreeMap<Double, Double> maxMargins = new TreeMap<>();
models.forEach((k, v) -> maxMargins.put(v.predict(input), k));
// returns value the most closest to 1
return maxMargins.lastEntry().getValue();
}
/** {@inheritDoc} */
@Override public <P> void saveModel(Exporter<MultiClassModel, P> exporter, P path) {
exporter.save(this, path);
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
MultiClassModel mdl = (MultiClassModel)o;
return Objects.equals(models, mdl.models);
}
/** {@inheritDoc} */
@Override public int hashCode() {
return Objects.hash(models);
}
/** {@inheritDoc} */
@Override public String toString() {
StringBuilder wholeStr = new StringBuilder();
models.forEach((clsLb, mdl) ->
wholeStr
.append("The class with label ")
.append(clsLb)
.append(" has classifier: ")
.append(mdl.toString())
.append(System.lineSeparator())
);
return wholeStr.toString();
}
/** {@inheritDoc} */
@Override public String toString(boolean pretty) {
return toString();
}
}
| apache-2.0 |
acartapanis/camel | platforms/spring-boot/components-starter/camel-jackson-starter/src/main/java/org/apache/camel/component/jackson/springboot/JacksonDataFormatAutoConfiguration.java | 5485 | /**
* 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.jackson.springboot;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.DataFormatFactory;
import org.apache.camel.util.IntrospectionSupport;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@Configuration
@ConditionalOnBean(type = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@Conditional(JacksonDataFormatAutoConfiguration.Condition.class)
@AutoConfigureAfter(name = "org.apache.camel.spring.boot.CamelAutoConfiguration")
@EnableConfigurationProperties(JacksonDataFormatConfiguration.class)
public class JacksonDataFormatAutoConfiguration {
@Bean(name = "json-jackson-dataformat-factory")
@ConditionalOnClass(CamelContext.class)
@ConditionalOnMissingBean(JacksonDataFormat.class)
public DataFormatFactory configureJacksonDataFormatFactory(
final CamelContext camelContext,
final JacksonDataFormatConfiguration configuration) {
return new DataFormatFactory() {
public DataFormat newInstance() {
JacksonDataFormat dataformat = new JacksonDataFormat();
if (CamelContextAware.class
.isAssignableFrom(JacksonDataFormat.class)) {
CamelContextAware contextAware = CamelContextAware.class
.cast(dataformat);
if (contextAware != null) {
contextAware.setCamelContext(camelContext);
}
}
try {
Map<String, Object> parameters = new HashMap<>();
IntrospectionSupport.getProperties(configuration,
parameters, null, false);
IntrospectionSupport.setProperties(camelContext,
camelContext.getTypeConverter(), dataformat,
parameters);
} catch (Exception e) {
throw new RuntimeCamelException(e);
}
return dataformat;
}
};
}
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
public static class Condition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(
ConditionContext conditionContext,
AnnotatedTypeMetadata annotatedTypeMetadata) {
boolean groupEnabled = isEnabled(conditionContext,
"camel.dataformat.", true);
ConditionMessage.Builder message = ConditionMessage
.forCondition("camel.dataformat.json-jackson");
if (isEnabled(conditionContext, "camel.dataformat.json-jackson.",
groupEnabled)) {
return ConditionOutcome.match(message.because("enabled"));
}
return ConditionOutcome.noMatch(message.because("not enabled"));
}
private boolean isEnabled(
org.springframework.context.annotation.ConditionContext context,
java.lang.String prefix, boolean defaultValue) {
RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(
context.getEnvironment(), prefix);
return resolver.getProperty("enabled", Boolean.class, defaultValue);
}
}
} | apache-2.0 |
yimun/ZzuNews | src/com/yimu/base/BaseSqlite.java | 5666 | package com.yimu.base;
import java.lang.reflect.Field;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public abstract class BaseSqlite {
private static final String DB_NAME = "duthelper.db";
private static final int DB_VERSION = 3;
public DbHelper dbh = null;
public SQLiteDatabase db = null;
public Cursor cursor = null;
protected Context context;
public BaseSqlite(Context context) {
this.context = context;
dbh = new DbHelper(context, DB_NAME, null, DB_VERSION);
}
public void insert(BaseModel values) {
try {
db = dbh.getWritableDatabase();
db.insert(tableName(), null, getValues(values, null));
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
public void insertList(ArrayList<? extends BaseModel> lists) {
try {
db = dbh.getWritableDatabase();
for (BaseModel item : lists) {
// TODO whether use null or tableColumns()
db.insert(tableName(), null, getValues(item, null));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
/**
*
* @param values
* BaseModel
* @param columns
* String[]
* @param where
* String
* @param params
* String[]
*/
public void update(BaseModel values, String[] columns, String where,
String[] params) {
try {
db = dbh.getWritableDatabase();
db.update(tableName(), getValues(values, columns), where, params);
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
/**
* delete all and insert list
*
* @param datalist
* ArrayList<? extends BaseModel>
*/
public void updateAll(ArrayList<? extends BaseModel> datalist) {
this.delete(null, null);
this.insertList(datalist);
}
/**
* delete all as {delete(null,null)}
*/
public void delete(String where, String[] params) {
try {
db = dbh.getWritableDatabase();
db.delete(tableName(), where, params);
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
/**
*
* @param columns
* {null if all}
* @param where
* @param params
* @return
*/
public ArrayList<? extends BaseModel> query(String[] columns, String where,
String[] params) {
ArrayList<BaseModel> rList = new ArrayList<BaseModel>();
if (columns == null)
columns = tableColumns();
try {
db = dbh.getReadableDatabase();
cursor = db.query(tableName(), columns, where, params, null, null,
null);
while (cursor.moveToNext()) {
BaseModel rRow = this.getModel(cursor, columns);
rList.add(rRow);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
cursor.close();
db.close();
}
return rList;
}
public int count(String where, String[] params) {
try {
db = dbh.getReadableDatabase();
cursor = db.query(tableName(), tableColumns(), where, params, null,
null, null);
return cursor.getCount();
} catch (Exception e) {
e.printStackTrace();
} finally {
cursor.close();
db.close();
}
return 0;
}
public boolean exists(String where, String[] params) {
boolean result = false;
int count = this.count(where, params);
if (count > 0) {
result = true;
}
return result;
}
abstract protected String tableName();
abstract protected String[] tableColumns();
abstract protected String createSql();
abstract protected String modelName();
protected String upgradeSql() {
return "DROP TABLE IF EXISTS " + tableName();
}
protected class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onOpen(SQLiteDatabase db) {
db.execSQL(createSql());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(upgradeSql());
onCreate(db);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
}
/**
* Get basemodel from db cursor
*
* @param cur
* @param fieldsName
* @return ? extends BaseModel
* @throws Exception
*/
protected BaseModel getModel(Cursor cur, String[] fieldsName)
throws Exception {
String modelClassName = C.packageName.model + "." + modelName();
BaseModel modelObj = (BaseModel) Class.forName(modelClassName)
.newInstance();
Class<? extends BaseModel> modelClass = modelObj.getClass();
// auto-setting model fields
for (String fieldname : fieldsName) {
Field field = modelClass.getDeclaredField(fieldname);
field.setAccessible(true); // have private to be accessable
field.set(modelObj, cur.getString(cur.getColumnIndex(fieldname)));
}
return modelObj;
}
/**
* Get ContentValues from basemodel
*
* @param model
* @param fieldsName
* @return ContentValues
*/
protected ContentValues getValues(BaseModel model, String[] fieldsName) {
ContentValues cv = new ContentValues();
if (fieldsName == null)
fieldsName = tableColumns();
try {
for (String fieldname : fieldsName) {
Field field = model.getClass().getDeclaredField(fieldname);
field.setAccessible(true);
String get = (String) field.get(model);
cv.put(fieldname, get);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return cv;
}
} | apache-2.0 |
botelhojp/apache-jmeter-2.10 | src/core/org/apache/jmeter/samplers/SampleListener.java | 1414 | /*
* 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.jmeter.samplers;
/**
* Allows notification on events occuring during the sampling process.
* Specifically, when sampling is started, when a specific sample is obtained,
* and when sampling is stopped.
*
* @version $Revision: 1377076 $
*/
public interface SampleListener {
/**
* A sample has started and stopped.
*/
void sampleOccurred(SampleEvent e);
/**
* A sample has started.
*/
void sampleStarted(SampleEvent e);
/**
* A sample has stopped.
*/
void sampleStopped(SampleEvent e);
}
| apache-2.0 |
apache/tapestry-5 | tapestry-core/src/main/java/org/apache/tapestry5/internal/services/messages/PropertiesFileParserImpl.java | 3389 | // Copyright 2010 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.internal.services.messages;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import java.util.Properties;
import org.apache.tapestry5.commons.Resource;
import org.apache.tapestry5.commons.util.CollectionFactory;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import org.apache.tapestry5.services.messages.PropertiesFileParser;
public class PropertiesFileParserImpl implements PropertiesFileParser
{
/**
* Charset used when reading a properties file.
*/
private static final String CHARSET = "UTF-8";
/**
* Buffer size used when reading a properties file.
*/
private static final int BUFFER_SIZE = 2000;
public Map<String, String> parsePropertiesFile(Resource resource) throws IOException
{
Map<String, String> result = CollectionFactory.newCaseInsensitiveMap();
Properties p = new Properties();
InputStream is = null;
try
{
is = readUTFStreamToEscapedASCII(resource.openStream());
// Ok, now we have the content read into memory as UTF-8, not ASCII.
p.load(is);
is.close();
is = null;
}
finally
{
InternalUtils.close(is);
}
for (Map.Entry e : p.entrySet())
{
String key = e.getKey().toString();
String value = p.getProperty(key);
result.put(key, value);
}
return result;
}
/**
* Reads a UTF-8 stream, performing a conversion to ASCII (i.e., ISO8859-1 encoding). Characters outside the normal
* range for ISO8859-1 are converted to unicode escapes. In effect, Tapestry is performing native2ascii on the
* files, on the fly.
*/
private static InputStream readUTFStreamToEscapedASCII(InputStream is) throws IOException
{
Reader reader = new InputStreamReader(is, CHARSET);
StringBuilder builder = new StringBuilder(BUFFER_SIZE);
char[] buffer = new char[BUFFER_SIZE];
while (true)
{
int length = reader.read(buffer);
if (length < 0)
break;
for (int i = 0; i < length; i++)
{
char ch = buffer[i];
if (ch <= '\u007f')
{
builder.append(ch);
continue;
}
builder.append(String.format("\\u%04x", (int) ch));
}
}
reader.close();
byte[] resourceContent = builder.toString().getBytes();
return new ByteArrayInputStream(resourceContent);
}
}
| apache-2.0 |
NGDATA/lilyproject | apps/import/src/main/java/org/lilyproject/tools/import_/core/RecordTypeImport.java | 6463 | /*
* Copyright 2010 Outerthought bvba
*
* 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.lilyproject.tools.import_.core;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.lilyproject.repository.api.FieldTypeEntry;
import org.lilyproject.repository.api.QName;
import org.lilyproject.repository.api.RecordType;
import org.lilyproject.repository.api.RecordTypeExistsException;
import org.lilyproject.repository.api.RecordTypeNotFoundException;
import org.lilyproject.repository.api.RepositoryException;
import org.lilyproject.repository.api.SchemaId;
import org.lilyproject.repository.api.TypeManager;
import static org.lilyproject.tools.import_.core.ImportMode.CREATE;
import static org.lilyproject.tools.import_.core.ImportMode.CREATE_OR_UPDATE;
import static org.lilyproject.tools.import_.core.ImportMode.UPDATE;
public class RecordTypeImport {
private RecordTypeImport() {
}
public static ImportResult<RecordType> importRecordType(RecordType newRecordType, ImportMode impMode,
IdentificationMode idMode, QName identifyingName, boolean refreshSubtypes, TypeManager typeManager)
throws RepositoryException, InterruptedException {
if (idMode == IdentificationMode.ID && impMode == CREATE_OR_UPDATE) {
throw new IllegalArgumentException("The combination of import mode " + CREATE_OR_UPDATE
+ " and identification mode " + IdentificationMode.ID + " is not possible.");
}
int loopCount = 0;
while (true) {
if (loopCount > 1) {
// We should never arrive here
throw new RuntimeException("Unexpected situation: when we tried to update the record type, " +
"it did not exist, when we tried to create the record type, it exists, and then when we retry " +
"to update, it does not exist after all.");
}
if (impMode == UPDATE || impMode == CREATE_OR_UPDATE) {
RecordType oldRecordType = null;
try {
if (idMode == IdentificationMode.ID) {
oldRecordType = typeManager.getRecordTypeById(newRecordType.getId(), null);
} else {
oldRecordType = typeManager.getRecordTypeByName(identifyingName, null);
}
} catch (RecordTypeNotFoundException e) {
if (impMode == UPDATE) {
return ImportResult.cannotUpdateDoesNotExist();
}
}
if (oldRecordType != null) {
boolean updated = false;
// Update field entries
Set<FieldTypeEntry> oldFieldTypeEntries = new HashSet<FieldTypeEntry>(oldRecordType.getFieldTypeEntries());
Set<FieldTypeEntry> newFieldTypeEntries = new HashSet<FieldTypeEntry>(newRecordType.getFieldTypeEntries());
if (!newFieldTypeEntries.equals(oldFieldTypeEntries)) {
updated = true;
oldRecordType.getFieldTypeEntries().clear();
for (FieldTypeEntry entry : newFieldTypeEntries) {
oldRecordType.addFieldTypeEntry(entry);
}
}
// Update supertypes
Map<SchemaId, Long> oldSupertypes = oldRecordType.getSupertypes();
Map<SchemaId, Long> newSupertypes = newRecordType.getSupertypes();
// Resolve any 'null' versions to actual version numbers, otherwise we are unable to compare
// with the old state.
for (Map.Entry<SchemaId, Long> entry : newSupertypes.entrySet()) {
if (entry.getValue() == null) {
entry.setValue(typeManager.getRecordTypeById(entry.getKey(), null).getVersion());
}
}
if (!oldSupertypes.equals(newSupertypes)) {
updated = true;
oldRecordType.getSupertypes().clear();
for (Map.Entry<SchemaId, Long> entry : newSupertypes.entrySet()) {
oldRecordType.addSupertype(entry.getKey(), entry.getValue());
}
}
// Update name
QName oldName = oldRecordType.getName();
QName newName = newRecordType.getName();
if (!oldName.equals(newName)) {
updated = true;
oldRecordType.setName(newName);
}
if (updated) {
oldRecordType = typeManager.updateRecordType(oldRecordType, refreshSubtypes);
return ImportResult.updated(oldRecordType);
} else {
return ImportResult.upToDate(oldRecordType);
}
}
}
if (impMode == UPDATE) {
// We should never arrive here, update is handled above
throw new RuntimeException("Unexpected situation: in case of mode " + UPDATE + " we should not be here.");
}
try {
RecordType createdRecordType = typeManager.createRecordType(newRecordType);
return ImportResult.created(createdRecordType);
} catch (RecordTypeExistsException e) {
if (impMode == CREATE) {
return ImportResult.cannotCreateExists();
}
// and otherwise, the record type has been created since we last checked, so we now
// loop again to the top to try to update it
}
loopCount++;
}
}
}
| apache-2.0 |
domeo/DomeoClient | src/org/mindinformatics/gwt/domeo/plugins/resource/opentrials/identities/EOpenTrialsDatabase.java | 679 | package org.mindinformatics.gwt.domeo.plugins.resource.opentrials.identities;
import org.mindinformatics.gwt.framework.component.agents.model.MAgentDatabase;
/**
* @author Paolo Ciccarese <paolo.ciccarese@gmail.com>
*/
@SuppressWarnings("serial")
public class EOpenTrialsDatabase extends MAgentDatabase {
private static EOpenTrialsDatabase _instance;
public static EOpenTrialsDatabase getInstance() {
if(_instance==null) _instance = new EOpenTrialsDatabase();
return _instance;
}
private EOpenTrialsDatabase() {
super("http://purl.org/domeo/entity/resource/OpenTrials", "OpenTrials - Lilly Open Clinical Trials", "http://opentrials.org/", "<noversion>");
}
}
| apache-2.0 |
YOU-i-Labs/appium-java-client | src/test/java/io/appium/java_client/pagefactory_tests/widgets/combined/SelendroidCombinedWidgetTest.java | 5150 | package io.appium.java_client.pagefactory_tests.widgets.combined;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
import io.appium.java_client.pagefactory.TimeOutDuration;
import io.appium.java_client.pagefactory_tests.widgets.Movie;
import io.appium.java_client.pagefactory_tests.widgets.WidgetTest;
import io.appium.java_client.remote.AutomationName;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServiceBuilder;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import java.io.File;
import java.util.concurrent.TimeUnit;
public class SelendroidCombinedWidgetTest implements WidgetTest {
private static int SELENDROID_PORT = 9999;
private static AppiumDriverLocalService service;
private AndroidDriver<?> driver;
private RottenTomatoesAppWithCombinedWidgets rottenTomatoes;
private TimeOutDuration duration;
/**
* initialization.
*/
@BeforeClass public static void beforeClass() throws Exception {
AppiumServiceBuilder builder = new AppiumServiceBuilder();
service = builder.build();
service.start();
}
/**
* finishing.
*/
@AfterClass public static void afterClass() throws Exception {
if (service != null) {
service.stop();
}
}
/**
* The setting up.
*/
@Before public void setUp() throws Exception {
File appDir = new File("src/test/java/io/appium/java_client");
File app = new File(appDir, "android-rottentomatoes-demo-debug.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.SELENDROID);
driver = new AndroidDriver<>(service.getUrl(), capabilities);
duration = new TimeOutDuration(20, TimeUnit.SECONDS);
rottenTomatoes = new RottenTomatoesAppWithCombinedWidgets();
driver.context("NATIVE_APP");
PageFactory.initElements(new AppiumFieldDecorator(driver, duration), rottenTomatoes);
}
/**
* after each test.
*/
@After public void tearDown() throws Exception {
driver.quit();
}
@Test
@Override public void checkACommonWidget() {
assertTrue(rottenTomatoes.getSimpleMovieCount() >= 1);
Movie movie = rottenTomatoes.getASimpleMovie(0);
assertTrue(!StringUtils.isBlank(movie.title()));
assertTrue(!StringUtils.isBlank(movie.score()));
assertNotNull(movie.getPoster());
movie.goToReview();
driver.getPageSource(); //forcing the refreshing hierarchy
rottenTomatoes.checkSimpleReview();
}
@Override
@Test public void checkAnAnnotatedWidget() {
assertTrue(rottenTomatoes.getAnnotatedMovieCount() >= 1);
Movie movie = rottenTomatoes.getAnAnnotatedMovie(0);
assertTrue(!StringUtils.isBlank(movie.title()));
assertTrue(!StringUtils.isBlank(movie.score()));
assertNotNull(movie.getPoster());
movie.goToReview();
driver.getPageSource(); //forcing the refreshing hierarchy
rottenTomatoes.checkAnnotatedReview();
}
@Override
@Test public void checkAnExtendedWidget() {
assertTrue(rottenTomatoes.getExtendeddMovieCount() >= 1);
Movie movie = rottenTomatoes.getAnExtendedMovie(0);
assertTrue(!StringUtils.isBlank(movie.title()));
assertTrue(!StringUtils.isBlank(movie.score()));
assertNotNull(movie.getPoster());
movie.goToReview();
driver.getPageSource(); //forcing the refreshing hierarchy
rottenTomatoes.checkExtendedReview();
}
@Override
@Test public void checkTheLocatorOverridingOnAWidget() {
duration.setTime(5);
try {
assertTrue(rottenTomatoes.getFakedMovieCount() == 0);
} catch (Exception e) {
if (!NoSuchElementException.class.isAssignableFrom(e.getClass())) {
throw e;
}
}
rottenTomatoes.getASimpleMovie(0).goToReview();
driver.getPageSource(); //forcing the refreshing hierarchy
try {
rottenTomatoes.checkFakeReview();
} catch (Exception e) {
if (NoSuchElementException.class.isAssignableFrom(e.getClass())) {
return;
} else {
throw e;
}
}
throw new RuntimeException("Any exception was expected");
}
}
| apache-2.0 |
cbmeeks/viritin | src/test/java/org/vaadin/viritin/it/FieldMatchValidator.java | 1312 | package org.vaadin.viritin.it;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.beanutils.BeanUtils;
/**
* * JSR303 crossfield validator example by Patrick:
* http://stackoverflow.com/questions/1972933/cross-field-validation-with-hibernate-validator-jsr-303
*
*
* @author Matti Tahvonen
*/
public class FieldMatchValidator implements
ConstraintValidator<FieldMatch, Object> {
private String firstFieldName;
private String secondFieldName;
@Override
public void initialize(final FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
@Override
public boolean isValid(final Object value,
final ConstraintValidatorContext context) {
try {
final Object firstObj = BeanUtils.getProperty(value,
firstFieldName);
final Object secondObj = BeanUtils.getProperty(value,
secondFieldName);
return firstObj == null && secondObj == null || firstObj != null && firstObj.
equals(secondObj);
} catch (final Exception ignore) {
// ignore
}
return true;
}
}
| apache-2.0 |
Ayvytr/logger | logger/src/main/java/com/ayvytr/logger/IPrinter.java | 410 | package com.ayvytr.logger;
/**
* Log打印接口
*
* @author Ayvytr ['s GitHub](https://github.com/Ayvytr)
* @since 1.0.0
*/
public interface IPrinter
{
void json(String json);
void xml(String xml);
void v(Object... objects);
void d(Object... objects);
void i(Object... objects);
void w(Object... objects);
void e(Object... objects);
void wtf(Object... objects);
}
| apache-2.0 |
mesutcelik/hazelcast | hazelcast/src/test/java/com/hazelcast/test/OverridePropertyRuleTest.java | 2083 | /*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.test;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import static com.hazelcast.test.OverridePropertyRule.set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Tests the {@link OverridePropertyRule} with multiple instances and a Hazelcast specific runner.
*/
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class OverridePropertyRuleTest {
@Rule
public OverridePropertyRule overridePropertyRule = set("hazelcast.custom.system.property", "5");
@Rule
public OverridePropertyRule overridePreferIpv4Rule = set("java.net.preferIPv4Stack", "true");
@Test
public void testNonExistingProperty() {
assertNull(System.getProperty("notExists"));
}
@Test
public void testCustomSystemProperty() {
assertEquals("5", System.getProperty("hazelcast.custom.system.property"));
}
@Test
public void testHazelcastProperty() {
assertEquals("true", System.getProperty("java.net.preferIPv4Stack"));
}
@Test
public void testHazelcastPropertyWithGetBoolean() {
assertTrue(Boolean.getBoolean("java.net.preferIPv4Stack"));
}
}
| apache-2.0 |
Netflix/spectator | spectator-api/src/test/java/com/netflix/spectator/impl/StepLongTest.java | 1889 | /*
* Copyright 2014-2019 Netflix, 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.netflix.spectator.impl;
import com.netflix.spectator.api.ManualClock;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class StepLongTest {
private final ManualClock clock = new ManualClock();
@BeforeEach
public void init() {
clock.setWallTime(0L);
}
@Test
public void empty() {
StepLong v = new StepLong(0L, clock, 10L);
Assertions.assertEquals(0L, v.getCurrent().get());
Assertions.assertEquals(0L, v.poll());
}
@Test
public void increment() {
StepLong v = new StepLong(0L, clock, 10L);
v.getCurrent().incrementAndGet();
Assertions.assertEquals(1L, v.getCurrent().get());
Assertions.assertEquals(0L, v.poll());
}
@Test
public void incrementAndCrossStepBoundary() {
StepLong v = new StepLong(0L, clock, 10L);
v.getCurrent().incrementAndGet();
clock.setWallTime(10L);
Assertions.assertEquals(0L, v.getCurrent().get());
Assertions.assertEquals(1L, v.poll());
}
@Test
public void missedRead() {
StepLong v = new StepLong(0L, clock, 10L);
v.getCurrent().incrementAndGet();
clock.setWallTime(20L);
Assertions.assertEquals(0L, v.getCurrent().get());
Assertions.assertEquals(0L, v.poll());
}
}
| apache-2.0 |
Orange-OpenSource/cf-java-client | cloudfoundry-client/src/test/java/org/cloudfoundry/client/v3/servicebindings/DeleteServiceBindingRequestTest.java | 1088 | /*
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.cloudfoundry.client.v3.servicebindings;
import org.junit.Test;
public final class DeleteServiceBindingRequestTest {
@Test(expected = IllegalStateException.class)
public void noServiceBindingId() {
DeleteServiceBindingRequest.builder()
.build();
}
@Test
public void valid() {
DeleteServiceBindingRequest.builder()
.serviceBindingId("test-service-binding-id")
.build();
}
}
| apache-2.0 |
vivekkant/my-personal-assistant | master-data/src/main/java/org/weekendsoft/mpa/masterdata/controller/AccountController.java | 2931 | /**
*
*/
package org.weekendsoft.mpa.masterdata.controller;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.weekendsoft.mpa.masterdata.exception.ERROR_CODES;
import org.weekendsoft.mpa.masterdata.exception.RecordNotFoundException;
import org.weekendsoft.mpa.masterdata.model.Account;
import org.weekendsoft.mpa.masterdata.model.ErrorInfo;
import org.weekendsoft.mpa.masterdata.repository.AccountRepository;
/**
* @author Vivek Kant
*
*/
@RestController
@RequestMapping("api/v1/accounts")
public class AccountController {
@Autowired
private AccountRepository accountRepository;
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(RecordNotFoundException.class)
public ErrorInfo handleException(RecordNotFoundException ex) {
ErrorInfo error = new ErrorInfo();
error.setCode(ERROR_CODES.RECORD_NOT_FOUND);
error.setMessage("Record with id: " + ex.id);
error.setStatus(HttpStatus.NOT_FOUND);
return error;
}
@RequestMapping(value = "", method = RequestMethod.GET)
public List<Account> list() {
return accountRepository.findAll();
}
@RequestMapping(value = "", method = RequestMethod.POST)
public Account create(@RequestBody Account account) {
return accountRepository.saveAndFlush(account);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Account get(@PathVariable int id) {
Account account = accountRepository.findOne(id);
if (account == null) throw new RecordNotFoundException(id, "Account ID not found: " + id, null);
return account;
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public Account update(@PathVariable int id, @RequestBody Account account) {
Account existingAccount = accountRepository.findOne(id);
if (existingAccount == null) throw new RecordNotFoundException(id, "Account ID not found: " + id, null);
BeanUtils.copyProperties(account, existingAccount);
account.setId(id);
return accountRepository.saveAndFlush(existingAccount);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Account delete(@PathVariable int id) {
Account existingAccount = accountRepository.findOne(id);
if (existingAccount == null) throw new RecordNotFoundException(id, "Account ID not found: " + id, null);
accountRepository.delete(existingAccount);
return existingAccount;
}
}
| bsd-2-clause |
jamerlan/jSpringLobbyLib | src/main/java/com/jamerlan/commands/impl/in/AgreementEnd.java | 652 | package com.jamerlan.commands.impl.in;
import com.jamerlan.ServerState;
import com.jamerlan.commands.Command;
import com.jamerlan.utils.CommandParser;
import java.io.IOException;
import java.io.PrintWriter;
/**
AGREEMENTEND
*/
public class AgreementEnd implements Command<String> {
private ServerState serverState;
public AgreementEnd(ServerState serverState) {
this.serverState = serverState;
}
@Override
public void execute(String line) throws IOException {
CommandParser parser = new CommandParser(line);
String commandName = parser.getString();
System.out.println(commandName);
}
}
| bsd-2-clause |
CameronTolooee/galileo | src/galileo/dht/hash/ConstrainedGeohash.java | 3449 | /*
Copyright (c) 2013, Colorado State University
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 holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/
package galileo.dht.hash;
import galileo.dataset.Metadata;
import galileo.dataset.SpatialProperties;
import galileo.util.GeoHash;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Provides a Geohash-based hash function that acts on a predefined constrained
* set of hashes.
*
* @author malensek
*/
public class ConstrainedGeohash implements HashFunction<Metadata> {
private Random random = new Random();
private String[] geohashes;
private Map<String, BigInteger> hashMappings = new HashMap<>();
private int precision;
public ConstrainedGeohash(String[] geohashes) throws HashException {
this.geohashes = geohashes;
/* All Geohashes are assumed to be a consistent precision .*/
precision = geohashes[0].length();
for (String hash : geohashes) {
/* Check for proper precision */
if (hash.length() != precision) {
throw new HashException("ConstrainedGeohash requires "
+ "consistent Geohash precision");
}
int idx = hashMappings.keySet().size();
hashMappings.put(hash.toLowerCase(), BigInteger.valueOf(idx));
}
}
@Override
public BigInteger hash(Metadata data)
throws HashException {
String hash = null;
SpatialProperties spatialProps = data.getSpatialProperties();
if (spatialProps.hasRange()) {
hash = GeoHash.encode(spatialProps.getSpatialRange(), precision);
} else {
hash = GeoHash.encode(spatialProps.getCoordinates(), precision);
}
BigInteger position = hashMappings.get(hash);
if (position == null) {
throw new HashException("Could not find position in hash space.");
}
return position;
}
@Override
public BigInteger maxValue() {
return BigInteger.valueOf(geohashes.length);
}
@Override
public BigInteger randomHash() {
int idx = random.nextInt(geohashes.length);
return hashMappings.get(geohashes[idx]);
}
}
| bsd-2-clause |
katasource/maera | osgi/loader/src/test/java/org/maera/plugin/osgi/factory/OsgiPluginFactoryTest.java | 5917 | package org.maera.plugin.osgi.factory;
import com.mockobjects.dynamic.C;
import com.mockobjects.dynamic.Mock;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.maera.plugin.*;
import org.maera.plugin.event.impl.DefaultPluginEventManager;
import org.maera.plugin.module.ModuleFactory;
import org.maera.plugin.osgi.container.OsgiContainerManager;
import org.maera.plugin.osgi.container.impl.DefaultOsgiPersistentCache;
import org.maera.plugin.osgi.hostcomponents.HostComponentRegistration;
import org.maera.plugin.test.PluginJarBuilder;
import org.maera.plugin.test.PluginTestUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.packageadmin.PackageAdmin;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class OsgiPluginFactoryTest {
private OsgiPluginFactory factory;
private File jar;
private Mock mockBundle;
private Mock mockSystemBundle;
private OsgiContainerManager osgiContainerManager;
private File tmpDir;
@Before
public void setUp() throws IOException, URISyntaxException {
tmpDir = PluginTestUtils.createTempDirectory(OsgiPluginFactoryTest.class);
osgiContainerManager = mock(OsgiContainerManager.class);
mock(ModuleFactory.class);
factory = new OsgiPluginFactory(PluginAccessor.Descriptor.FILENAME, (String) null, new DefaultOsgiPersistentCache(tmpDir), osgiContainerManager, new DefaultPluginEventManager());
jar = new PluginJarBuilder("someplugin").addPluginInformation("plugin.key", "My Plugin", "1.0").build();
mockBundle = new Mock(Bundle.class);
final Dictionary<String, String> dict = new Hashtable<String, String>();
dict.put(Constants.BUNDLE_DESCRIPTION, "desc");
dict.put(Constants.BUNDLE_VERSION, "1.0");
mockBundle.matchAndReturn("getHeaders", dict);
mockSystemBundle = new Mock(Bundle.class);
final Dictionary<String, String> sysDict = new Hashtable<String, String>();
sysDict.put(Constants.BUNDLE_DESCRIPTION, "desc");
sysDict.put(Constants.BUNDLE_VERSION, "1.0");
mockSystemBundle.matchAndReturn("getHeaders", sysDict);
mockSystemBundle.matchAndReturn("getLastModified", System.currentTimeMillis());
mockSystemBundle.matchAndReturn("getSymbolicName", "system.bundle");
Mock mockSysContext = new Mock(BundleContext.class);
mockSystemBundle.matchAndReturn("getBundleContext", mockSysContext.proxy());
mockSysContext.matchAndReturn("getServiceReference", C.ANY_ARGS, null);
mockSysContext.matchAndReturn("getService", C.ANY_ARGS, new Mock(PackageAdmin.class).proxy());
}
@After
public void tearDown() throws IOException {
factory = null;
FileUtils.cleanDirectory(tmpDir);
jar.delete();
}
@Test
public void testCanLoadNoXml() throws PluginParseException, IOException {
final File plugin = new PluginJarBuilder("loadwithxml").build();
final String key = factory.canCreate(new JarPluginArtifact(plugin));
assertNull(key);
}
@Test
public void testCanLoadWithXml() throws PluginParseException, IOException {
final File plugin = new PluginJarBuilder("loadwithxml").addPluginInformation("foo.bar", "", "1.0").build();
final String key = factory.canCreate(new JarPluginArtifact(plugin));
assertEquals("foo.bar", key);
}
@Test
public void testCreateOsgiPlugin() throws PluginParseException {
mockBundle.expectAndReturn("getSymbolicName", "plugin.key");
when(osgiContainerManager.getHostComponentRegistrations()).thenReturn(new ArrayList<HostComponentRegistration>());
when(osgiContainerManager.getBundles()).thenReturn(new Bundle[]{(Bundle) mockSystemBundle.proxy()});
final Plugin plugin = factory.create(new JarPluginArtifact(jar), (ModuleDescriptorFactory) new Mock(ModuleDescriptorFactory.class).proxy());
assertNotNull(plugin);
assertTrue(plugin instanceof OsgiPlugin);
}
@Test
public void testCreateOsgiPluginWithBadVersion() throws PluginParseException, IOException {
jar = new PluginJarBuilder("someplugin").addPluginInformation("plugin.key", "My Plugin", "beta.1.0").build();
mockBundle.expectAndReturn("getSymbolicName", "plugin.key");
when(osgiContainerManager.getHostComponentRegistrations()).thenReturn(new ArrayList<HostComponentRegistration>());
when(osgiContainerManager.getBundles()).thenReturn(new Bundle[]{(Bundle) mockSystemBundle.proxy()});
try {
factory.create(new JarPluginArtifact(jar), (ModuleDescriptorFactory) new Mock(ModuleDescriptorFactory.class).proxy());
fail("Should have complained about osgi version");
}
catch (PluginParseException ignored) {
}
}
@Test
public void testCreateOsgiPluginWithBadVersion2() throws PluginParseException, IOException {
jar = new PluginJarBuilder("someplugin").addPluginInformation("plugin.key", "My Plugin", "3.2-rc1").build();
mockBundle.expectAndReturn("getSymbolicName", "plugin.key");
when(osgiContainerManager.getHostComponentRegistrations()).thenReturn(new ArrayList<HostComponentRegistration>());
when(osgiContainerManager.getBundles()).thenReturn(new Bundle[]{(Bundle) mockSystemBundle.proxy()});
Plugin plugin = factory.create(new JarPluginArtifact(jar), (ModuleDescriptorFactory) new Mock(ModuleDescriptorFactory.class).proxy());
assertTrue(plugin instanceof OsgiPlugin);
}
}
| bsd-3-clause |
NCIP/caaers | caAERS/software/web/src/test/java/gov/nih/nci/cabig/caaers/web/listener/AbstractEventListenerTest.java | 5743 | /*******************************************************************************
* Copyright SemanticBits, Northwestern University and Akaza Research
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caaers/LICENSE.txt for details.
******************************************************************************/
package gov.nih.nci.cabig.caaers.web.listener;
import gov.nih.nci.cabig.caaers.AbstractTestCase;
import gov.nih.nci.cabig.caaers.accesscontrol.dataproviders.FilteredDataLoader;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.event.*;
import gov.nih.nci.cabig.caaers.security.SecurityTestUtils;
import gov.nih.nci.cabig.caaers.security.SecurityUtils;
import org.acegisecurity.Authentication;
import org.acegisecurity.event.authentication.AuthenticationSuccessEvent;
import org.easymock.EasyMock;
import org.springframework.context.ApplicationEvent;
/**
* @author: Biju Joseph
*/
public class AbstractEventListenerTest extends AbstractTestCase {
AuthenticationSuccessListener listener;
CourseModificationEventListener courseListener;
FilteredDataLoader loader;
@Override
public void setUp() throws Exception {
super.setUp();
loader = registerMockFor(FilteredDataLoader.class);
listener = new AuthenticationSuccessListener();
courseListener = new CourseModificationEventListener();
listener.setEventMonitor(new EventMonitor());
listener.setFilteredDataLoader(loader);
courseListener.setEventMonitor(new EventMonitor());
courseListener.setFilteredDataLoader(loader);
SecurityTestUtils.switchToSuperuser();
}
public void testIsSupported() throws Exception {
AuthenticationSuccessEvent event = new AuthenticationSuccessEvent(SecurityUtils.getAuthentication());
assertTrue(listener.isSupported(event));
assertFalse(listener.isSupported(new StudyModificationEvent(SecurityUtils.getAuthentication(), new LocalStudy())));
}
public void testIsSupportedForAllListeners(){
Authentication a = SecurityUtils.getAuthentication();
assertTrue(new StudyModificationEventListener().isSupported(new StudyModificationEvent(a, new LocalStudy())));
assertTrue(new CourseModificationEventListener().isSupported(new CourseModificationEvent(a, new AdverseEvent())));
assertTrue(new AdverseEventModificationEventListener().isSupported(new AdverseEventModificationEvent(a, new LocalStudy())));
assertTrue(new ExpeditedReportModificationEventListener().isSupported(new ExpeditedReportModificationEvent(a, new ExpeditedAdverseEventReport())));
assertTrue(new InvestigatorModificationEventListener().isSupported(new InvestigatorModificationEvent(a, new LocalInvestigator())));
assertTrue(new OrganizationModificationEventListener().isSupported(new OrganizationModificationEvent(a, new LocalOrganization())));
assertTrue(new ReportModificationEventListener().isSupported(new ReportModificationEvent(a, new LocalOrganization())));
assertTrue(new ResearchStaffModificationEventListener().isSupported(new ResearchStaffModificationEvent(a, new LocalOrganization())));
assertTrue(new SubjectModificationEventListener().isSupported(new SubjectModificationEvent(a, new LocalOrganization())));
assertFalse(new StudyModificationEventListener().isSupported( new AuthenticationSuccessEvent(SecurityUtils.getAuthentication())));
assertFalse(new CourseModificationEventListener().isSupported( new AuthenticationSuccessEvent(SecurityUtils.getAuthentication())));
assertFalse(new AdverseEventModificationEventListener().isSupported( new AuthenticationSuccessEvent(SecurityUtils.getAuthentication())));
assertFalse(new ExpeditedReportModificationEventListener().isSupported( new AuthenticationSuccessEvent(SecurityUtils.getAuthentication())));
assertFalse(new InvestigatorModificationEventListener().isSupported( new AuthenticationSuccessEvent(SecurityUtils.getAuthentication())));
assertFalse(new OrganizationModificationEventListener().isSupported( new AuthenticationSuccessEvent(SecurityUtils.getAuthentication())));
assertFalse(new ReportModificationEventListener().isSupported( new AuthenticationSuccessEvent(SecurityUtils.getAuthentication())));
assertFalse(new ResearchStaffModificationEventListener().isSupported( new AuthenticationSuccessEvent(SecurityUtils.getAuthentication())));
assertFalse(new SubjectModificationEventListener().isSupported( new AuthenticationSuccessEvent(SecurityUtils.getAuthentication())));
}
public void testOnApplicationEventUnsupportedEvent() throws Exception{
Authentication a = SecurityUtils.getAuthentication();
replayMocks();
listener.onApplicationEvent(new EntityModificationEvent(a, new Lab(), null));
verifyMocks();
}
public void testOnApplicationEventCourseModification() throws Exception{
Authentication a = SecurityUtils.getAuthentication();
loader.updateIndexByUserName(a);
replayMocks();
courseListener.onApplicationEvent(new CourseModificationEvent(a, new AdverseEventReportingPeriod()));
verifyMocks();
}
public void testOnApplicationEventOnAuthentication() throws Exception{
Authentication a = SecurityUtils.getAuthentication();
AuthenticationSuccessEvent event = new AuthenticationSuccessEvent(a);
loader.updateIndexByUserName(a);
replayMocks();
listener.onApplicationEvent(event);
verifyMocks();
}
}
| bsd-3-clause |
sahara-labs/scheduling-server | RigProvider/src/au/edu/uts/eng/remotelabs/schedserver/rigprovider/identok/impl/tests/IdentityTokenRegisterTester.java | 6259 | /**
* SAHARA Scheduling Server
*
* Schedules and assigns local laboratory rigs.
*
* @license See LICENSE in the top level directory for complete license terms.
*
* Copyright (c) 2010, University of Technology, Sydney
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Technology, Sydney 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.
*
* @author Michael Diponio (mdiponio)
* @date 4th January 2010
*/
package au.edu.uts.eng.remotelabs.schedserver.rigprovider.identok.impl.tests;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import au.edu.uts.eng.remotelabs.schedserver.logger.LoggerActivator;
import au.edu.uts.eng.remotelabs.schedserver.logger.impl.SystemErrLogger;
import au.edu.uts.eng.remotelabs.schedserver.rigprovider.identok.impl.IdentityTokenRegister;
/**
* Tests the {@link IdentityTokenRegister} class.
*/
public class IdentityTokenRegisterTester extends TestCase
{
/** Object of class under test. */
private IdentityTokenRegister register;
@Override
@Before
public void setUp() throws Exception
{
/* Set up the logger. */
Field f = LoggerActivator.class.getDeclaredField("logger");
f.setAccessible(true);
f.set(null, new SystemErrLogger());
this.register = IdentityTokenRegister.getInstance();
f = IdentityTokenRegister.class.getDeclaredField("registry");
f.setAccessible(true);
f.set(this.register, Collections.synchronizedMap(new HashMap<String, String>()));
}
@Test
public void testGenerateIdentityToken()
{
String tok, prevTok = this.register.generateIdentityToken("rig");
assertNotNull(prevTok);
assertEquals(20, prevTok.length());
List<Character> charTable = new ArrayList<Character>(94);
for (int i = 33; i <= 126; i++)
{
charTable.add((char)i);
}
for (int i = 0; i < 10000; i++)
{
tok = this.register.generateIdentityToken("rig");
assertNotNull(tok);
assertFalse(tok.equals(prevTok));
for (char c : tok.toCharArray())
{
/* Make sure the characters are all visible. */
assertTrue(c >= 33); // '!' - minimum visible glyph in Ascii
assertTrue(c <= 126); // '~' - maximum visible glyph in Ascii
assertFalse(c == '\\'); // '\' character in Ascii
assertFalse(c == '\'');
charTable.remove(Character.valueOf(c));
}
}
assertEquals(2, charTable.size());
assertEquals('\'', charTable.get(0).charValue());
assertEquals('\\', charTable.get(1).charValue());
}
@Test
public void testGetIdentityToken()
{
String tok[] = new String[100];
for (int i = 0; i < 100; i++)
{
tok[i] = this.register.generateIdentityToken("tok" + i);
}
for (int i = 0; i < IdentityTokenRegister.AVERAGE_IDENTITY_TOKEN_LIFE * 10; i++)
{
for (int j = 0; j < 100; j++)
{
assertEquals(tok[j], this.register.getIdentityToken("tok" + j));
}
}
}
@Test
public void testRemoveIdentityToken()
{
assertNotNull(this.register.generateIdentityToken("tok"));
assertNotNull(this.register.getIdentityToken("tok"));
this.register.removeIdentityToken("tok");
assertNull(this.register.getIdentityToken("tok"));
}
@Test
public void testGetOrGenerateIdentityToken()
{
String tok = this.register.generateIdentityToken("tok");
int diff = 0;
for (int i = 0; i < IdentityTokenRegister.AVERAGE_IDENTITY_TOKEN_LIFE * 100; i++)
{
if (!tok.equals(this.register.getOrGenerateIdentityToken("tok")))
{
tok = this.register.getIdentityToken("tok");
diff++;
}
}
/* The average is within 15 % of the expected value. */
assertTrue(85 < diff && diff < 115);
}
@SuppressWarnings("unchecked")
@Test
public void testExpunge() throws Exception
{
for (int i = 0; i < 100; i++)
{
assertNotNull(this.register.generateIdentityToken("t" + i));
}
this.register.expunge();
Field f = IdentityTokenRegister.class.getDeclaredField("registry");
f.setAccessible(true);
assertEquals(0, ((Map<String, String>)f.get(this.register)).size());
}
}
| bsd-3-clause |
drmacro/basex | basex-core/src/main/java/org/basex/query/func/db/DbRestore.java | 1087 | package org.basex.query.func.db;
import static org.basex.query.QueryError.*;
import static org.basex.util.Token.*;
import org.basex.core.*;
import org.basex.query.*;
import org.basex.query.up.primitives.name.*;
import org.basex.query.value.item.*;
import org.basex.util.*;
import org.basex.util.list.*;
/**
* Function implementation.
*
* @author BaseX Team 2005-16, BSD License
* @author Christian Gruen
*/
public final class DbRestore extends DbAccess {
@Override
public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
// extract database name from backup file
final String name = string(toToken(exprs[0], qc));
if(!Databases.validName(name)) throw BXDB_NAME_X.get(info, name);
// find backup with or without date suffix
final StringList backups = qc.context.databases.backups(name);
if(backups.isEmpty()) throw BXDB_NOBACKUP_X.get(info, name);
final String backup = backups.get(0);
final String db = Databases.name(backup);
qc.updates().add(new DBRestore(db, backup, qc, info), qc);
return null;
}
}
| bsd-3-clause |
gutomaia/steam-condenser-java | src/main/java/com/github/koraktor/steamcondenser/steam/packets/S2A_LOGSTRING_Packet.java | 1020 | /**
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2011, Sebastian Staudt
*/
package com.github.koraktor.steamcondenser.steam.packets;
/**
* This class represents a S2A_LOGSTRING packet used to transfer log messages
*
* @author Sebastian Staudt
*/
public class S2A_LOGSTRING_Packet extends SteamPacket {
/**
* The log message contained in this packet
*/
private String message;
/**
* Creates a new S2A_LOGSTRING object based on the given data
*
* @param data The raw packet data sent by the server
*/
public S2A_LOGSTRING_Packet(byte[] data) {
super(SteamPacket.S2A_LOGSTRING_HEADER, data);
this.contentData.getByte();
this.message = this.contentData.getString();
}
/**
* Returns the log message contained in this packet
*
* @return The log message
*/
public String getMessage() {
return this.message;
}
}
| bsd-3-clause |
rahulmutt/ghcvm | rts/src/main/java/eta/runtime/concurrent/WorkerThread.java | 634 | package eta.runtime.concurrent;
import eta.runtime.Runtime;
import eta.runtime.stg.Capability;
import static eta.runtime.RuntimeLogging.*;
public class WorkerThread extends Thread {
public WorkerThread() {}
@Override
public void run() {
final Capability worker = Capability.getLocal(true);
try {
worker.schedule(null);
} catch (Exception e) {
if (Runtime.debugScheduler()) {
debugScheduler("Died from exception: " + e.getMessage());
}
e.printStackTrace();
} finally {
worker.removeWorker();
}
}
}
| bsd-3-clause |
MaTriXy/fresco | imagepipeline/src/test/java/com/facebook/imagepipeline/producers/QualifiedResourceFetchProducerTest.java | 3805 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.imagepipeline.producers;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.ContentResolver;
import android.net.Uri;
import com.facebook.common.memory.PooledByteBuffer;
import com.facebook.common.memory.PooledByteBufferFactory;
import com.facebook.common.util.UriUtil;
import com.facebook.imagepipeline.common.Priority;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.testing.FakeClock;
import com.facebook.imagepipeline.testing.TestExecutorService;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
/**
* Basic tests for QualifiedResourceFetchProducer
*/
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class QualifiedResourceFetchProducerTest {
private static final String PRODUCER_NAME = QualifiedResourceFetchProducer.PRODUCER_NAME;
private static final String PACKAGE_NAME = "com.myapp.myplugin";
private static final int RESOURCE_ID = 42;
private static final String REQUEST_ID = "requestId";
private static final String CALLER_CONTEXT = "callerContext";
@Mock public PooledByteBufferFactory mPooledByteBufferFactory;
@Mock public ContentResolver mContentResolver;
@Mock public Consumer<EncodedImage> mConsumer;
@Mock public ImageRequest mImageRequest;
@Mock public ProducerListener mProducerListener;
@Mock public Exception mException;
private TestExecutorService mExecutor;
private SettableProducerContext mProducerContext;
private Uri mContentUri;
private QualifiedResourceFetchProducer mQualifiedResourceFetchProducer;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mExecutor = new TestExecutorService(new FakeClock());
mQualifiedResourceFetchProducer = new QualifiedResourceFetchProducer(
mExecutor,
mPooledByteBufferFactory,
mContentResolver);
mContentUri = UriUtil.getUriForQualifiedResource(PACKAGE_NAME, RESOURCE_ID);
mProducerContext = new SettableProducerContext(
mImageRequest,
REQUEST_ID,
mProducerListener,
CALLER_CONTEXT,
ImageRequest.RequestLevel.FULL_FETCH,
false,
true,
Priority.MEDIUM);
when(mImageRequest.getSourceUri()).thenReturn(mContentUri);
}
@Test
public void testQualifiedResourceUri() throws Exception {
PooledByteBuffer pooledByteBuffer = mock(PooledByteBuffer.class);
when(mPooledByteBufferFactory.newByteBuffer(any(InputStream.class)))
.thenReturn(pooledByteBuffer);
when(mContentResolver.openInputStream(mContentUri))
.thenReturn(mock(InputStream.class));
mQualifiedResourceFetchProducer.produceResults(mConsumer, mProducerContext);
mExecutor.runUntilIdle();
verify(mPooledByteBufferFactory, times(1)).newByteBuffer(any(InputStream.class));
verify(mContentResolver, times(1)).openInputStream(mContentUri);
verify(mProducerListener).onProducerStart(REQUEST_ID, PRODUCER_NAME);
verify(mProducerListener).onProducerFinishWithSuccess(REQUEST_ID, PRODUCER_NAME, null);
}
}
| bsd-3-clause |
eclipse/flux | org.eclipse.flux.client.java/src/test/java/org/eclipse/flux/client/java/AbstractFluxClientTest.java | 9162 | /*******************************************************************************
* Copyright (c) 2014 Pivotal Software, Inc. and others.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution
* License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html).
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.flux.client.java;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import junit.framework.TestCase;
import org.eclipse.flux.client.MessageConnector;
import org.eclipse.flux.client.MessageHandler;
import org.eclipse.flux.client.SingleResponseHandler;
import org.eclipse.flux.client.util.BasicFuture;
import org.eclipse.flux.client.util.ExceptionUtil;
import org.json.JSONObject;
/**
* Test harness for FluxClient. Subclass this class to use it.
*
* @author Kris De Volder
*/
public abstract class AbstractFluxClientTest extends TestCase {
public static abstract class ResponseHandler<T> {
protected abstract T handle(String messageType, JSONObject msg) throws Exception;
}
/**
* Limits the duration of various operations in the test harness so that we
* can, for example also write 'negative' tests that succeed only if
* certain messages are not received (within the timeout).
*/
public static final long TIMEOUT = 2000;
/**
* The expectation in the test harness is that Processes are meant to terminate naturally
* without raising exceptions, within a reasonable time. When a process gets stuck
* this timeout kicks in to allow operations that are waiting for processes to terminate to proceed.
*/
public static final long STUCK_PROCESS_TIMEOUT = 60000;
public static <T> void assertError(Class<? extends Throwable> expected, BasicFuture<T> r) {
T result = null;
Throwable error = null;
try {
result = r.get();
} catch (Throwable e) {
error = e;
}
assertTrue("Should have thrown "+expected.getName()+" but returned "+result,
error!=null
&& ( expected.isAssignableFrom(error.getClass())
|| expected.isAssignableFrom(ExceptionUtil.getDeepestCause(error).getClass())
)
);
}
public static <T> void assertError(String expectContains, BasicFuture<T> r) {
T result = null;
Throwable error = null;
try {
result = r.get();
} catch (Throwable e) {
error = e;
}
assertTrue("Should have thrown '..."+expectContains+"...' but returned "+result,
error!=null
&& ( contains(error.getMessage(), expectContains)
|| contains(ExceptionUtil.getDeepestCause(error).getMessage(), expectContains)
)
);
}
private Timer timer;
/**
* Javascript style 'setTimeout' useful for tests that are doing 'callback' style things rather thread-style waiting.
*/
public void setTimeout(long delay, TimerTask task) {
timer().schedule(task, delay);
}
private synchronized Timer timer() {
if (timer==null) {
timer = new Timer();
}
return timer;
}
private static boolean contains(String message, String expectContains) {
return message!=null && message.contains(expectContains);
}
private final List<Process<?>> processes = new ArrayList<>();
protected abstract MessageConnector createConnection(String user) throws Exception;
@Override
protected void tearDown() throws Exception {
try {
super.tearDown();
//ensure all processes are terminated.
synchronized (processes) {
for (Process<?> process : processes) {
assertTrue("Process not started", process.hasRun);
assertFalse("Poorly behaved tests, left a processes running", process.isAlive());
}
}
} finally {
//Make sure this gets executed no matter what or there will be Thread leakage!
if (timer!=null) {
timer.cancel();
}
}
}
/**
* A 'test process' is essentially a thread with some convenient methods to be
* able to easily script test sequences that send / receive messages to / from
* a flux connection. There is also a built-in timeout mechanism that ensures
* no test process runs forever. To use this class simply subclass (typically
* with a anonymous class) and implement the 'execute' method.
* <p>
* A well behaved process should terminate naturally without throwing an exception.
* The test harness tries to detect if a process is not well behaved.
*/
public abstract class Process<T> extends Thread {
protected MessageConnector conn;
public final BasicFuture<T> result;
boolean hasRun = false; //To be able to detect mistakes in tests where a process is created but never started.
// It doesn't really make sense to create a Process if this process is never being run
// so this almost certainly means there's a bug in the test that created the process.
public Process(String user) throws Exception {
this.result = new BasicFuture<>();
this.conn = createConnection(user);
this.conn.connectToChannelSync(user);
this.result.setTimeout(STUCK_PROCESS_TIMEOUT);
synchronized (processes) {
processes.add(this);
}
}
@Override
public final void run() {
hasRun = true;
try {
this.result.resolve(execute());
} catch (Throwable e) {
result.reject(e);
} finally {
this.conn.disconnect();
}
}
public void send(String type, JSONObject msg) throws Exception {
conn.send(type, msg);
}
/**
* Asynchronously send a request and return a Future with the response.
*/
public <R> BasicFuture<R> asendRequest(final String messageType, JSONObject msg, final ResponseHandler<R> responseHandler) throws Exception {
SingleResponseHandler<R> response = new SingleResponseHandler<R>(conn, responseType(messageType)) {
@Override
protected R parse(String messageType, JSONObject message) throws Exception {
return responseHandler.handle(messageType, message);
}
};
conn.addMessageHandler(response);
send(messageType, msg);
return response.getFuture();
}
/**
* Synchronously send a request and return the response.
*/
public <R> R sendRequest(String messageType, JSONObject msg, ResponseHandler<R> responseHandler) throws Exception {
return asendRequest(messageType, msg, responseHandler).get();
}
private String responseType(String messageType) {
if (messageType.endsWith("Request")) {
return messageType.substring(0, messageType.length()-"Request".length()) + "Response";
}
throw new IllegalArgumentException("Not a 'Request' message type: "+messageType);
}
/**
* Asynchronous receive. Returns a BasicFuture that resolves when message
* is received.
*/
public BasicFuture<JSONObject> areceive(String type) {
final BasicFuture<JSONObject> result = new BasicFuture<JSONObject>();
result.setTimeout(TIMEOUT);
once(new MessageHandler(type) {
public void handle(String type, JSONObject message) {
result.resolve(message);
}
});
return result;
}
/**
* Synchronous receive. Blocks until message of given type is received.
*/
public JSONObject receive(String type) throws Exception {
return areceive(type).get();
}
public void once(final MessageHandler messageHandler) {
conn.addMessageHandler(new MessageHandler(messageHandler.getMessageType()) {
@Override
public boolean canHandle(String type, JSONObject message) {
return messageHandler.canHandle(type, message);
}
@Override
public void handle(String type, JSONObject message) {
conn.removeMessageHandler(this);
messageHandler.handle(type, message);
}
});
}
protected abstract T execute() throws Exception;
}
/**
* Run a bunch of processes by starting them in the provided order. Once all processes are running,
* block until all of them complete. If any one of the processes is terminated by an Exception then
* 'run' guarantees that at least one of the exceptions is re-thrown
*/
public void run(Process<?>... processes) throws Exception {
for (Process<?> process : processes) {
process.start();
}
await(processes);
}
public void await(Process<?>... processes) throws Exception {
Throwable error = null;
for (Process<?> process : processes) {
try {
process.result.get();
} catch (Throwable e) {
e.printStackTrace();
if (error==null) {
error = e;
}
}
}
if (error!=null) {
throw ExceptionUtil.exception(error);
}
//Allthough the work the Processes are doing is 'finished' It is possible the threads themselves
// are still 'busy' for a brief time thereafter so wait for the threads to die.
for (Process<?> process : processes) {
process.join(500); //shouldn't be long (unless test is ill-behaved and process is 'stuck', but then it would
// not be possible to reach this point, since at least a TimeoutException will be raised
// above as a result of that 'stuck' Process's result.promise timing out.
}
}
}
| bsd-3-clause |
emaze/emaze-dysfunctional | src/main/java/net/emaze/dysfunctional/dispatching/spying/TernaryMonitoringFunction.java | 1106 | package net.emaze.dysfunctional.dispatching.spying;
import java.util.concurrent.atomic.AtomicLong;
import net.emaze.dysfunctional.contracts.dbc;
import net.emaze.dysfunctional.dispatching.delegates.TriFunction;
/**
* Proxies a ternary function monitoring its calls.
*
* @author rferranti
* @param <T1> the first parameter type
* @param <T2> the second parameter type
* @param <T3> the third parameter type
* @param <R> the result type
*/
public class TernaryMonitoringFunction<T1, T2, T3, R> implements TriFunction<T1, T2, T3, R> {
private final TriFunction<T1, T2, T3, R> nested;
private final AtomicLong calls;
public TernaryMonitoringFunction(TriFunction<T1, T2, T3, R> nested, AtomicLong calls) {
dbc.precondition(nested != null, "cannot monitor a null function");
dbc.precondition(calls != null, "cannot monitor with a null AtomicLong");
this.nested = nested;
this.calls = calls;
}
@Override
public R apply(T1 first, T2 second, T3 third) {
calls.incrementAndGet();
return nested.apply(first, second, third);
}
}
| bsd-3-clause |
ttk2/FactoryMod | src/com/github/igotyou/FactoryMod/properties/NetherFactoryProperties.java | 3525 | package com.github.igotyou.FactoryMod.properties;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import com.github.igotyou.FactoryMod.FactoryModPlugin;
import com.github.igotyou.FactoryMod.utility.ItemList;
import com.github.igotyou.FactoryMod.utility.NamedItemStack;
public class NetherFactoryProperties
{
private ItemList<NamedItemStack> constructionMaterials;
private ItemList<NamedItemStack> fuel;
private ItemList<NamedItemStack> repairMaterials;
private int energyTime;
private String name;
private int repair;
private double repairTime;
private int scalingMode;
private int scalingRadius;
private int costScalingRadius;
private boolean useFuelOnTeleport;
public NetherFactoryProperties(ItemList<NamedItemStack> constructionMaterials, ItemList<NamedItemStack> fuel, ItemList<NamedItemStack> repairMaterials,
int energyTime, String name,int repair, double repairTime, int scalingRadius, boolean useFuelOnTeleport, int costScalingRadius)
{
this.constructionMaterials = constructionMaterials;
this.fuel = fuel;
this.repairMaterials = repairMaterials;
this.energyTime = energyTime;
this.name = name;
this.repair=repair;
this.repairTime=repairTime;
this.scalingRadius = scalingRadius;
this.costScalingRadius = costScalingRadius;
this.useFuelOnTeleport = useFuelOnTeleport;
}
public int getRepair()
{
return repair;
}
public int getScalingRadius()
{
return scalingRadius;
}
public int getCostScalingRadius()
{
return costScalingRadius;
}
//0 == no scaling, 1==linear scaling, 2==exponential scaling
public int getScalingMode()
{
return scalingMode;
}
public ItemList<NamedItemStack> getConstructionMaterials()
{
return constructionMaterials;
}
public ItemList<NamedItemStack> getFuel()
{
return fuel;
}
public ItemList<NamedItemStack> getRepairMaterials()
{
return repairMaterials;
}
public int getEnergyTime()
{
return energyTime;
}
public String getName()
{
return name;
}
public static NetherFactoryProperties fromConfig(FactoryModPlugin plugin, ConfigurationSection configNetherFactory)
{
ItemList<NamedItemStack> nfFuel=plugin.getItems(configNetherFactory.getConfigurationSection("fuel"));
if(nfFuel.isEmpty())
{
nfFuel=new ItemList<NamedItemStack>();
nfFuel.add(new NamedItemStack(Material.getMaterial("COAL"),1,(short)1,"Charcoal"));
}
ConfigurationSection costs = configNetherFactory.getConfigurationSection("costs");
ItemList<NamedItemStack> nfConstructionCost=plugin.getItems(costs.getConfigurationSection("construction"));
ItemList<NamedItemStack> nfRepairCost=plugin.getItems(costs.getConfigurationSection("repair"));
int nfEnergyTime = configNetherFactory.getInt("fuel_time", 10);
int nfRepair = costs.getInt("repair_multiple",1);
String nfName = configNetherFactory.getString("name", "Nether Factory");
int repairTime = configNetherFactory.getInt("repair_time",12);
int nfScalingRadius = configNetherFactory.getInt("scaling_radius", 5000);
int costScalingRadius = configNetherFactory.getInt("scaling_radius", 5000);
boolean nfUseFuelOnTeleport = configNetherFactory.getBoolean("use_fuel_on_teleport", false);
return new NetherFactoryProperties(nfConstructionCost, nfFuel, nfRepairCost, nfEnergyTime, nfName, nfRepair, repairTime, nfScalingRadius,nfUseFuelOnTeleport, costScalingRadius);
}
public double getRepairTime()
{
return repairTime;
}
public boolean getUseFuelOnTeleport()
{
return useFuelOnTeleport;
}
}
| bsd-3-clause |
GCRC/nunaliit | nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/FieldSelectorColumn.java | 3034 | /*
Copyright (c) 2010, Geomatics and Cartographic Research Centre, Carleton
University
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Geomatics and Cartographic Research Centre,
Carleton University 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.
$Id$
*/
package ca.carleton.gcrc.dbSec;
import java.util.ArrayList;
import java.util.List;
import ca.carleton.gcrc.dbSec.impl.TypedValue;
/**
* Instance of field selector which specifies a column name
*
*/
public class FieldSelectorColumn implements FieldSelector {
private String columnName;
public FieldSelectorColumn(String columnName) {
this.columnName = columnName;
}
public String getColumnName() {
return columnName;
}
public List<ColumnData> getColumnData(
TableSchema tableSchema
) throws Exception {
List<ColumnData> columnDataList = new ArrayList<ColumnData>(1);
columnDataList.add( tableSchema.getColumnFromName(columnName) );
return columnDataList;
}
public String getQueryString(TableSchema tableSchema, Phase phase) throws Exception {
ColumnData cData = tableSchema.getColumnFromName(columnName);
// Check that we can read
if( null != cData && false == cData.isReadable() ) {
cData = null;
}
if( null == cData ) {
throw new Exception("Select Expression column "+columnName+" is not available in table "+tableSchema.getLogicalName()+ "("+tableSchema.getPhysicalName()+")");
}
return cData.getQuerySelector();
}
public List<TypedValue> getQueryValues(
TableSchema tableSchema
,Variables variables
) throws Exception {
return new ArrayList<TypedValue>();
}
public String toString() {
return "column("+columnName+")";
}
}
| bsd-3-clause |
queenBNE/javaplex | src/java/edu/stanford/math/plex4/utility/ArrayUtility.java | 3500 | package edu.stanford.math.plex4.utility;
import java.util.Arrays;
public class ArrayUtility {
public static double[][] getSubset(double[][] points, int[] indices) {
double[][] result = new double[indices.length][];
for (int i = 0; i < indices.length; i++) {
result[i] = points[indices[i]];
}
return result;
}
public static boolean isMonotoneIncreasing(int[] a) {
for (int i = 1; i < a.length; i++) {
if (a[i] <= a[i - 1]) {
return false;
}
}
return true;
}
public static int[] makeMonotone(int[] a) {
int[] temp = ArrayUtility.copyOf(a, a.length);
Arrays.sort(temp);
int k = 0, i = 0;
int[] result = new int[temp.length];
while (i < temp.length && k < result.length) {
if (k > 0 && result[k - 1] == temp[i]) {
i++;
continue;
}
result[k] = temp[i];
i++;
k++;
}
return ArrayUtility.copyOf(result, k);
}
public static int[] union(int[] a, int[] b) {
int i = 0, j = 0, k = 0;
int[] temp = new int[a.length + b.length];
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
temp[k] = a[i];
k++;
i++;
} else if (a[i] > b[j]) {
temp[k] = b[j];
k++;
j++;
} else {
temp[k] = a[i];
i++;
j++;
k++;
}
}
while (i < a.length) {
temp[k] = a[i];
i++;
k++;
}
while (j < b.length) {
temp[k] = b[j];
j++;
k++;
}
return ArrayUtility.copyOf(temp, k);
}
public static double[] copyOf(double[] array, int length) {
double[] result = new double[length];
int n = Math.min(length, array.length);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
public static int[] copyOf(int[] array, int length) {
int[] result = new int[length];
int n = Math.min(length, array.length);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
public static float[] copyOf(float[] array, int length) {
float[] result = new float[length];
int n = Math.min(length, array.length);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
public static short[] copyOf(short[] array, int length) {
short[] result = new short[length];
int n = Math.min(length, array.length);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
public static long[] copyOf(long[] array, int length) {
long[] result = new long[length];
int n = Math.min(length, array.length);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
public static boolean[] copyOf(boolean[] array, int length) {
boolean[] result = new boolean[length];
int n = Math.min(length, array.length);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
public static byte[] copyOf(byte[] array, int length) {
byte[] result = new byte[length];
int n = Math.min(length, array.length);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
public static char[] copyOf(char[] array, int length) {
char[] result = new char[length];
int n = Math.min(length, array.length);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
public static Object[] copyOf(Object[] array, int length) {
Object[] result = new Object[length];
int n = Math.min(length, array.length);
for (int i = 0; i < n; i++) {
result[i] = array[i];
}
return result;
}
}
| bsd-3-clause |
cisco/PDTool | CISAdminApi8.0.0/src/com/compositesw/services/system/util/security/GetLoginModuleListResponse.java | 1965 |
package com.compositesw.services.system.util.security;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import com.compositesw.services.system.util.common.BaseResponse;
/**
* <p>Java class for getLoginModuleListResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="getLoginModuleListResponse">
* <complexContent>
* <extension base="{http://www.compositesw.com/services/system/util/common}baseResponse">
* <sequence>
* <element name="id" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getLoginModuleListResponse", propOrder = {
"id"
})
public class GetLoginModuleListResponse
extends BaseResponse
{
protected List<String> id;
/**
* Gets the value of the id property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the id property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getId() {
if (id == null) {
id = new ArrayList<String>();
}
return this.id;
}
}
| bsd-3-clause |
emaze/emaze-dysfunctional | src/main/java/net/emaze/dysfunctional/interceptions/BinaryInterceptorChain.java | 965 | package net.emaze.dysfunctional.interceptions;
import java.util.Iterator;
import net.emaze.dysfunctional.contracts.dbc;
import java.util.function.BiFunction;
/**
*
* @param <T1>
* @param <T2>
* @param <R>
* @author rferranti
*/
public class BinaryInterceptorChain<T1, T2, R> implements BiFunction<T1, T2, R> {
private final BiFunction<T1, T2, R> composed;
public <I extends BinaryInterceptor<T1, T2>> BinaryInterceptorChain(BiFunction<T1, T2, R> innermost, Iterator<I> chain) {
dbc.precondition(innermost != null, "innermost function cannot be null");
dbc.precondition(chain != null, "chain cannot be null");
BiFunction<T1, T2, R> current = innermost;
while (chain.hasNext()) {
current = new BinaryInterceptorAdapter<>(chain.next(), current);
}
this.composed = current;
}
@Override
public R apply(T1 first, T2 second) {
return composed.apply(first, second);
}
}
| bsd-3-clause |
Artemish/jodd | jodd-mail/src/main/java/jodd/mail/SimpleAuthenticator.java | 636 | // Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.
package jodd.mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
* Performs simple authentication when the server requires it.
*/
public class SimpleAuthenticator extends Authenticator {
protected final String username;
protected final String password;
public SimpleAuthenticator(String username, String password) {
super();
this.username = username;
this.password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
| bsd-3-clause |
SvenBunge/tracee | api/src/test/java/io/tracee/BackendProviderResolverTest.java | 2584 | package io.tracee;
import io.tracee.spi.TraceeBackendProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import static io.tracee.BackendProviderResolver.EmptyBackendProviderSet;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
@RunWith(PowerMockRunner.class)
@PrepareForTest(BackendProviderResolver.class)
public class BackendProviderResolverTest {
private BackendProviderResolver out;
@Before
public void before() {
out = new BackendProviderResolver();
}
@Test
public void shouldReturnTrueIfSetIsNull() {
assertThat(out.isLookupNeeded(null), is(true));
}
@Test
public void shouldReturnTrueIfSetIsEmpty() {
assertThat(out.isLookupNeeded(Collections.<TraceeBackendProvider>emptySet()), is(true));
}
@Test
public void shouldReturnFalseIfEmptySetObjectIsPresent() {
assertThat(out.isLookupNeeded(new EmptyBackendProviderSet()), is(false));
}
@Test
public void emptyProviderSetShouldReturnEmptyIterator() {
final Iterator<TraceeBackendProvider> emptySetIter = new EmptyBackendProviderSet().iterator();
assertThat(emptySetIter.hasNext(), is(false));
}
@Test
public void emptyProviderSetShouldBeEmpty() {
assertThat(new EmptyBackendProviderSet(), empty());
}
@Test(expected = UnsupportedOperationException.class)
public void emptyProviderSetShouldBeImmutable() {
new EmptyBackendProviderSet().add(mock(TraceeBackendProvider.class));
}
@Test
public void shouldReturnClassloaderFromContext() throws Exception {
final Set<TraceeBackendProvider> contextClassloader = new HashSet<>();
contextClassloader.add(mock(TraceeBackendProvider.class));
BackendProviderResolver resolver = PowerMockito.spy(new BackendProviderResolver());
when(resolver, method(BackendProviderResolver.class, "loadProviders", ClassLoader.class))
.withArguments(BackendProviderResolver.GetClassLoader.fromContext())
.thenReturn(contextClassloader);
assertThat(resolver.getBackendProviders(), is(equalTo(contextClassloader)));
}
}
| bsd-3-clause |
hlzz/dotfiles | graphics/VTK-7.0.0/Examples/Android/JavaVTK/src/com/kitware/JavaVTK/JavaVTKLib.java | 2022 | /*=========================================================================
Program: Visualization Toolkit
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*
* Copyright (C) 2007 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.kitware.JavaVTK;
import android.view.KeyEvent;
// Wrapper for native library
public class JavaVTKLib
{
static
{
System.loadLibrary("JavaVTK");
}
/**
* @param width the current view width
* @param height the current view height
*/
public static native long init(int width, int height);
public static native void render(long udp);
public static native void onKeyEvent(long udp, boolean down, int keyCode,
int metaState,
int repeatCount);
public static native void onMotionEvent(long udp,
int action,
int eventPointer,
int numPtrs,
float [] xPos, float [] yPos, int [] ids,
int metaState);
}
| bsd-3-clause |
Artemish/jodd | jodd-petite/src/test/java/jodd/petite/tst/Foo.java | 447 | // Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.
package jodd.petite.tst;
import jodd.petite.meta.PetiteBean;
@PetiteBean
public class Foo {
public static int instanceCounter;
int counter;
public Foo() {
instanceCounter++;
counter = 0;
}
public int hello() {
return instanceCounter;
}
public int getCounter() {
return counter;
}
private String name;
public String getName() {
return name;
}
}
| bsd-3-clause |
TatianaRoma/COS576 | web/src/main/java/org/openhds/web/service/WebFlowService.java | 210 | package org.openhds.web.service;
import org.springframework.binding.message.MessageContext;
public interface WebFlowService {
void createMessage(MessageContext messageContext, String message);
}
| bsd-3-clause |
mbien/netbeans-opengl-pack | RapidShadingPrototype/src/net/java/nboglpack/visualdesigner/LogOutputPanel.java | 2274 | /*
* LogOutputPanel.java
*
* Created on 19. Juni 2007, 16:04
*/
package net.java.nboglpack.visualdesigner;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
* This Class holds a stream and displays it in a textarea
*
* @author Samuel Sperling
*/
public class LogOutputPanel extends JScrollPane {
PrintStream printStream;
JTextArea textarea;
/** Creates a new instance of LogOutputPanel */
public LogOutputPanel() {
textarea = new JTextArea();
textarea.setEditable(false);
printStream = new PrintStream(new OutputStream() {
public void write(int b) throws IOException {
textarea.append(String.valueOf((char) b));
}
});
setViewportView(textarea);
JPopupMenu contextmenu = new JPopupMenu();
textarea.setComponentPopupMenu(contextmenu);
JMenuItem mnuClear = new JMenuItem("Clear");
mnuClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textarea.setText("");
}
});
contextmenu.add(mnuClear);
}
public PrintStream getPrintStream() {
return printStream;
}
}
//class TextAreaStream extends OutputStream {
//
// private JTextArea textarea;
//// private StringWriter cachedContent;
//
// public TextAreaStream(JTextArea textarea) {
// this.textarea = textarea;
//// this.cachedContent = new StringWriter();
// }
//
// public void flushToTextArea() {
// textarea.append(cachedContent.toString());
// cachedContent.getBuffer().setLength(0);
// }
//
// public boolean hasUnflushedContent() {
// return cachedContent.getBuffer().length() > 0;
// }
//
// public void write(int b) throws IOException {
// cachedContent.write(b);
// textarea.append(String.valueOf((char) b));
// }
//
//} | bsd-3-clause |
haleystorm/gwt-leaflet | src/gwtl-core/src/main/java/org/discotools/gwt/leaflet/client/layers/vector/RectangleImpl.java | 575 | package org.discotools.gwt.leaflet.client.layers.vector;
import org.discotools.gwt.leaflet.client.jsobject.JSObject;
/**
* A class for drawing rectangle overlays on a map.
* Extends Polygon.
* Use Map#addLayer to add it to the map.
*
* @author Lionel Leiva-Marcon
*/
public class RectangleImpl extends PolygonImpl {
public static native JSObject create(JSObject latlngs, JSObject options) /*-{
return new $wnd.L.rectangle(latlngs, options);
}-*/;
public static native void setBounds(JSObject self, JSObject bounds)/*-{
self.setBounds(bounds);
}-*/;
} | bsd-3-clause |
jorenham/LifeTiles | lifetiles-sequence/src/main/java/nl/tudelft/lifetiles/sequence/controller/SequenceController.java | 11711 | package nl.tudelft.lifetiles.sequence.controller;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import java.util.Set;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import nl.tudelft.lifetiles.core.controller.AbstractController;
import nl.tudelft.lifetiles.core.util.Logging;
import nl.tudelft.lifetiles.core.util.Message;
import nl.tudelft.lifetiles.notification.controller.NotificationController;
import nl.tudelft.lifetiles.notification.model.NotificationFactory;
import nl.tudelft.lifetiles.sequence.model.Sequence;
import nl.tudelft.lifetiles.sequence.model.SequenceEntry;
import nl.tudelft.lifetiles.sequence.model.SequenceMetaParser;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* The controller of the data view.
*
* @author Joren Hammudoglu
*
*/
public class SequenceController extends AbstractController {
/**
* Shout message indicating a sequence has been set as reference.
*/
public static final Message REFERENCE_SET = Message.create("referenceSet");
/**
* The default reference sequence name.
*/
private static final String DEFAULT_REFERENCE = "TKK_REF";
/**
* The sequence table.
*/
@FXML
private TableView<SequenceEntry> sequenceTable;
/**
* The table column indiciating sequence visibility.
*/
@FXML
private TableColumn<SequenceEntry, Boolean> visibleColumn;
/**
* The table column indiciating if a sequence is the reference.
*/
@FXML
private TableColumn<SequenceEntry, Boolean> referenceColumn;
/**
* The model of sequences.
*/
private Map<String, Sequence> sequences;
/**
* Set containing the currently visible sequences.
*/
private Set<Sequence> visibleSequences;
/**
* The sequence entries for in the table.
*/
private ObservableMap<String, SequenceEntry> sequenceEntries;
/**
* The index of the reference sequence entry.
*/
private String reference;
/**
* The listeners for the visible properties.
*/
private Map<SequenceEntry, ChangeListener<? super Boolean>> visibleListeners;
/**
* {@inheritDoc}
*/
@Override
public void initialize(final URL location, final ResourceBundle resources) {
registerShoutListeners();
initializeTable();
visibleListeners = new HashMap<>();
}
/**
* Register the shout listeners.
*/
// checkstyle bug causes false positives in our assert, so suppress.
@SuppressWarnings("checkstyle:genericwhitespace")
private void registerShoutListeners() {
listen(Message.LOADED, (sender, subject, args) -> {
if (!"sequences".equals(subject)) {
return;
}
// eclipse and PMD disagree on whether parentheses are
// needed
assert args[0] instanceof Map<?, ?>;
@SuppressWarnings("unchecked")
Map<String, Sequence> sequences = (Map<String, Sequence>) args[0];
load(sequences);
});
listen(Message.FILTERED, (sender, subject, args) -> {
assert args.length == 1;
assert args[0] instanceof Set<?>;
@SuppressWarnings("unchecked")
Set<Sequence> sequences = (Set<Sequence>) args[0];
updateVisible(sequences);
});
listen(Message.RESET, (sender, subject, args) -> {
Set<Sequence> visibleSet = new HashSet<>(sequences.values());
shout(Message.FILTERED, "", visibleSet);
});
listen(Message.OPENED,
(sender, subject, args) -> {
if (!"meta".equals(subject)) {
return;
}
assert args[0] instanceof File;
SequenceMetaParser parser = new SequenceMetaParser();
try {
parser.parse((File) args[0]);
addMetaData(parser.getColumns(), parser.getData());
} catch (IOException exception) {
Logging.exception(exception);
shout(NotificationController.NOTIFY, "",
new NotificationFactory()
.getNotification(exception));
}
});
}
/**
* Add the meta data to the appropriate sequence entries.
*
* @param columns
* The column names
* @param data
* The actual data
*/
private void addMetaData(final List<String> columns,
final Map<String, Map<String, String>> data) {
for (Entry<String, Map<String, String>> sequenceMeta : data.entrySet()) {
String identifier = sequenceMeta.getKey();
if (sequenceEntries.containsKey(identifier)) {
SequenceEntry sequenceEntry = sequenceEntries.get(identifier);
sequenceEntry.setMetaData(sequenceMeta.getValue());
}
}
addMetaColumns(columns);
}
/**
* Load in the new sequences.
*
* @param sequences
* the new sequences
*/
private void load(final Map<String, Sequence> sequences) {
this.sequences = sequences;
this.visibleSequences = new HashSet<>(sequences.values());
initializeEntries(sequences);
populateTable();
}
/**
* Initialize and populate the table.
* TODO display colors
*/
private void populateTable() {
sequenceTable.setItems(FXCollections
.observableArrayList(sequenceEntries.values()));
}
/**
* Initialize the table.
*/
private void initializeTable() {
sequenceTable.setEditable(true);
visibleColumn.setCellFactory(CheckBoxTableCell
.forTableColumn(visibleColumn));
visibleColumn.setEditable(true);
referenceColumn.setCellFactory(CheckBoxTableCell
.forTableColumn(referenceColumn));
referenceColumn.setEditable(true);
}
/**
* Add the meta data columns to the table.
*
* @param columns
* the names of the columns
*/
private void addMetaColumns(final List<String> columns) {
for (String columnName : columns) {
// purpose of this method is to create these.
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
TableColumn<SequenceEntry, String> column = new TableColumn<>(
columnName);
column.setCellValueFactory(entry -> entry.getValue().metaProperty(
columnName));
sequenceTable.getColumns().add(column);
}
}
/**
* Generate Sequence entries from sequences and store them.
*
* @param sequences
* the sequences
*/
// suppress a false positive on SequenceEntry
@SuppressFBWarnings("DLS_DEAD_LOCAL_STORE")
private void initializeEntries(final Map<String, Sequence> sequences) {
sequenceEntries = FXCollections.observableHashMap();
for (Sequence sequence : sequences.values()) {
SequenceEntry sequenceEntry = SequenceEntry.fromSequence(sequence);
String identifier = sequence.getIdentifier();
if (identifier.equals(DEFAULT_REFERENCE)) {
sequenceEntry = SequenceEntry
.fromSequence(sequence, true, true);
reference = identifier;
shout(SequenceController.REFERENCE_SET, "", sequence);
} else {
sequenceEntry = SequenceEntry.fromSequence(sequence);
}
addVisibilityListener(sequenceEntry);
addReferenceListener(sequenceEntry);
sequenceEntries.put(identifier, sequenceEntry);
}
}
/**
* Add listener to the visible and reference properties of a sequence entry.
*
* @param entry
* the sequence entry
*/
private void addVisibilityListener(final SequenceEntry entry) {
final ChangeListener<? super Boolean> listener;
if (visibleListeners.containsKey(entry)) {
listener = visibleListeners.get(entry);
} else {
listener = (value, previous, current) -> {
if (previous != current) {
updateVisible(entry, current);
shout(Message.FILTERED, "", visibleSequences);
}
};
visibleListeners.put(entry, listener);
}
entry.visibleProperty().addListener(listener);
}
/**
* Remove the visibility listener from the entry.
*
* @param entry
* the entry
*/
private void removeVisibilityListener(final SequenceEntry entry) {
if (!visibleListeners.containsKey(entry)) {
throw new IllegalArgumentException("Entry " + entry.getIdentifier()
+ " has no listener");
}
entry.visibleProperty().removeListener(visibleListeners.get(entry));
}
/**
* Add listener to the sequence entry's reference property.
*
* @param entry
* the sequence entry.
*/
private void addReferenceListener(final SequenceEntry entry) {
entry.referenceProperty().addListener(
(value, previous, current) -> {
if (previous != current && !previous) {
SequenceEntry previousRef = sequenceEntries
.get(reference);
previousRef.setReference(false);
String identifier = entry.getIdentifier();
reference = identifier;
shout(SequenceController.REFERENCE_SET, "",
sequences.get(identifier));
}
});
}
/**
* Update a sequence's visiblity and shout new visible sequences.
*
* @param entry
* the sequence entry
* @param visible
* whether the sequence became visible
*/
private void updateVisible(final SequenceEntry entry, final boolean visible) {
Sequence sequence = this.sequences.get(entry.getIdentifier());
if (visible) {
visibleSequences.add(sequence);
} else {
visibleSequences.remove(sequence);
}
}
/**
* Update to the new visibles.
*
* @param visibles
* the new visibles
*/
private void updateVisible(final Set<Sequence> visibles) {
if (!sequences.values().containsAll(visibles)) {
throw new IllegalArgumentException("Unknown sequences");
}
for (Sequence sequence : sequences.values()) {
boolean visible = visibles.contains(sequence);
SequenceEntry entry = sequenceEntries.get(sequence.getIdentifier());
// temporarily stop listening to prevent circular shouting
removeVisibilityListener(entry);
entry.visibleProperty().setValue(visible);
addVisibilityListener(entry);
}
visibleSequences = visibles;
}
}
| bsd-3-clause |
mbosecke/pebble | pebble/src/main/java/com/mitchellbosecke/pebble/utils/StringLengthComparator.java | 549 | /*
* This file is part of Pebble.
*
* Copyright (c) 2014 by Mitchell Bösecke
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.mitchellbosecke.pebble.utils;
public class StringLengthComparator implements java.util.Comparator<String> {
public static StringLengthComparator INSTANCE = new StringLengthComparator();
private StringLengthComparator() {
}
public int compare(String s1, String s2) {
return s2.length() - s1.length();
}
}
| bsd-3-clause |
ds-hwang/chromium-crosswalk | chrome/android/javatests/src/org/chromium/chrome/browser/offlinepages/OfflinePageUtilsTest.java | 10222 | // Copyright 2015 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.offlinepages;
import android.content.Context;
import android.os.Environment;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.Log;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.offlinepages.OfflinePageBridge.OfflinePageModelObserver;
import org.chromium.chrome.browser.offlinepages.OfflinePageBridge.SavePageCallback;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.snackbar.SnackbarManager.SnackbarController;
import org.chromium.chrome.test.ChromeActivityTestCaseBase;
import org.chromium.components.bookmarks.BookmarkId;
import org.chromium.components.bookmarks.BookmarkType;
import org.chromium.components.offlinepages.SavePageResult;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.content.browser.test.util.CriteriaHelper;
import org.chromium.net.ConnectionType;
import org.chromium.net.NetworkChangeNotifier;
import org.chromium.net.test.EmbeddedTestServer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/** Unit tests for {@link OfflinePageUtils}. */
@CommandLineFlags.Add({ChromeSwitches.ENABLE_OFFLINE_PAGES})
public class OfflinePageUtilsTest extends ChromeActivityTestCaseBase<ChromeActivity> {
private static final String TAG = "OfflinePageUtilsTest";
private static final String TEST_PAGE = "/chrome/test/data/android/about.html";
private static final int TIMEOUT_MS = 5000;
private static final BookmarkId BOOKMARK_ID = new BookmarkId(1234, BookmarkType.NORMAL);
private OfflinePageBridge mOfflinePageBridge;
private EmbeddedTestServer mTestServer;
public OfflinePageUtilsTest() {
super(ChromeActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
// Ensure we start in an offline state.
NetworkChangeNotifier.forceConnectivityState(false);
Profile profile = Profile.getLastUsedProfile();
mOfflinePageBridge = new OfflinePageBridge(profile);
// Context context1 = getInstrumentation().getTargetContext();
Context context2 = getActivity().getBaseContext();
if (!NetworkChangeNotifier.isInitialized()) {
NetworkChangeNotifier.init(context2);
}
if (mOfflinePageBridge.isOfflinePageModelLoaded()) {
semaphore.release();
} else {
mOfflinePageBridge.addObserver(new OfflinePageModelObserver() {
@Override
public void offlinePageModelLoaded() {
semaphore.release();
mOfflinePageBridge.removeObserver(this);
}
});
}
}
});
assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
mTestServer = EmbeddedTestServer.createAndStartFileServer(
getInstrumentation().getContext(), Environment.getExternalStorageDirectory());
}
@Override
protected void tearDown() throws Exception {
mTestServer.stopAndDestroyServer();
super.tearDown();
}
/**
* Mock implementation of the SnackbarController.
*/
static class MockSnackbarController implements SnackbarController {
private int mButtonType;
private boolean mDismissed;
private static final long SNACKBAR_TIMEOUT = 7 * 1000;
private static final long POLLING_INTERVAL = 100;
public MockSnackbarController() {
super();
mButtonType = OfflinePageUtils.RELOAD_BUTTON;
mDismissed = false;
}
public void waitForSnackbarControllerToFinish() {
try {
CriteriaHelper.pollForUIThreadCriteria(
new Criteria("Failed while waiting for snackbar calls to complete.") {
@Override
public boolean isSatisfied() {
return mDismissed;
}
},
SNACKBAR_TIMEOUT, POLLING_INTERVAL);
} catch (InterruptedException e) {
fail("Failed while waiting for snackbar calls to complete." + e);
}
}
@Override
public void onAction(Object actionData) {
Log.d(TAG, "onAction for snackbar");
mButtonType = (int) actionData;
}
@Override
public void onDismissNoAction(Object actionData) {
Log.d(TAG, "onDismissNoAction for snackbar");
if (actionData == null) return;
mButtonType = (int) actionData;
mDismissed = true;
}
public int getLastButtonType() {
return mButtonType;
}
public boolean getDismissed() {
return mDismissed;
}
}
@Override
public void startMainActivity() throws InterruptedException {
startMainActivityOnBlankPage();
}
@SmallTest
public void testShowOfflineSnackbarIfNecessary() throws Exception {
// Arrange - build a mock controller for sensing.
Log.d(TAG, "Starting test");
final MockSnackbarController mockSnackbarController = new MockSnackbarController();
Log.d(TAG, "mockSnackbarController " + mockSnackbarController);
// Save an offline page.
String testUrl = mTestServer.getURL(TEST_PAGE);
loadUrl(testUrl);
savePage(SavePageResult.SUCCESS, testUrl);
// Load an offline page into the current tab. Note that this will create a
// SnackbarController when the page loads, but we use our own for the test. The one created
// here will also get the notification, but that won't interfere with our test.
List<OfflinePageItem> allPages = getAllPages();
OfflinePageItem offlinePage = allPages.get(0);
String offlinePageUrl = offlinePage.getOfflineUrl();
loadUrl(offlinePageUrl);
Log.d(TAG, "Calling showOfflineSnackbarIfNecessary from test");
// Act. This needs to be called from the UI thread.
Log.d(TAG, "before connecting NCN online state " + NetworkChangeNotifier.isOnline());
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Showing offline snackbar from UI thread");
OfflinePageUtils.showOfflineSnackbarIfNecessary(
getActivity(), getActivity().getActivityTab(), mockSnackbarController);
// Pretend that we went online, this should cause the snackbar to show.
// This call will set the isConnected call to return true.
NetworkChangeNotifier.forceConnectivityState(true);
// This call will make an event get sent with connection type CONNECTION_WIFI.
NetworkChangeNotifier.fakeNetworkConnected(0, ConnectionType.CONNECTION_WIFI);
}
});
// Wait for the snackbar to be dismissed before we check its values. The snackbar is on a
// three second timer, and will dismiss itself in about 3 seconds.
mockSnackbarController.waitForSnackbarControllerToFinish();
// Assert snackbar was shown.
Log.d(TAG, "last button = " + mockSnackbarController.getLastButtonType());
Log.d(TAG, "dismissed = " + mockSnackbarController.getDismissed());
assertEquals(OfflinePageUtils.RELOAD_BUTTON, mockSnackbarController.getLastButtonType());
assertTrue(mockSnackbarController.getDismissed());
}
// TODO(petewil): This is borrowed from OfflinePageBridge test. We should refactor
// to some common test code (including the setup).
private void savePage(final int expectedResult, final String expectedUrl)
throws InterruptedException {
final Semaphore semaphore = new Semaphore(0);
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
mOfflinePageBridge.savePage(getActivity().getActivityTab().getWebContents(),
BOOKMARK_ID, new SavePageCallback() {
@Override
public void onSavePageDone(int savePageResult, String url) {
assertEquals(
"Requested and returned URLs differ.", expectedUrl, url);
assertEquals(
"Save result incorrect.", expectedResult, savePageResult);
semaphore.release();
}
});
}
});
assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
}
private List<OfflinePageItem> getAllPages() throws InterruptedException {
final Semaphore semaphore = new Semaphore(0);
final List<OfflinePageItem> result = new ArrayList<OfflinePageItem>();
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
result.clear();
for (OfflinePageItem item : mOfflinePageBridge.getAllPages()) {
result.add(item);
}
semaphore.release();
}
});
assertTrue(semaphore.tryAcquire(TIMEOUT_MS, TimeUnit.MILLISECONDS));
return result;
}
}
| bsd-3-clause |
Azure/azure-sdk-for-java | sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/models/AppServicePlans.java | 1456 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.appservice.models;
import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.appservice.AppServiceManager;
import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsDeletingByResourceGroup;
import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsGettingById;
import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsGettingByResourceGroup;
import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsListingByResourceGroup;
import com.azure.resourcemanager.resources.fluentcore.arm.models.HasManager;
import com.azure.resourcemanager.resources.fluentcore.collection.SupportsCreating;
import com.azure.resourcemanager.resources.fluentcore.collection.SupportsDeletingById;
import com.azure.resourcemanager.resources.fluentcore.collection.SupportsListing;
/** Entry point for App Service plan management API. */
@Fluent
public interface AppServicePlans
extends SupportsCreating<AppServicePlan.DefinitionStages.Blank>,
SupportsDeletingById,
SupportsListingByResourceGroup<AppServicePlan>,
SupportsListing<AppServicePlan>,
SupportsGettingByResourceGroup<AppServicePlan>,
SupportsGettingById<AppServicePlan>,
SupportsDeletingByResourceGroup,
HasManager<AppServiceManager> {
}
| mit |
madhavanks26/com.vliesaputra.deviceinformation | src/com/vliesaputra/cordova/plugins/android/support/v4/src/api21/android/support/v4/media/MediaMetadataCompatApi21.java | 2894 | /*
* Copyright (C) 2014 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 android.support.v4.media;
import android.graphics.Bitmap;
import android.media.MediaMetadata;
import android.media.Rating;
import android.os.Parcel;
import java.util.Set;
class MediaMetadataCompatApi21 {
public static Set<String> keySet(Object metadataObj) {
return ((MediaMetadata)metadataObj).keySet();
}
public static Bitmap getBitmap(Object metadataObj, String key) {
return ((MediaMetadata)metadataObj).getBitmap(key);
}
public static long getLong(Object metadataObj, String key) {
return ((MediaMetadata)metadataObj).getLong(key);
}
public static Object getRating(Object metadataObj, String key) {
return ((MediaMetadata)metadataObj).getRating(key);
}
public static CharSequence getText(Object metadataObj, String key) {
return ((MediaMetadata) metadataObj).getText(key);
}
public static void writeToParcel(Object metadataObj, Parcel dest, int flags) {
((MediaMetadata) metadataObj).writeToParcel(dest, flags);
}
public static Object createFromParcel(Parcel in) {
return MediaMetadata.CREATOR.createFromParcel(in);
}
public static class Builder {
public static Object newInstance() {
return new MediaMetadata.Builder();
}
public static void putBitmap(Object builderObj, String key, Bitmap value) {
((MediaMetadata.Builder)builderObj).putBitmap(key, value);
}
public static void putLong(Object builderObj, String key, long value) {
((MediaMetadata.Builder)builderObj).putLong(key, value);
}
public static void putRating(Object builderObj, String key, Object ratingObj) {
((MediaMetadata.Builder)builderObj).putRating(key, (Rating)ratingObj);
}
public static void putText(Object builderObj, String key, CharSequence value) {
((MediaMetadata.Builder) builderObj).putText(key, value);
}
public static void putString(Object builderObj, String key, String value) {
((MediaMetadata.Builder) builderObj).putString(key, value);
}
public static Object build(Object builderObj) {
return ((MediaMetadata.Builder)builderObj).build();
}
}
}
| mit |
vandersonmaroni/java-design-patterns | NullObject/src/com/ibanheiz/Main.java | 501 | package com.ibanheiz;
public class Main {
public static void main(String[] args) {
// true para Person existente e false para nova Person
Person person = PersonFactory.createPerson(true);
// Aqui não será necessário uma condicional para
// verificar se Person está nula.
System.out.println("Nome: " + person.getNome());
System.out.println("Idade: " + person.getIdade());
System.out.println("CPF: " + person.getCpf());
System.out.println("------");
person.doCrazy();
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanagerhybrid/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayOperationalState.java | 1808 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for ApplicationGatewayOperationalState. */
public final class ApplicationGatewayOperationalState extends ExpandableStringEnum<ApplicationGatewayOperationalState> {
/** Static value Stopped for ApplicationGatewayOperationalState. */
public static final ApplicationGatewayOperationalState STOPPED = fromString("Stopped");
/** Static value Starting for ApplicationGatewayOperationalState. */
public static final ApplicationGatewayOperationalState STARTING = fromString("Starting");
/** Static value Running for ApplicationGatewayOperationalState. */
public static final ApplicationGatewayOperationalState RUNNING = fromString("Running");
/** Static value Stopping for ApplicationGatewayOperationalState. */
public static final ApplicationGatewayOperationalState STOPPING = fromString("Stopping");
/**
* Creates or finds a ApplicationGatewayOperationalState from its string representation.
*
* @param name a name to look for.
* @return the corresponding ApplicationGatewayOperationalState.
*/
@JsonCreator
public static ApplicationGatewayOperationalState fromString(String name) {
return fromString(name, ApplicationGatewayOperationalState.class);
}
/** @return known ApplicationGatewayOperationalState values. */
public static Collection<ApplicationGatewayOperationalState> values() {
return values(ApplicationGatewayOperationalState.class);
}
}
| mit |
MPieter/Notification-Analyser | NotificationAnalyser/MPChartLib/src/com/github/mikephil/charting/charts/PieChart.java | 20693 |
package com.github.mikephil.charting.charts;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import com.github.mikephil.charting.data.DataSet;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.utils.Utils;
import java.util.ArrayList;
/**
* View that represents a pie chart. Draws cake like slices.
*
* @author Philipp Jahoda
*/
public class PieChart extends PieRadarChartBase<PieData> {
/**
* rect object that represents the bounds of the piechart, needed for
* drawing the circle
*/
private RectF mCircleBox = new RectF();
/** array that holds the width of each pie-slice in degrees */
private float[] mDrawAngles;
/** array that holds the absolute angle in degrees of each slice */
private float[] mAbsoluteAngles;
/** if true, the white hole inside the chart will be drawn */
private boolean mDrawHole = true;
/**
* variable for the text that is drawn in the center of the pie-chart. If
* this value is null, the default is "Total Value\n + getYValueSum()"
*/
private String mCenterText = "";
/**
* indicates the size of the hole in the center of the piechart, default:
* radius / 2
*/
private float mHoleRadiusPercent = 50f;
/**
* the radius of the transparent circle next to the chart-hole in the center
*/
private float mTransparentCircleRadius = 55f;
/** if enabled, centertext is drawn */
private boolean mDrawCenterText = true;
/**
* set this to true to draw the x-values next to the values in the pie
* slices
*/
private boolean mDrawXVals = true;
/**
* if set to true, all values show up in percent instead of their real value
*/
private boolean mUsePercentValues = false;
/**
* paint for the hole in the center of the pie chart and the transparent
* circle
*/
private Paint mHolePaint;
/**
* paint object for the text that can be displayed in the center of the
* chart
*/
private Paint mCenterTextPaint;
public PieChart(Context context) {
super(context);
}
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PieChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void init() {
super.init();
// // piechart has no offsets
// mOffsetTop = 0;
// mOffsetBottom = 0;
// mOffsetLeft = 0;
// mOffsetRight = 0;
mHolePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHolePaint.setColor(Color.WHITE);
mCenterTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterTextPaint.setColor(Color.BLACK);
mCenterTextPaint.setTextSize(Utils.convertDpToPixel(12f));
mCenterTextPaint.setTextAlign(Align.CENTER);
mValuePaint.setTextSize(Utils.convertDpToPixel(13f));
mValuePaint.setColor(Color.WHITE);
mValuePaint.setTextAlign(Align.CENTER);
// for the piechart, drawing values is enabled
mDrawYValues = true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mDataNotSet)
return;
drawHighlights();
drawData();
drawAdditional();
drawValues();
drawLegend();
drawDescription();
drawCenterText();
canvas.drawBitmap(mDrawBitmap, 0, 0, mDrawPaint);
}
@Override
protected void prepareContentRect() {
super.prepareContentRect();
// prevent nullpointer when no data set
if (mDataNotSet)
return;
float diameter = getDiameter();
float boxSize = diameter / 2f;
PointF c = getCenterOffsets();
// create the circle box that will contain the pie-chart (the bounds of
// the pie-chart)
mCircleBox.set(c.x - boxSize, c.y - boxSize,
c.x + boxSize, c.y + boxSize);
}
@Override
protected void calcMinMax(boolean fixedValues) {
super.calcMinMax(fixedValues);
calcAngles();
}
/**
* calculates the needed angles for the chart slices
*/
private void calcAngles() {
mDrawAngles = new float[mCurrentData.getYValCount()];
mAbsoluteAngles = new float[mCurrentData.getYValCount()];
ArrayList<PieDataSet> dataSets = mCurrentData.getDataSets();
int cnt = 0;
for (int i = 0; i < mCurrentData.getDataSetCount(); i++) {
PieDataSet set = dataSets.get(i);
ArrayList<Entry> entries = set.getYVals();
for (int j = 0; j < entries.size(); j++) {
mDrawAngles[cnt] = calcAngle(Math.abs(entries.get(j).getVal()));
if (cnt == 0) {
mAbsoluteAngles[cnt] = mDrawAngles[cnt];
} else {
mAbsoluteAngles[cnt] = mAbsoluteAngles[cnt - 1] + mDrawAngles[cnt];
}
cnt++;
}
}
}
@Override
protected void drawHighlights() {
// if there are values to highlight and highlighnting is enabled, do it
if (mHighlightEnabled && valuesToHighlight()) {
float angle = 0f;
for (int i = 0; i < mIndicesToHightlight.length; i++) {
// get the index to highlight
int xIndex = mIndicesToHightlight[i].getXIndex();
if (xIndex >= mDrawAngles.length)
continue;
if (xIndex == 0)
angle = mRotationAngle;
else
angle = mRotationAngle + mAbsoluteAngles[xIndex - 1];
angle *= mPhaseY;
float sliceDegrees = mDrawAngles[xIndex];
float shiftangle = (float) Math.toRadians(angle + sliceDegrees / 2f);
PieDataSet set = mCurrentData
.getDataSetByIndex(mIndicesToHightlight[i]
.getDataSetIndex());
if (set == null)
continue;
float shift = set.getSelectionShift();
float xShift = shift * (float) Math.cos(shiftangle);
float yShift = shift * (float) Math.sin(shiftangle);
RectF highlighted = new RectF(mCircleBox.left + xShift, mCircleBox.top + yShift,
mCircleBox.right
+ xShift, mCircleBox.bottom + yShift);
mRenderPaint.setColor(set.getColor(xIndex));
// redefine the rect that contains the arc so that the
// highlighted pie is not cut off
mDrawCanvas.drawArc(highlighted, angle + set.getSliceSpace() / 2f, sliceDegrees
- set.getSliceSpace() / 2f, true, mRenderPaint);
}
}
}
@Override
protected void drawData() {
float angle = mRotationAngle;
ArrayList<PieDataSet> dataSets = mCurrentData.getDataSets();
int cnt = 0;
for (int i = 0; i < mCurrentData.getDataSetCount(); i++) {
PieDataSet dataSet = dataSets.get(i);
ArrayList<Entry> entries = dataSet.getYVals();
for (int j = 0; j < entries.size(); j++) {
float newangle = mDrawAngles[cnt];
float sliceSpace = dataSet.getSliceSpace();
Entry e = entries.get(j);
// draw only if the value is greater than zero
if ((Math.abs(e.getVal()) > 0.000001)) {
if (!needsHighlight(e.getXIndex(), i)) {
mRenderPaint.setColor(dataSet.getColor(j));
mDrawCanvas.drawArc(mCircleBox, angle + sliceSpace / 2f, newangle * mPhaseY
- sliceSpace / 2f, true, mRenderPaint);
}
// if(sliceSpace > 0f) {
//
// PointF outer = getPosition(c, radius, angle);
// PointF inner = getPosition(c, radius * mHoleRadiusPercent
// / 100f, angle);
// }
}
angle += newangle * mPhaseX;
cnt++;
}
}
}
/**
* checks if the given index in the given DataSet is set for highlighting or
* not
*
* @param xIndex
* @param dataSetIndex
* @return
*/
private boolean needsHighlight(int xIndex, int dataSetIndex) {
// no highlight
if (!valuesToHighlight())
return false;
for (int i = 0; i < mIndicesToHightlight.length; i++)
// check if the xvalue for the given dataset needs highlight
if (mIndicesToHightlight[i].getXIndex() == xIndex
&& mIndicesToHightlight[i].getDataSetIndex() == dataSetIndex)
return true;
return false;
}
/**
* draws the hole in the center of the chart and the transparent circle /
* hole
*/
private void drawHole() {
if (mDrawHole) {
float radius = getRadius();
PointF c = getCenterCircleBox();
int color = mHolePaint.getColor();
// draw the hole-circle
mDrawCanvas.drawCircle(c.x, c.y,
radius / 100 * mHoleRadiusPercent, mHolePaint);
if (mTransparentCircleRadius > mHoleRadiusPercent) {
// make transparent
mHolePaint.setColor(color & 0x60FFFFFF);
// draw the transparent-circle
mDrawCanvas.drawCircle(c.x, c.y,
radius / 100 * mTransparentCircleRadius, mHolePaint);
mHolePaint.setColor(color);
}
}
}
/**
* draws the description text in the center of the pie chart makes most
* sense when center-hole is enabled
*/
private void drawCenterText() {
if (mDrawCenterText && mCenterText != null) {
PointF c = getCenterCircleBox();
// get all lines from the text
String[] lines = mCenterText.split("\n");
// calculate the height for each line
float lineHeight = Utils.calcTextHeight(mCenterTextPaint, lines[0]);
float linespacing = lineHeight * 0.2f;
float totalheight = lineHeight * lines.length - linespacing * (lines.length - 1);
int cnt = lines.length;
float y = c.y;
for (int i = 0; i < lines.length; i++) {
String line = lines[lines.length - i - 1];
mDrawCanvas.drawText(line, c.x, y
+ lineHeight * cnt - totalheight / 2f,
mCenterTextPaint);
cnt--;
y -= linespacing;
}
}
}
@Override
protected void drawValues() {
// if neither xvals nor yvals are drawn, return
if (!mDrawXVals && !mDrawYValues)
return;
PointF center = getCenterCircleBox();
// get whole the radius
float r = getRadius();
float off = r / 2f;
if (mDrawHole) {
off = (r - (r / 100f * mHoleRadiusPercent)) / 2f;
}
r -= off; // offset to keep things inside the chart
ArrayList<PieDataSet> dataSets = mCurrentData.getDataSets();
int cnt = 0;
for (int i = 0; i < mCurrentData.getDataSetCount(); i++) {
PieDataSet dataSet = dataSets.get(i);
ArrayList<Entry> entries = dataSet.getYVals();
for (int j = 0; j < entries.size() * mPhaseX; j++) {
// offset needed to center the drawn text in the slice
float offset = mDrawAngles[cnt] / 2;
// calculate the text position
float x = (float) (r
* Math.cos(Math.toRadians((mRotationAngle + mAbsoluteAngles[cnt] - offset)
* mPhaseY)) + center.x);
float y = (float) (r
* Math.sin(Math.toRadians((mRotationAngle + mAbsoluteAngles[cnt] - offset)
* mPhaseY)) + center.y);
String val = "";
float value = entries.get(j).getVal();
if (mUsePercentValues)
val = mValueFormatter.getFormattedValue(Math.abs(getPercentOfTotal(value)))
+ " %";
else
val = mValueFormatter.getFormattedValue(value);
if (mDrawUnitInChart)
val = val + mUnit;
// draw everything, depending on settings
if (mDrawXVals && mDrawYValues) {
// use ascent and descent to calculate the new line
// position,
// 1.6f is the line spacing
float lineHeight = (mValuePaint.ascent() + mValuePaint.descent()) * 1.6f;
y -= lineHeight / 2;
mDrawCanvas.drawText(val, x, y, mValuePaint);
if (j < mCurrentData.getXValCount())
mDrawCanvas.drawText(mCurrentData.getXVals().get(j), x, y + lineHeight,
mValuePaint);
} else if (mDrawXVals && !mDrawYValues) {
if (j < mCurrentData.getXValCount())
mDrawCanvas.drawText(mCurrentData.getXVals().get(j), x, y, mValuePaint);
} else if (!mDrawXVals && mDrawYValues) {
mDrawCanvas.drawText(val, x, y, mValuePaint);
}
cnt++;
}
}
}
@Override
protected void drawAdditional() {
drawHole();
}
/**
* calculates the needed angle for a given value
*
* @param value
* @return
*/
private float calcAngle(float value) {
return value / mCurrentData.getYValueSum() * 360f;
}
@Override
public int getIndexForAngle(float angle) {
// take the current angle of the chart into consideration
float a = (angle - mRotationAngle + 360) % 360f;
for (int i = 0; i < mAbsoluteAngles.length; i++) {
if (mAbsoluteAngles[i] > a)
return i;
}
return -1; // return -1 if no index found
}
/**
* Returns the index of the DataSet this x-index belongs to.
*
* @param xIndex
* @return
*/
public int getDataSetIndexForIndex(int xIndex) {
ArrayList<? extends DataSet<? extends Entry>> dataSets = mCurrentData.getDataSets();
for (int i = 0; i < dataSets.size(); i++) {
if (dataSets.get(i).getEntryForXIndex(xIndex) != null)
return i;
}
return -1;
}
/**
* returns an integer array of all the different angles the chart slices
* have the angles in the returned array determine how much space (of 360°)
* each slice takes
*
* @return
*/
public float[] getDrawAngles() {
return mDrawAngles;
}
/**
* returns the absolute angles of the different chart slices (where the
* slices end)
*
* @return
*/
public float[] getAbsoluteAngles() {
return mAbsoluteAngles;
}
/**
* Sets the color for the hole that is drawn in the center of the piechart
* (if enabled).
*
* @param color
*/
public void setHoleColor(int color) {
mHolePaint.setColor(color);
}
/**
* set this to true to draw the pie center empty
*
* @param enabled
*/
public void setDrawHoleEnabled(boolean enabled) {
this.mDrawHole = enabled;
}
/**
* returns true if the hole in the center of the pie-chart is set to be
* visible, false if not
*
* @return
*/
public boolean isDrawHoleEnabled() {
return mDrawHole;
}
/**
* sets the text that is displayed in the center of the pie-chart. By
* default, the text is "Total Value + sumofallvalues"
*
* @param text
*/
public void setCenterText(String text) {
mCenterText = text;
}
/**
* returns the text that is drawn in the center of the pie-chart
*
* @return
*/
public String getCenterText() {
return mCenterText;
}
/**
* set this to true to draw the text that is displayed in the center of the
* pie chart
*
* @param enabled
*/
public void setDrawCenterText(boolean enabled) {
this.mDrawCenterText = enabled;
}
/**
* returns true if drawing the center text is enabled
*
* @return
*/
public boolean isDrawCenterTextEnabled() {
return mDrawCenterText;
}
/**
* set this to true to draw percent values instead of the actual values
*
* @param enabled
*/
public void setUsePercentValues(boolean enabled) {
mUsePercentValues = enabled;
}
/**
* returns true if drawing percent values is enabled
*
* @return
*/
public boolean isUsePercentValuesEnabled() {
return mUsePercentValues;
}
/**
* set this to true to draw the x-value text into the pie slices
*
* @param enabled
*/
public void setDrawXValues(boolean enabled) {
mDrawXVals = enabled;
}
/**
* returns true if drawing x-values is enabled, false if not
*
* @return
*/
public boolean isDrawXValuesEnabled() {
return mDrawXVals;
}
@Override
protected float getRequiredBottomOffset() {
return mLegendLabelPaint.getTextSize() * 4f;
}
@Override
protected float getRequiredBaseOffset() {
return 0;
}
@Override
public float getRadius() {
if (mCircleBox == null)
return 0;
else
return Math.min(mCircleBox.width() / 2f, mCircleBox.height() / 2f);
}
/**
* returns the circlebox, the boundingbox of the pie-chart slices
*
* @return
*/
public RectF getCircleBox() {
return mCircleBox;
}
/**
* returns the center of the circlebox
*
* @return
*/
public PointF getCenterCircleBox() {
return new PointF(mCircleBox.centerX(), mCircleBox.centerY());
}
/**
* sets the typeface for the center-text paint
*
* @param t
*/
public void setCenterTextTypeface(Typeface t) {
mCenterTextPaint.setTypeface(t);
}
/**
* Sets the size of the center text of the piechart.
*
* @param size
*/
public void setCenterTextSize(float size) {
mCenterTextPaint.setTextSize(Utils.convertDpToPixel(size));
}
/**
* sets the radius of the hole in the center of the piechart in percent of
* the maximum radius (max = the radius of the whole chart), default 50%
*
* @param size
*/
public void setHoleRadius(final float percent) {
mHoleRadiusPercent = percent;
}
/**
* sets the radius of the transparent circle that is drawn next to the hole
* in the piechart in percent of the maximum radius (max = the radius of the
* whole chart), default 55% -> means 5% larger than the center-hole by
* default
*
* @param percent
*/
public void setTransparentCircleRadius(final float percent) {
mTransparentCircleRadius = percent;
}
@Override
public void setPaint(Paint p, int which) {
super.setPaint(p, which);
switch (which) {
case PAINT_HOLE:
mHolePaint = p;
break;
case PAINT_CENTER_TEXT:
mCenterTextPaint = p;
break;
}
}
@Override
public Paint getPaint(int which) {
Paint p = super.getPaint(which);
if (p != null)
return p;
switch (which) {
case PAINT_HOLE:
return mHolePaint;
case PAINT_CENTER_TEXT:
return mCenterTextPaint;
}
return null;
}
}
| mit |
0x90sled/droidtowers | tools/proguard/src/proguard/gui/SwingUtil.java | 2553 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2011 Eric Lafortune (eric@graphics.cornell.edu)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.gui;
import javax.swing.*;
import java.lang.reflect.InvocationTargetException;
/**
* This utility class provides variants of the invocation method from the
* <code>SwingUtilities</code> class.
*
* @see SwingUtilities
* @author Eric Lafortune
*/
public class SwingUtil
{
/**
* Invokes the given Runnable in the AWT event dispatching thread,
* and waits for it to finish. This method may be called from any thread,
* including the event dispatching thread itself.
* @see SwingUtilities#invokeAndWait(Runnable)
* @param runnable the Runnable to be executed.
*/
public static void invokeAndWait(Runnable runnable)
throws InterruptedException, InvocationTargetException
{
try
{
if (SwingUtilities.isEventDispatchThread())
{
runnable.run();
}
else
{
SwingUtilities.invokeAndWait(runnable);
}
}
catch (Exception ex)
{
// Ignore any exceptions.
}
}
/**
* Invokes the given Runnable in the AWT event dispatching thread, not
* necessarily right away. This method may be called from any thread,
* including the event dispatching thread itself.
* @see SwingUtilities#invokeLater(Runnable)
* @param runnable the Runnable to be executed.
*/
public static void invokeLater(Runnable runnable)
{
if (SwingUtilities.isEventDispatchThread())
{
runnable.run();
}
else
{
SwingUtilities.invokeLater(runnable);
}
}
}
| mit |
navalev/azure-sdk-for-java | sdk/logic/mgmt-v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountImpl.java | 2434 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.logic.v2016_06_01.implementation;
import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl;
import com.microsoft.azure.management.logic.v2016_06_01.IntegrationAccount;
import rx.Observable;
import com.microsoft.azure.management.logic.v2016_06_01.IntegrationAccountSku;
class IntegrationAccountImpl extends GroupableResourceCoreImpl<IntegrationAccount, IntegrationAccountInner, IntegrationAccountImpl, LogicManager> implements IntegrationAccount, IntegrationAccount.Definition, IntegrationAccount.Update {
IntegrationAccountImpl(String name, IntegrationAccountInner inner, LogicManager manager) {
super(name, inner, manager);
}
@Override
public Observable<IntegrationAccount> createResourceAsync() {
IntegrationAccountsInner client = this.manager().inner().integrationAccounts();
return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner())
.map(innerToFluentMap(this));
}
@Override
public Observable<IntegrationAccount> updateResourceAsync() {
IntegrationAccountsInner client = this.manager().inner().integrationAccounts();
return client.updateAsync(this.resourceGroupName(), this.name(), this.inner())
.map(innerToFluentMap(this));
}
@Override
protected Observable<IntegrationAccountInner> getInnerAsync() {
IntegrationAccountsInner client = this.manager().inner().integrationAccounts();
return client.getByResourceGroupAsync(this.resourceGroupName(), this.name());
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
@Override
public Object properties() {
return this.inner().properties();
}
@Override
public IntegrationAccountSku sku() {
return this.inner().sku();
}
@Override
public IntegrationAccountImpl withProperties(Object properties) {
this.inner().withProperties(properties);
return this;
}
@Override
public IntegrationAccountImpl withSku(IntegrationAccountSku sku) {
this.inner().withSku(sku);
return this;
}
}
| mit |
Microsoft/ace | src/android/framework/PolyQuadraticBezierSegment.java | 651 | //-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
package Windows.UI.Xaml.Controls;
public class PolyQuadraticBezierSegment extends PathSegment {
PointCollection _points;
public PointCollection getPoints() {
return _points;
}
public void setPoints(PointCollection points) {
_points = points;
}
}
| mit |
JUMA-IO/JUMA-Samples | ST/light_switch/android/src/com/example/juswitch/CustomDialog.java | 7088 | package com.example.juswitch;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class CustomDialog extends Dialog implements android.view.View.OnClickListener,OnItemClickListener{
public static final int DIALOG_TYPE_SCAN = 0;
public static final int DIALOG_TYPE_EDIT_MESSAGE = 1;
public static final int DIALOG_TYPE_SEND_MESSAGE = 2;
private EditText etInput = null;
private ListView lvDevice = null;
private Button positiveButton = null, negativeButton = null;
private Context context = null;
private int type = -1;
private MessageCallback messageCallback = null;
private Callback scanCallback = null;
private CustomListViewAdapter lvDeviceAdapter = null;
private List<HashMap<String, Object>> deviceInfo = null;
private android.view.View.OnClickListener positiveButtonClickListener = null;
private android.view.View.OnClickListener negativeButtonClickListener = null;
private int id = -1;
public CustomDialog(Context context, int type) {
super(context);
this.context = context;
this.type = type;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Window win = getWindow();
win.requestFeature(Window.FEATURE_NO_TITLE);
if(type == DIALOG_TYPE_SCAN)
this.setContentView(R.layout.dialog_scan);
else if(type == DIALOG_TYPE_EDIT_MESSAGE || type == DIALOG_TYPE_SEND_MESSAGE)
this.setContentView(R.layout.dialog_edit);
initView();
}
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
}
@Override
public void dismiss() {
// TODO Auto-generated method stub
super.dismiss();
}
private void initView(){
if(type == DIALOG_TYPE_SCAN){
etInput = (EditText) findViewById(R.id.etInputName);
lvDevice = (ListView) findViewById(R.id.lvDevice);
positiveButton = (Button) findViewById(R.id.btnStartScan);
negativeButton = (Button) findViewById(R.id.btnCancelScan);
deviceInfo = new ArrayList<HashMap<String,Object>>();
lvDeviceAdapter = new CustomListViewAdapter(context, deviceInfo);
lvDevice.setAdapter(lvDeviceAdapter);
lvDevice.setOnItemClickListener(this);
}else if(type == DIALOG_TYPE_EDIT_MESSAGE || type == DIALOG_TYPE_SEND_MESSAGE){
etInput = (EditText) findViewById(R.id.etInputMessage);
positiveButton = (Button) findViewById(R.id.btnOk);
negativeButton = (Button) findViewById(R.id.btnCancel);
}
if(positiveButtonClickListener != null)
positiveButton.setOnClickListener(positiveButtonClickListener);
else
positiveButton.setOnClickListener(this);
if(negativeButtonClickListener != null)
negativeButton.setOnClickListener(negativeButtonClickListener);
else
negativeButton.setOnClickListener(this);
}
public void setMessageCallback(MessageCallback messageCallback){
this.messageCallback = messageCallback;
}
public void setScanCallback(Callback scanCallback){
this.scanCallback = scanCallback;
}
public void setId(int id){
this.id = id;
}
@Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(context).registerReceiver(receiver, getIntentFilter());
}
private IntentFilter getIntentFilter(){
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_DEVICE_DISCOVERED);
return filter;
}
@Override
protected void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver);
}
public void setPositiveButton(android.view.View.OnClickListener listener){
positiveButtonClickListener = listener;
}
public void setNegativeButton(android.view.View.OnClickListener listener){
negativeButtonClickListener = listener;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStartScan:
String name = etInput.getText().toString();
if(scanCallback != null)
scanCallback.onName(name);
etInput.setText("");
break;
case R.id.btnCancelScan:
dismiss();
break;
case R.id.btnOk:
if(messageCallback != null){
String hexStr = etInput.getText().toString();
if(hexStr.length() % 2 == 1){
hexStr = hexStr + "0";
}
if(hexStr.length() > 0)
messageCallback.onMessage(hexToByte(hexStr), id);
}
dismiss();
break;
case R.id.btnCancel:
dismiss();
break;
}
}
@SuppressWarnings("unchecked")
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
HashMap<String, Object> map = (HashMap<String, Object>) lvDeviceAdapter.getItem(arg2);
String name = (String) map.get(MainActivity.NAME_STR);
UUID uuid = UUID.fromString((String)map.get(MainActivity.UUID_STR));
if(scanCallback != null)
scanCallback.onDevice(uuid, name);
dismiss();
}
public interface MessageCallback{
void onMessage(byte[] message, int id);
}
public interface Callback{
void onName(String name);
void onDevice(UUID uuid, String name);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String uuid = intent.getStringExtra(MainActivity.UUID_STR);
String name = intent.getStringExtra(MainActivity.NAME_STR);
int rssi = intent.getIntExtra(MainActivity.RSSI_STR, 0);
addDeviceInfo(name, uuid, rssi);
}
};
private void addDeviceInfo(String name, String uuid, int rssi){
if(deviceInfo != null && lvDeviceAdapter != null){
boolean isContain = false;
HashMap<String , Object> map = new HashMap<String, Object>();
map.put(MainActivity.NAME_STR, name);
map.put(MainActivity.UUID_STR, uuid);
map.put(MainActivity.RSSI_STR, rssi);
for (int i = 0; i < deviceInfo.size(); i++) {
if(deviceInfo.get(i).get(MainActivity.UUID_STR).equals(uuid)){
deviceInfo.remove(i);
deviceInfo.add(i, map);
isContain = true;
}
if(isContain)
break;
}
if(!isContain){
deviceInfo.add(map);
}
lvDeviceAdapter.notifyDataSetChanged();
}
}
@SuppressLint("UseValueOf")
public static final byte[] hexToByte(String hex)throws IllegalArgumentException {
if (hex.length() % 2 != 0) {
throw new IllegalArgumentException();
}
char[] arr = hex.toCharArray();
byte[] b = new byte[hex.length() / 2];
for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
String swap = "" + arr[i++] + arr[i];
int byteint = Integer.parseInt(swap, 16) & 0xFF;
b[j] = new Integer(byteint).byteValue();
}
return b;
}
}
| mit |
Jochen-A-Fuerbacher/jenkins | core/src/main/java/hudson/ExtensionComponent.java | 3615 | /*
* The MIT License
*
* Copyright (c) 2010, Kohsuke Kawaguchi
*
* 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 hudson;
import hudson.model.Describable;
import hudson.model.Descriptor;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.ExtensionFilter;
/**
* Discovered {@link Extension} object with a bit of metadata for Hudson.
* This is a plain value object.
*
* @author Kohsuke Kawaguchi
* @since 1.356
* @see ExtensionFinder
* @see ExtensionFilter
*/
public class ExtensionComponent<T> implements Comparable<ExtensionComponent<T>> {
private static final Logger LOG = Logger.getLogger(ExtensionComponent.class.getName());
private final T instance;
private final double ordinal;
public ExtensionComponent(T instance, double ordinal) {
this.instance = instance;
this.ordinal = ordinal;
}
public ExtensionComponent(T instance, Extension annotation) {
this(instance,annotation.ordinal());
}
public ExtensionComponent(T instance) {
this(instance,0);
}
/**
* See {@link Extension#ordinal()}. Used to sort extensions.
*/
public double ordinal() {
return ordinal;
}
/**
* The instance of the discovered extension.
*
* @return never null.
*/
public T getInstance() {
return instance;
}
/**
* Checks if this component is a {@link Descriptor} describing the given type
*
* For example, {@code component.isDescriptorOf(Builder.class)}
*/
public boolean isDescriptorOf(Class<? extends Describable> c) {
return instance instanceof Descriptor && ((Descriptor)instance).isSubTypeOf(c);
}
/**
* Sort {@link ExtensionComponent}s in the descending order of {@link #ordinal()}.
*/
public int compareTo(ExtensionComponent<T> that) {
double a = this.ordinal();
double b = that.ordinal();
if (a>b) return -1;
if (a<b) return 1;
// make the order bit more deterministic among extensions of the same ordinal
if (this.instance instanceof Descriptor && that.instance instanceof Descriptor) {
try {
return Util.fixNull(((Descriptor)this.instance).getDisplayName()).compareTo(Util.fixNull(((Descriptor)that.instance).getDisplayName()));
} catch (RuntimeException | LinkageError x) {
LOG.log(Level.WARNING, null, x);
}
}
return this.instance.getClass().getName().compareTo(that.instance.getClass().getName());
}
}
| mit |
XristosMallios/cache | exareme-master/src/test/java/madgik/exareme/master/queryProcessor/graph/RandomParameters.java | 3215 | /**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.master.queryProcessor.graph;
import madgik.exareme.utils.statistics.Zipf;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.util.Properties;
/**
* @author Herald Kllapi <br>
* University of Athens /
* Department of Informatics and Telecommunications.
* @since 1.0
*/
public class RandomParameters implements Serializable {
public double z;
public double operatorType;
public double[] runTime = null;
public double[] cpuUtil = null;
public int[] memory = null;
public double[] dataout = null;
public Zipf runTimeDist = null;
public Zipf cpuUtilDist = null;
public Zipf memoryDist = null;
public Zipf dataoutDist = null;
public RandomParameters(double z, double operatorType, double[] runTime, double[] cpuUtil,
int[] memory, double[] dataout) {
this.z = z;
this.operatorType = operatorType;
this.runTime = runTime;
this.cpuUtil = cpuUtil;
this.memory = memory;
this.dataout = dataout;
this.runTimeDist = new Zipf(this.runTime.length, z);
this.cpuUtilDist = new Zipf(this.cpuUtil.length, z);
this.memoryDist = new Zipf(this.memory.length, z);
this.dataoutDist = new Zipf(this.dataout.length, z);
}
@SuppressWarnings("static-access") public static RandomParameters parseFile(String url)
throws IOException {
Properties properties = new Properties();
properties.load(new URL(url).openStream());
double z = Double.parseDouble(properties.getProperty("z"));
double operatorType = Double.parseDouble(properties.getProperty("type"));
String[] runtimeStr = properties.getProperty("time").split(",");
double[] runTime = new double[runtimeStr.length];
for (int i = 0; i < runTime.length; i++) {
runTime[i] = Double.parseDouble(runtimeStr[i]);
}
String[] cpuUtilStr = properties.getProperty("cpu").split(",");
double[] cpuUtil = new double[cpuUtilStr.length];
for (int i = 0; i < cpuUtil.length; i++) {
cpuUtil[i] = Double.parseDouble(cpuUtilStr[i]);
}
String[] memoryStr = properties.getProperty("mem").split(",");
int[] memory = new int[memoryStr.length];
for (int i = 0; i < memory.length; i++) {
memory[i] = Integer.parseInt(memoryStr[i]);
}
String[] dataoutStr = properties.getProperty("data").split(",");
double[] dataout = new double[dataoutStr.length];
for (int i = 0; i < dataout.length; i++) {
dataout[i] = Double.parseDouble(dataoutStr[i]);
}
RandomParameters parameters =
new RandomParameters(z, operatorType, runTime, cpuUtil, memory, dataout);
return parameters;
}
public void resetRandom(long seed) {
this.runTimeDist = new Zipf(this.runTime.length, z, seed);
this.cpuUtilDist = new Zipf(this.cpuUtil.length, z, seed);
this.memoryDist = new Zipf(this.memory.length, z, seed);
this.dataoutDist = new Zipf(this.dataout.length, z, seed);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/compute/mgmt-v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/RollingUpgradeStatusInfoInner.java | 2498 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.compute.v2017_03_30.implementation;
import com.microsoft.azure.management.compute.v2017_03_30.RollingUpgradePolicy;
import com.microsoft.azure.management.compute.v2017_03_30.RollingUpgradeRunningStatus;
import com.microsoft.azure.management.compute.v2017_03_30.RollingUpgradeProgressInfo;
import com.microsoft.azure.management.compute.v2017_03_30.ApiError;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.Resource;
/**
* The status of the latest virtual machine scale set rolling upgrade.
*/
@JsonFlatten
public class RollingUpgradeStatusInfoInner extends Resource {
/**
* The rolling upgrade policies applied for this upgrade.
*/
@JsonProperty(value = "properties.policy", access = JsonProperty.Access.WRITE_ONLY)
private RollingUpgradePolicy policy;
/**
* Information about the current running state of the overall upgrade.
*/
@JsonProperty(value = "properties.runningStatus", access = JsonProperty.Access.WRITE_ONLY)
private RollingUpgradeRunningStatus runningStatus;
/**
* Information about the number of virtual machine instances in each
* upgrade state.
*/
@JsonProperty(value = "properties.progress", access = JsonProperty.Access.WRITE_ONLY)
private RollingUpgradeProgressInfo progress;
/**
* Error details for this upgrade, if there are any.
*/
@JsonProperty(value = "properties.error", access = JsonProperty.Access.WRITE_ONLY)
private ApiError error;
/**
* Get the policy value.
*
* @return the policy value
*/
public RollingUpgradePolicy policy() {
return this.policy;
}
/**
* Get the runningStatus value.
*
* @return the runningStatus value
*/
public RollingUpgradeRunningStatus runningStatus() {
return this.runningStatus;
}
/**
* Get the progress value.
*
* @return the progress value
*/
public RollingUpgradeProgressInfo progress() {
return this.progress;
}
/**
* Get the error value.
*
* @return the error value
*/
public ApiError error() {
return this.error;
}
}
| mit |
v1v/jenkins | cli/src/main/java/hudson/cli/CLI.java | 20305 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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 hudson.cli;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.parse;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.cli.client.Messages;
import jakarta.websocket.ClientEndpointConfig;
import jakarta.websocket.Endpoint;
import jakarta.websocket.EndpointConfig;
import jakarta.websocket.Session;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.glassfish.tyrus.client.ClientManager;
import org.glassfish.tyrus.client.ClientProperties;
import org.glassfish.tyrus.container.jdk.client.JdkClientContainer;
/**
* CLI entry point to Jenkins.
*/
public class CLI {
private CLI() {}
/**
* Make sure the connection is open against Jenkins server.
*
* @param c The open connection.
* @throws IOException in case of communication problem.
* @throws NotTalkingToJenkinsException when connection is not made to Jenkins service.
*/
/*package*/ static void verifyJenkinsConnection(URLConnection c) throws IOException {
if (c.getHeaderField("X-Hudson") == null && c.getHeaderField("X-Jenkins") == null)
throw new NotTalkingToJenkinsException(c);
}
/*package*/ static final class NotTalkingToJenkinsException extends IOException {
NotTalkingToJenkinsException(String s) {
super(s);
}
NotTalkingToJenkinsException(URLConnection c) {
super("There's no Jenkins running at " + c.getURL().toString());
}
}
public static void main(final String[] _args) throws Exception {
try {
System.exit(_main(_args));
} catch (NotTalkingToJenkinsException ex) {
System.err.println(ex.getMessage());
System.exit(3);
} catch (Throwable t) {
// if the CLI main thread die, make sure to kill the JVM.
t.printStackTrace();
System.exit(-1);
}
}
private enum Mode { HTTP, SSH, WEB_SOCKET }
public static int _main(String[] _args) throws Exception {
List<String> args = Arrays.asList(_args);
PrivateKeyProvider provider = new PrivateKeyProvider();
String url = System.getenv("JENKINS_URL");
if (url == null)
url = System.getenv("HUDSON_URL");
boolean noKeyAuth = false;
// TODO perhaps allow mode to be defined by environment variable too (assuming $JENKINS_USER_ID can be used for -user)
Mode mode = null;
String user = null;
String auth = null;
String bearer = null;
String userIdEnv = System.getenv("JENKINS_USER_ID");
String tokenEnv = System.getenv("JENKINS_API_TOKEN");
boolean strictHostKey = false;
while (!args.isEmpty()) {
String head = args.get(0);
if (head.equals("-version")) {
System.out.println("Version: " + computeVersion());
return 0;
}
if (head.equals("-http")) {
if (mode != null) {
printUsage("-http clashes with previously defined mode " + mode);
return -1;
}
mode = Mode.HTTP;
args = args.subList(1, args.size());
continue;
}
if (head.equals("-ssh")) {
if (mode != null) {
printUsage("-ssh clashes with previously defined mode " + mode);
return -1;
}
mode = Mode.SSH;
args = args.subList(1, args.size());
continue;
}
if (head.equals("-webSocket")) {
if (mode != null) {
printUsage("-webSocket clashes with previously defined mode " + mode);
return -1;
}
mode = Mode.WEB_SOCKET;
args = args.subList(1, args.size());
continue;
}
if (head.equals("-remoting")) {
printUsage("-remoting mode is no longer supported");
return -1;
}
if (head.equals("-s") && args.size() >= 2) {
url = args.get(1);
args = args.subList(2, args.size());
continue;
}
if (head.equals("-noCertificateCheck")) {
LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new NoCheckTrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
// bypass host name check, too.
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
@SuppressFBWarnings(value = "WEAK_HOSTNAME_VERIFIER", justification = "User set parameter to skip verifier.")
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
args = args.subList(1, args.size());
continue;
}
if (head.equals("-noKeyAuth")) {
noKeyAuth = true;
args = args.subList(1, args.size());
continue;
}
if (head.equals("-i") && args.size() >= 2) {
File f = getFileFromArguments(args);
if (!f.exists()) {
printUsage(Messages.CLI_NoSuchFileExists(f));
return -1;
}
provider.readFrom(f);
args = args.subList(2, args.size());
continue;
}
if (head.equals("-strictHostKey")) {
strictHostKey = true;
args = args.subList(1, args.size());
continue;
}
if (head.equals("-user") && args.size() >= 2) {
user = args.get(1);
args = args.subList(2, args.size());
continue;
}
if (head.equals("-auth") && args.size() >= 2) {
auth = args.get(1);
args = args.subList(2, args.size());
continue;
}
if (head.equals("-bearer") && args.size() >= 2) {
bearer = args.get(1);
args = args.subList(2, args.size());
continue;
}
if (head.equals("-logger") && args.size() >= 2) {
Level level = parse(args.get(1));
for (Handler h : Logger.getLogger("").getHandlers()) {
h.setLevel(level);
}
for (Logger logger : new Logger[] {LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER, Logger.getLogger("org.apache.sshd")}) { // perhaps also Channel
logger.setLevel(level);
}
args = args.subList(2, args.size());
continue;
}
break;
}
if (url == null) {
printUsage(Messages.CLI_NoURL());
return -1;
}
if (auth != null && bearer != null) {
LOGGER.warning("-auth and -bearer are mutually exclusive");
}
if (auth == null && bearer == null) {
// -auth option not set
if (StringUtils.isNotBlank(userIdEnv) && StringUtils.isNotBlank(tokenEnv)) {
auth = StringUtils.defaultString(userIdEnv).concat(":").concat(StringUtils.defaultString(tokenEnv));
} else if (StringUtils.isNotBlank(userIdEnv) || StringUtils.isNotBlank(tokenEnv)) {
printUsage(Messages.CLI_BadAuth());
return -1;
} // Otherwise, none credentials were set
}
if (!url.endsWith("/")) {
url += '/';
}
if (args.isEmpty())
args = Collections.singletonList("help"); // default to help
if (mode == null) {
mode = Mode.HTTP;
}
LOGGER.log(FINE, "using connection mode {0}", mode);
if (user != null && auth != null) {
LOGGER.warning("-user and -auth are mutually exclusive");
}
if (mode == Mode.SSH) {
if (user == null) {
// TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same?
LOGGER.warning("-user required when using -ssh");
return -1;
}
if (!noKeyAuth && !provider.hasKeys()) {
provider.readFromDefaultLocations();
}
return SSHCLI.sshConnection(url, user, args, provider, strictHostKey);
}
if (strictHostKey) {
LOGGER.warning("-strictHostKey meaningful only with -ssh");
}
if (noKeyAuth) {
LOGGER.warning("-noKeyAuth meaningful only with -ssh");
}
if (user != null) {
LOGGER.warning("Warning: -user ignored unless using -ssh");
}
CLIConnectionFactory factory = new CLIConnectionFactory();
String userInfo = new URL(url).getUserInfo();
if (userInfo != null) {
factory = factory.basicAuth(userInfo);
} else if (auth != null) {
factory = factory.basicAuth(auth.startsWith("@") ? readAuthFromFile(auth).trim() : auth);
} else if (bearer != null) {
factory = factory.bearerAuth(bearer.startsWith("@") ? readAuthFromFile(bearer).trim() : bearer);
}
if (mode == Mode.HTTP) {
return plainHttpConnection(url, args, factory);
}
if (mode == Mode.WEB_SOCKET) {
return webSocketConnection(url, args, factory);
}
throw new AssertionError();
}
@SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.")
private static String readAuthFromFile(String auth) throws IOException {
return FileUtils.readFileToString(new File(auth.substring(1)), Charset.defaultCharset());
}
@SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.")
private static File getFileFromArguments(List<String> args) {
return new File(args.get(1));
}
private static int webSocketConnection(String url, List<String> args, CLIConnectionFactory factory) throws Exception {
LOGGER.fine(() -> "Trying to connect to " + url + " via plain protocol over WebSocket");
class CLIEndpoint extends Endpoint {
@Override
public void onOpen(Session session, EndpointConfig config) {}
}
class Authenticator extends ClientEndpointConfig.Configurator {
@Override
public void beforeRequest(Map<String, List<String>> headers) {
if (factory.authorization != null) {
headers.put("Authorization", Collections.singletonList(factory.authorization));
}
}
}
ClientManager client = ClientManager.createClient(JdkClientContainer.class.getName()); // ~ ContainerProvider.getWebSocketContainer()
client.getProperties().put(ClientProperties.REDIRECT_ENABLED, true); // https://tyrus-project.github.io/documentation/1.13.1/index/tyrus-proprietary-config.html#d0e1775
Session session = client.connectToServer(new CLIEndpoint(), ClientEndpointConfig.Builder.create().configurator(new Authenticator()).build(), URI.create(url.replaceFirst("^http", "ws") + "cli/ws"));
PlainCLIProtocol.Output out = new PlainCLIProtocol.Output() {
@Override
public void send(byte[] data) throws IOException {
session.getBasicRemote().sendBinary(ByteBuffer.wrap(data));
}
@Override
public void close() throws IOException {
session.close();
}
};
try (ClientSideImpl connection = new ClientSideImpl(out)) {
session.addMessageHandler(InputStream.class, is -> {
try {
connection.handle(new DataInputStream(is));
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
}
});
connection.start(args);
return connection.exit();
}
}
private static int plainHttpConnection(String url, List<String> args, CLIConnectionFactory factory) throws IOException, InterruptedException {
LOGGER.log(FINE, "Trying to connect to {0} via plain protocol over HTTP", url);
FullDuplexHttpStream streams = new FullDuplexHttpStream(new URL(url), "cli?remoting=false", factory.authorization);
try (ClientSideImpl connection = new ClientSideImpl(new PlainCLIProtocol.FramedOutput(streams.getOutputStream()))) {
connection.start(args);
InputStream is = streams.getInputStream();
if (is.read() != 0) { // cf. FullDuplexHttpService
throw new IOException("expected to see initial zero byte; perhaps you are connecting to an old server which does not support -http?");
}
new PlainCLIProtocol.FramedReader(connection, is).start();
new Thread("ping") { // JENKINS-46659
@Override
public void run() {
try {
Thread.sleep(PING_INTERVAL);
while (!connection.complete) {
LOGGER.fine("sending ping");
connection.sendEncoding(Charset.defaultCharset().name()); // no-op at this point
Thread.sleep(PING_INTERVAL);
}
} catch (IOException | InterruptedException x) {
LOGGER.log(Level.WARNING, null, x);
}
}
}.start();
return connection.exit();
}
}
private static final class ClientSideImpl extends PlainCLIProtocol.ClientSide {
volatile boolean complete;
private int exit = -1;
ClientSideImpl(PlainCLIProtocol.Output out) {
super(out);
}
void start(List<String> args) throws IOException {
for (String arg : args) {
sendArg(arg);
}
sendEncoding(Charset.defaultCharset().name());
sendLocale(Locale.getDefault().toString());
sendStart();
new Thread("input reader") {
@Override
public void run() {
try {
final OutputStream stdin = streamStdin();
byte[] buf = new byte[60_000]; // less than 64Kb frame size for WS
while (!complete) {
int len = System.in.read(buf);
if (len == -1) {
break;
} else {
stdin.write(buf, 0, len);
}
}
sendEndStdin();
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
}
}
}.start();
}
@Override
protected synchronized void onExit(int code) {
this.exit = code;
finished();
}
@Override
protected void onStdout(byte[] chunk) throws IOException {
System.out.write(chunk);
}
@Override
protected void onStderr(byte[] chunk) throws IOException {
System.err.write(chunk);
}
@Override
protected void handleClose() {
finished();
}
private synchronized void finished() {
complete = true;
notifyAll();
}
synchronized int exit() throws InterruptedException {
while (!complete) {
wait();
}
return exit;
}
}
private static String computeVersion() {
Properties props = new Properties();
try {
InputStream is = CLI.class.getResourceAsStream("/jenkins/cli/jenkins-cli-version.properties");
if (is != null) {
try {
props.load(is);
} finally {
is.close();
}
}
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
}
return props.getProperty("version", "?");
}
/**
* Loads RSA/DSA private key in a PEM format into {@link KeyPair}.
*/
public static KeyPair loadKey(File f, String passwd) throws IOException, GeneralSecurityException {
return PrivateKeyProvider.loadKey(f, passwd);
}
public static KeyPair loadKey(File f) throws IOException, GeneralSecurityException {
return loadKey(f, null);
}
/**
* Loads RSA/DSA private key in a PEM format into {@link KeyPair}.
*/
public static KeyPair loadKey(String pemString, String passwd) throws IOException, GeneralSecurityException {
return PrivateKeyProvider.loadKey(pemString, passwd);
}
public static KeyPair loadKey(String pemString) throws IOException, GeneralSecurityException {
return loadKey(pemString, null);
}
/** For access from {@code HelpCommand}. */
static String usage() {
return Messages.CLI_Usage();
}
private static void printUsage(String msg) {
if (msg != null) System.out.println(msg);
System.err.println(usage());
}
static final Logger LOGGER = Logger.getLogger(CLI.class.getName());
private static final int PING_INTERVAL = Integer.getInteger(CLI.class.getName() + ".pingInterval", 3_000); // JENKINS-59267
}
| mit |
caseif/SpongeAPI | src/main/java/org/spongepowered/api/data/manipulator/ColoredData.java | 1867 | /*
* 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;
import java.awt.Color;
/**
* Represents item data that uses colors. Examples may include leather armor,
* dyes, and wool blocks.
*/
public interface ColoredData extends SingleValueData<Color, ColoredData> {
/**
* Gets the color data for this item stack.
*
* @return The color data for this item stack
*/
Color getColor();
/**
* Sets the color data for this item stack.
*
* @param color The color data for this item stack
* @return This instance, for chaining
*/
ColoredData setColor(Color color);
}
| mit |
mhe504/MigSim | src/org/cloudbus/cloudsim/container/resourceAllocators/PowerContainerAllocationPolicySimple.java | 515 | package org.cloudbus.cloudsim.container.resourceAllocators;
import org.cloudbus.cloudsim.container.core.Container;
import java.util.List;
import java.util.Map;
/**
* Created by sareh on 16/07/15.
*/
public class PowerContainerAllocationPolicySimple extends PowerContainerAllocationPolicy {
public PowerContainerAllocationPolicySimple() {
super();
}
@Override
public List<Map<String, Object>> optimizeAllocation(List<? extends Container> containerList) {
return null;
}
}
| mit |
XristosMallios/cache | exareme-worker/src/main/java/madgik/exareme/worker/art/remote/RetryPolicyFactory.java | 1470 | /**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.worker.art.remote;
import madgik.exareme.utils.properties.AdpProperties;
import madgik.exareme.utils.units.Metrics;
import madgik.exareme.worker.art.remote.retryPolicy.ConstantTimeIntervalPolicy;
import madgik.exareme.worker.art.remote.retryPolicy.RandomTimeIntervalPolicy;
import madgik.exareme.worker.art.remote.retryPolicy.RetryNTimesPolicy;
/**
* @author Herald Kllapi <br>
* University of Athens /
* Department of Informatics and Telecommunications.
* @since 1.0
*/
public class RetryPolicyFactory {
private static RetryPolicy defaultRetryPolicy = null;
private static RetryPolicy socketRetryPolicy = null;
static {
int retryTimes = AdpProperties.getArtProps().getInt("art.rmi.retryTimes");
int retryPeriod_ms = (int) (AdpProperties.getArtProps().getFloat("art.rmi.retryPeriod_sec")
* (float) Metrics.MiliSec);
defaultRetryPolicy = new RetryPolicy(new RetryNTimesPolicy(retryTimes),
new ConstantTimeIntervalPolicy(retryPeriod_ms));
socketRetryPolicy = new RetryPolicy(new RetryNTimesPolicy(retryTimes),
new RandomTimeIntervalPolicy(retryPeriod_ms));
}
private RetryPolicyFactory() {
}
public static RetryPolicy defaultRetryPolicy() {
return defaultRetryPolicy;
}
public static RetryPolicy socketRetryPolicy() {
return socketRetryPolicy;
}
}
| mit |
virtix/mut4j | lib/slf4j-1.6.0/integration/src/test/java/org/slf4j/StringPrintStream.java | 665 | package org.slf4j;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class StringPrintStream extends PrintStream {
public static final String LINE_SEP = System.getProperty("line.separator");
PrintStream other;
List stringList = new ArrayList();
public StringPrintStream(PrintStream ps) {
super(ps);
other = ps;
}
public void print(String s) {
other.print(s);
stringList.add(s);
}
public void println(String s) {
other.println(s);
stringList.add(s);
}
public void println(Object o) {
other.println(o);
stringList.add(o);
}
}
| mit |
akochurov/mxcache | mxcache-runtime/src/main/java/com/maxifier/mxcache/impl/wrapping/WrapperFactoryImpl.java | 1401 | /*
* Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved.
*/
package com.maxifier.mxcache.impl.wrapping;
import com.maxifier.mxcache.caches.Cache;
import com.maxifier.mxcache.caches.Calculable;
import com.maxifier.mxcache.impl.MutableStatistics;
import com.maxifier.mxcache.impl.caches.storage.StorageHolder;
import com.maxifier.mxcache.storage.Storage;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* @author Alexander Kochurov (alexander.kochurov@maxifier.com)
*/
class WrapperFactoryImpl implements WrapperFactory {
private final Constructor<? extends Cache> constructor;
public WrapperFactoryImpl(Constructor<? extends Cache> constructor) {
this.constructor = constructor;
}
@SuppressWarnings({ "unchecked" })
@Override
public Cache wrap(Object owner, Calculable calculable, Storage storage, MutableStatistics statistics) {
try {
Cache cache = constructor.newInstance(owner, calculable, statistics);
((StorageHolder)cache).setStorage(storage);
return cache;
} catch (InstantiationException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
}
| mit |
ctron/kura | kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/server/GwtCertificatesServiceImpl.java | 9431 | /*******************************************************************************
* Copyright (c) 2011, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech
*******************************************************************************/
package org.eclipse.kura.web.server;
import static java.lang.String.format;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore.Entry;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStore.SecretKeyEntry;
import java.security.KeyStore.TrustedCertificateEntry;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.eclipse.kura.KuraException;
import org.eclipse.kura.certificate.CertificatesService;
import org.eclipse.kura.certificate.KuraCertificateEntry;
import org.eclipse.kura.core.keystore.util.KeystoreRemoteService;
import org.eclipse.kura.security.keystore.KeystoreService;
import org.eclipse.kura.web.server.util.ServiceLocator;
import org.eclipse.kura.web.shared.GwtKuraErrorCode;
import org.eclipse.kura.web.shared.GwtKuraException;
import org.eclipse.kura.web.shared.model.GwtKeystoreEntry;
import org.eclipse.kura.web.shared.model.GwtKeystoreEntry.Kind;
import org.eclipse.kura.web.shared.model.GwtXSRFToken;
import org.eclipse.kura.web.shared.service.GwtCertificatesService;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GwtCertificatesServiceImpl extends OsgiRemoteServiceServlet implements GwtCertificatesService {
/**
*
*/
private static final long serialVersionUID = 7402961266449489433L;
private static final String KURA_SERVICE_PID = "kura.service.pid";
private static final Logger logger = LoggerFactory.getLogger(GwtCertificatesServiceImpl.class);
@Override
public void storeKeyPair(GwtXSRFToken xsrfToken, String keyStorePid, String privateKey, String publicCert,
String alias) throws GwtKuraException {
checkXSRFToken(xsrfToken);
try {
PrivateKeyEntry entry = KeystoreRemoteService.createPrivateKey(privateKey, publicCert);
if (entry == null) {
throw new GwtKuraException(GwtKuraErrorCode.ILLEGAL_ARGUMENT);
} else {
final String filter = format("(%s=%s)", KURA_SERVICE_PID, keyStorePid);
final Collection<ServiceReference<KeystoreService>> keystoreServiceReferences = ServiceLocator
.getInstance().getServiceReferences(KeystoreService.class, filter);
for (ServiceReference<KeystoreService> reference : keystoreServiceReferences) {
KeystoreService keystoreService = ServiceLocator.getInstance().getService(reference);
keystoreService.setEntry(alias, entry);
ServiceLocator.getInstance().ungetService(reference);
}
}
} catch (GeneralSecurityException | IOException | KuraException | IllegalStateException
| IllegalArgumentException e) {
logger.error("Error storing keypair with alias: {} in keystore: {}", alias, keyStorePid, e);
throw new GwtKuraException(GwtKuraErrorCode.ILLEGAL_ARGUMENT);
}
}
@Override
public void storeCertificate(GwtXSRFToken xsrfToken, String keyStorePid, String certificate, String alias)
throws GwtKuraException {
checkXSRFToken(xsrfToken);
try {
X509Certificate[] certs = KeystoreRemoteService.parsePublicCertificates(certificate);
if (certs.length == 0) {
throw new GwtKuraException(GwtKuraErrorCode.ILLEGAL_ARGUMENT);
} else {
CertificatesService certificateService = ServiceLocator.getInstance()
.getService(CertificatesService.class);
for (X509Certificate cert : certs) {
certificateService.addCertificate(new KuraCertificateEntry(keyStorePid, alias, cert));
}
}
} catch (CertificateException e) {
logger.error("Error parsing certificate with alias: {} in keystore: {}", alias, keyStorePid, e);
throw new GwtKuraException(GwtKuraErrorCode.CERTIFICATE_PARSE_FAILURE);
} catch (KuraException | IllegalStateException | IllegalArgumentException e) {
logger.error("Error storing certificate with alias: {} in keystore: {}. Illegal argument provided.", alias,
keyStorePid, e);
throw new GwtKuraException(GwtKuraErrorCode.ILLEGAL_ARGUMENT);
}
}
@Override
public List<String> listKeystoreServicePids() throws GwtKuraException {
final List<String> pids = new ArrayList<>();
ServiceLocator.withAllServiceReferences(null, (r, c) -> {
final Object pid = r.getProperties().get(KURA_SERVICE_PID);
if (pid instanceof String) {
pids.add((String) pid);
}
}, KeystoreService.class);
return pids;
}
@Override
public List<GwtKeystoreEntry> listEntries() throws GwtKuraException {
List<GwtKeystoreEntry> result = new ArrayList<>();
ServiceLocator.withAllServiceReferences(KeystoreService.class, null, (ref, context) -> {
final Object kuraServicePid = ref.getProperty(KURA_SERVICE_PID);
if (!(kuraServicePid instanceof String)) {
return;
}
final KeystoreService service = context.getService(ref);
if (service == null) {
return;
}
try {
for (final Map.Entry<String, Entry> e : service.getEntries().entrySet()) {
final Kind kind;
Date validityStartDate = null;
Date validityEndDate = null;
if (e.getValue() instanceof PrivateKeyEntry) {
kind = Kind.KEY_PAIR;
PrivateKeyEntry pke = (PrivateKeyEntry) e.getValue();
Certificate[] chain = pke.getCertificateChain();
if (chain.length > 0) {
Certificate leaf = chain[chain.length - 1];
if (leaf instanceof X509Certificate) {
validityStartDate = ((X509Certificate) leaf).getNotBefore();
validityEndDate = ((X509Certificate) leaf).getNotAfter();
}
}
} else if (e.getValue() instanceof TrustedCertificateEntry) {
kind = Kind.TRUSTED_CERT;
Certificate cert = ((TrustedCertificateEntry) e.getValue()).getTrustedCertificate();
if (cert instanceof X509Certificate) {
validityStartDate = ((X509Certificate) cert).getNotBefore();
validityEndDate = ((X509Certificate) cert).getNotAfter();
}
} else if (e.getValue() instanceof SecretKeyEntry) {
kind = Kind.SECRET_KEY;
} else {
continue;
}
result.add(new GwtKeystoreEntry(e.getKey(), (String) kuraServicePid, kind, validityStartDate,
validityEndDate));
}
} catch (KuraException keystoreException) {
logger.error("Error while accessing keystore file of Keystore Service {}: {}", (String) kuraServicePid,
keystoreException.getMessage(), keystoreException);
} finally {
context.ungetService(ref);
}
});
return result;
}
@Override
public void removeEntry(GwtXSRFToken xsrfToken, GwtKeystoreEntry entry) throws GwtKuraException {
final Collection<ServiceReference<KeystoreService>> refs = ServiceLocator.getInstance().getServiceReferences(
KeystoreService.class, "(" + KURA_SERVICE_PID + "=" + entry.getKeystoreName() + ")");
if (refs.isEmpty()) {
throw new GwtKuraException(GwtKuraErrorCode.ILLEGAL_ARGUMENT);
}
for (final ServiceReference<KeystoreService> ref : refs) {
final KeystoreService service = ServiceLocator.getInstance().getService(ref);
if (service == null) {
continue;
}
try {
try {
service.deleteEntry(entry.getAlias());
} catch (Exception e) {
logger.error("Error deleting keystore entry: {}", entry.getAlias(), e);
throw new GwtKuraException(GwtKuraErrorCode.INTERNAL_ERROR);
}
} finally {
ServiceLocator.getInstance().ungetService(ref);
}
}
}
} | epl-1.0 |
sguan-actuate/birt | data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/ICancellable.java | 782 |
/*******************************************************************************
* Copyright (c) 2004, 2008 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.impl;
import org.eclipse.birt.data.engine.core.DataException;
/**
*
*/
public interface ICancellable
{
public boolean doCancel();
public void cancel();
public DataException collectException();
}
| epl-1.0 |