repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
konduruvijaykumar/spring-cloud-boot-lab | lab4/lab4-restservice-article/src/main/java/org/pjay/Lab4RestserviceArticleApplication.java | 428 | package org.pjay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class Lab4RestserviceArticleApplication {
public static void main(String[] args) {
SpringApplication.run(Lab4RestserviceArticleApplication.class, args);
}
}
| apache-2.0 |
spring-cloud/spring-cloud-bus | spring-cloud-bus/src/main/java/org/springframework/cloud/bus/endpoint/AbstractBusEndpoint.java | 1632 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bus.endpoint;
import org.springframework.cloud.bus.event.Destination;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
/**
* @author Spencer Gibb
*/
public class AbstractBusEndpoint {
private ApplicationEventPublisher publisher;
private String appId;
private final Destination.Factory destinationFactory;
public AbstractBusEndpoint(ApplicationEventPublisher publisher, String appId,
Destination.Factory destinationFactory) {
this.publisher = publisher;
this.appId = appId;
this.destinationFactory = destinationFactory;
}
protected String getInstanceId() {
return this.appId;
}
protected Destination.Factory getDestinationFactory() {
return this.destinationFactory;
}
protected Destination getDestination(String original) {
return destinationFactory.getDestination(original);
}
protected void publish(ApplicationEvent event) {
this.publisher.publishEvent(event);
}
}
| apache-2.0 |
eFaps/eFaps-Kernel | src/main/java/org/efaps/db/databases/information/ColumnInformation.java | 4999 | /*
* Copyright 2003 - 2016 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.efaps.db.databases.information;
import java.io.Serializable;
import java.util.Set;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.efaps.db.Context;
import org.efaps.db.databases.AbstractDatabase.ColumnType;
/**
* Stores information about one column within a table.
*
* @author The eFaps Team
*
*/
public class ColumnInformation
implements Serializable
{
/**
* Needed for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Name of column in upper case.
*
* @see #getName()
*/
private final String name;
/**
* Set of all possible column types.
*/
private final Set<ColumnType> types;
/**
* Size of the column (for string). Precision of the column (for decimal).
*
* @see #getSize()
*/
private final int size;
/**
* Could the column have a null value?
*
* @see #isNullable
*/
private final boolean isNullable;
/**
* Scale of the column.
*
* @see #getScale()
*/
private final int scale;
/**
* Constructor to initialize all instance variables.
*
* @param _name name of column
* @param _types set of column types
* @param _size size/precision of column
* @param _scale sclae of the column
* @param _isNullable is the column nullable
*/
protected ColumnInformation(final String _name,
final Set<ColumnType> _types,
final int _size,
final int _scale,
final boolean _isNullable)
{
this.name = _name.toUpperCase();
this.types = _types;
this.size = _size;
this.scale = _scale;
this.isNullable = _isNullable;
}
/**
* Returns for the first found column type in {@link #types} the related
* SQL select statement for null values.
*
* @return null value select statement
* @see #types
*/
public String getNullValueSelect()
{
String ret = null;
if (!this.types.isEmpty()) {
ret = Context.getDbType().getNullValueSelect(this.types.iterator().next());
}
return ret;
}
/**
* This is the getter method for instance variable {@link #name}. The
* method returns the name of the SQL column always in upper case.
*
* @return value of instance variable {@link #name}
* @see #name
*/
public String getName()
{
return this.name;
}
/**
* This is the getter method for instance variable {@link #size}. The
* method returns the column size for this column (used for string column
* types defined for eFaps column types {@link ColumnType#STRING_LONG} and
* {@link ColumnType#STRING_SHORT}). Or the precision/size of this column
* (used for decimal column types {@link ColumnType#DECIMAL})
*
* @return value of instance variable {@link #size}
* @see #size
*/
public int getSize()
{
return this.size;
}
/**
* Getter method for instance variable {@link #scale}. The method
* returns the scale of this column.
* The information is used for decimal column types
* {@link ColumnType#DECIMAL}.
*
* @return value of instance variable {@link #scale}
*/
public int getScale()
{
return this.scale;
}
/**
* This is the getter method for instance variable {@link #isNullable}. The
* method returns true, if a null value for this column is allowed.
*
* @return value of instance variable {@link #isNullable}
* @see #isNullable
*/
public boolean isNullable()
{
return this.isNullable;
}
/**
* Returns string representation of this class instance. The information
* includes {@link #name}, {@link #types}, {@link #size} and
* {@link #isNullable}.
* @return String representation of this class
*/
@Override
public String toString()
{
return new ToStringBuilder(this)
.append("name", this.name)
.append("types", this.types)
.append("size", this.size)
.append("isNullable", this.isNullable)
.toString();
}
}
| apache-2.0 |
jdgwartney/vsphere-ws | java/JAXWS/samples/com/vmware/vim25/RefreshStorageDrsRecommendationRequestType.java | 2323 |
package com.vmware.vim25;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for RefreshStorageDrsRecommendationRequestType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RefreshStorageDrsRecommendationRequestType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="_this" type="{urn:vim25}ManagedObjectReference"/>
* <element name="pod" type="{urn:vim25}ManagedObjectReference"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RefreshStorageDrsRecommendationRequestType", propOrder = {
"_this",
"pod"
})
public class RefreshStorageDrsRecommendationRequestType {
@XmlElement(required = true)
protected ManagedObjectReference _this;
@XmlElement(required = true)
protected ManagedObjectReference pod;
/**
* Gets the value of the this property.
*
* @return
* possible object is
* {@link ManagedObjectReference }
*
*/
public ManagedObjectReference getThis() {
return _this;
}
/**
* Sets the value of the this property.
*
* @param value
* allowed object is
* {@link ManagedObjectReference }
*
*/
public void setThis(ManagedObjectReference value) {
this._this = value;
}
/**
* Gets the value of the pod property.
*
* @return
* possible object is
* {@link ManagedObjectReference }
*
*/
public ManagedObjectReference getPod() {
return pod;
}
/**
* Sets the value of the pod property.
*
* @param value
* allowed object is
* {@link ManagedObjectReference }
*
*/
public void setPod(ManagedObjectReference value) {
this.pod = value;
}
}
| apache-2.0 |
PkayJava/overlap2d-dev | src/main/java/com/o2d/pkayjava/editor/view/ui/followers/SubFollower.java | 647 | package com.o2d.pkayjava.editor.view.ui.followers;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.puremvc.patterns.observer.Notification;
/**
* Created by CyberJoe on 7/2/2015.
*/
public abstract class SubFollower extends Actor {
protected Entity entity;
public SubFollower(Entity entity) {
setItem(entity);
create();
update();
}
private void setItem(Entity entity) {
this.entity = entity;
}
public void handleNotification(Notification notification) {
}
public abstract void create();
public abstract void update();
}
| apache-2.0 |
shivpun/spring-framework | spring-web/src/main/java/org/springframework/http/client/OkHttp3ClientHttpRequest.java | 1878 | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.client;
import java.io.IOException;
import java.net.URI;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
/**
* {@link ClientHttpRequest} implementation that uses OkHttp 3.x to execute requests.
*
* <p>Created via the {@link OkHttp3ClientHttpRequestFactory}.
*
* @author Luciano Leggieri
* @author Arjen Poutsma
* @author Roy Clarkson
* @since 4.3
*/
class OkHttp3ClientHttpRequest extends AbstractBufferingClientHttpRequest {
private final OkHttpClient client;
private final URI uri;
private final HttpMethod method;
public OkHttp3ClientHttpRequest(OkHttpClient client, URI uri, HttpMethod method) {
this.client = client;
this.uri = uri;
this.method = method;
}
@Override
public HttpMethod getMethod() {
return this.method;
}
@Override
public URI getURI() {
return this.uri;
}
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] content) throws IOException {
Request request = OkHttp3ClientHttpRequestFactory.buildRequest(headers, content, this.uri, this.method);
return new OkHttp3ClientHttpResponse(this.client.newCall(request).execute());
}
}
| apache-2.0 |
lmjacksoniii/hazelcast | hazelcast/src/main/java/com/hazelcast/config/EntryListenerConfigReadOnly.java | 1883 | /*
* Copyright (c) 2008-2016, 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.config;
import com.hazelcast.core.EntryListener;
import java.util.EventListener;
/**
* Configuration for EntryListener(Read Only)
*
* @deprecated this class will be removed in 3.8; it is meant for internal usage only.
*/
public class EntryListenerConfigReadOnly extends EntryListenerConfig {
public EntryListenerConfigReadOnly(EntryListenerConfig config) {
super(config);
}
@Override
public EntryListenerConfig setImplementation(EntryListener implementation) {
throw new UnsupportedOperationException("this config is read-only");
}
@Override
public EntryListenerConfig setLocal(boolean local) {
throw new UnsupportedOperationException("this config is read-only");
}
@Override
public EntryListenerConfig setIncludeValue(boolean includeValue) {
throw new UnsupportedOperationException("this config is read-only");
}
@Override
public ListenerConfig setClassName(String className) {
throw new UnsupportedOperationException("this config is read-only");
}
@Override
public ListenerConfig setImplementation(EventListener implementation) {
throw new UnsupportedOperationException("this config is read-only");
}
}
| apache-2.0 |
aureagle/cassandra | src/java/org/apache/cassandra/db/compaction/CompactionManager.java | 75751 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db.compaction;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.LongPredicate;
import java.util.stream.Collectors;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.TabularData;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.*;
import com.google.common.util.concurrent.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.util.concurrent.FastThreadLocal;
import org.apache.cassandra.cache.AutoSavingCache;
import org.apache.cassandra.concurrent.DebuggableThreadPoolExecutor;
import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutor;
import org.apache.cassandra.concurrent.NamedThreadFactory;
import org.apache.cassandra.repair.ValidationPartitionIterator;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.schema.Schema;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.compaction.CompactionInfo.Holder;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.db.lifecycle.SSTableIntervalTree;
import org.apache.cassandra.db.lifecycle.SSTableSet;
import org.apache.cassandra.db.lifecycle.View;
import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.db.view.ViewBuilderTask;
import org.apache.cassandra.dht.Bounds;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.index.SecondaryIndexBuilder;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.ISSTableScanner;
import org.apache.cassandra.io.sstable.IndexSummaryRedistribution;
import org.apache.cassandra.io.sstable.SSTableRewriter;
import org.apache.cassandra.io.sstable.SnapshotDeletingTask;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.io.sstable.format.SSTableWriter;
import org.apache.cassandra.io.sstable.metadata.MetadataCollector;
import org.apache.cassandra.io.sstable.metadata.StatsMetadata;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.metrics.CompactionMetrics;
import org.apache.cassandra.metrics.TableMetrics;
import org.apache.cassandra.repair.Validator;
import org.apache.cassandra.schema.CompactionParams.TombstoneOption;
import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.streaming.PreviewKind;
import org.apache.cassandra.utils.*;
import org.apache.cassandra.utils.Throwables;
import org.apache.cassandra.utils.concurrent.Refs;
import static java.util.Collections.singleton;
/**
* <p>
* A singleton which manages a private executor of ongoing compactions.
* </p>
* Scheduling for compaction is accomplished by swapping sstables to be compacted into
* a set via Tracker. New scheduling attempts will ignore currently compacting
* sstables.
*/
public class CompactionManager implements CompactionManagerMBean
{
public static final String MBEAN_OBJECT_NAME = "org.apache.cassandra.db:type=CompactionManager";
private static final Logger logger = LoggerFactory.getLogger(CompactionManager.class);
public static final CompactionManager instance;
public static final int NO_GC = Integer.MIN_VALUE;
public static final int GC_ALL = Integer.MAX_VALUE;
// A thread local that tells us if the current thread is owned by the compaction manager. Used
// by CounterContext to figure out if it should log a warning for invalid counter shards.
public static final FastThreadLocal<Boolean> isCompactionManager = new FastThreadLocal<Boolean>()
{
@Override
protected Boolean initialValue()
{
return false;
}
};
static
{
instance = new CompactionManager();
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try
{
mbs.registerMBean(instance, new ObjectName(MBEAN_OBJECT_NAME));
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
private final CompactionExecutor executor = new CompactionExecutor();
private final CompactionExecutor validationExecutor = new ValidationExecutor();
private final static CompactionExecutor cacheCleanupExecutor = new CacheCleanupExecutor();
private final CompactionExecutor viewBuildExecutor = new ViewBuildExecutor();
private final CompactionMetrics metrics = new CompactionMetrics(executor, validationExecutor, viewBuildExecutor);
@VisibleForTesting
final Multiset<ColumnFamilyStore> compactingCF = ConcurrentHashMultiset.create();
private final RateLimiter compactionRateLimiter = RateLimiter.create(Double.MAX_VALUE);
public CompactionMetrics getMetrics()
{
return metrics;
}
/**
* Gets compaction rate limiter.
* Rate unit is bytes per sec.
*
* @return RateLimiter with rate limit set
*/
public RateLimiter getRateLimiter()
{
setRate(DatabaseDescriptor.getCompactionThroughputMbPerSec());
return compactionRateLimiter;
}
/**
* Sets the rate for the rate limiter. When compaction_throughput_mb_per_sec is 0 or node is bootstrapping,
* this sets the rate to Double.MAX_VALUE bytes per second.
* @param throughPutMbPerSec throughput to set in mb per second
*/
public void setRate(final double throughPutMbPerSec)
{
double throughput = throughPutMbPerSec * 1024.0 * 1024.0;
// if throughput is set to 0, throttling is disabled
if (throughput == 0 || StorageService.instance.isBootstrapMode())
throughput = Double.MAX_VALUE;
if (compactionRateLimiter.getRate() != throughput)
compactionRateLimiter.setRate(throughput);
}
/**
* Call this whenever a compaction might be needed on the given columnfamily.
* It's okay to over-call (within reason) if a call is unnecessary, it will
* turn into a no-op in the bucketing/candidate-scan phase.
*/
public List<Future<?>> submitBackground(final ColumnFamilyStore cfs)
{
if (cfs.isAutoCompactionDisabled())
{
logger.trace("Autocompaction is disabled");
return Collections.emptyList();
}
/**
* If a CF is currently being compacted, and there are no idle threads, submitBackground should be a no-op;
* we can wait for the current compaction to finish and re-submit when more information is available.
* Otherwise, we should submit at least one task to prevent starvation by busier CFs, and more if there
* are idle threads stil. (CASSANDRA-4310)
*/
int count = compactingCF.count(cfs);
if (count > 0 && executor.getActiveCount() >= executor.getMaximumPoolSize())
{
logger.trace("Background compaction is still running for {}.{} ({} remaining). Skipping",
cfs.keyspace.getName(), cfs.name, count);
return Collections.emptyList();
}
logger.trace("Scheduling a background task check for {}.{} with {}",
cfs.keyspace.getName(),
cfs.name,
cfs.getCompactionStrategyManager().getName());
List<Future<?>> futures = new ArrayList<>(1);
Future<?> fut = executor.submitIfRunning(new BackgroundCompactionCandidate(cfs), "background task");
if (!fut.isCancelled())
futures.add(fut);
else
compactingCF.remove(cfs);
return futures;
}
public boolean isCompacting(Iterable<ColumnFamilyStore> cfses)
{
for (ColumnFamilyStore cfs : cfses)
if (!cfs.getTracker().getCompacting().isEmpty())
return true;
return false;
}
/**
* Shutdowns both compaction and validation executors, cancels running compaction / validation,
* and waits for tasks to complete if tasks were not cancelable.
*/
public void forceShutdown()
{
// shutdown executors to prevent further submission
executor.shutdown();
validationExecutor.shutdown();
viewBuildExecutor.shutdown();
// interrupt compactions and validations
for (Holder compactionHolder : CompactionMetrics.getCompactions())
{
compactionHolder.stop();
}
// wait for tasks to terminate
// compaction tasks are interrupted above, so it shuold be fairy quick
// until not interrupted tasks to complete.
for (ExecutorService exec : Arrays.asList(executor, validationExecutor, viewBuildExecutor))
{
try
{
if (!exec.awaitTermination(1, TimeUnit.MINUTES))
logger.warn("Failed to wait for compaction executors shutdown");
}
catch (InterruptedException e)
{
logger.error("Interrupted while waiting for tasks to be terminated", e);
}
}
}
public void finishCompactionsAndShutdown(long timeout, TimeUnit unit) throws InterruptedException
{
executor.shutdown();
executor.awaitTermination(timeout, unit);
}
// the actual sstables to compact are not determined until we run the BCT; that way, if new sstables
// are created between task submission and execution, we execute against the most up-to-date information
class BackgroundCompactionCandidate implements Runnable
{
private final ColumnFamilyStore cfs;
BackgroundCompactionCandidate(ColumnFamilyStore cfs)
{
compactingCF.add(cfs);
this.cfs = cfs;
}
public void run()
{
try
{
logger.trace("Checking {}.{}", cfs.keyspace.getName(), cfs.name);
if (!cfs.isValid())
{
logger.trace("Aborting compaction for dropped CF");
return;
}
CompactionStrategyManager strategy = cfs.getCompactionStrategyManager();
AbstractCompactionTask task = strategy.getNextBackgroundTask(getDefaultGcBefore(cfs, FBUtilities.nowInSeconds()));
if (task == null)
{
logger.trace("No tasks available");
return;
}
task.execute(metrics);
}
finally
{
compactingCF.remove(cfs);
}
submitBackground(cfs);
}
}
/**
* Run an operation over all sstables using jobs threads
*
* @param cfs the column family store to run the operation on
* @param operation the operation to run
* @param jobs the number of threads to use - 0 means use all available. It never uses more than concurrent_compactors threads
* @return status of the operation
* @throws ExecutionException
* @throws InterruptedException
*/
@SuppressWarnings("resource")
private AllSSTableOpStatus parallelAllSSTableOperation(final ColumnFamilyStore cfs, final OneSSTableOperation operation, int jobs, OperationType operationType) throws ExecutionException, InterruptedException
{
List<LifecycleTransaction> transactions = new ArrayList<>();
try (LifecycleTransaction compacting = cfs.markAllCompacting(operationType))
{
if (compacting == null)
return AllSSTableOpStatus.UNABLE_TO_CANCEL;
Iterable<SSTableReader> sstables = Lists.newArrayList(operation.filterSSTables(compacting));
if (Iterables.isEmpty(sstables))
{
logger.info("No sstables to {} for {}.{}", operationType.name(), cfs.keyspace.getName(), cfs.name);
return AllSSTableOpStatus.SUCCESSFUL;
}
List<Future<?>> futures = new ArrayList<>();
for (final SSTableReader sstable : sstables)
{
final LifecycleTransaction txn = compacting.split(singleton(sstable));
transactions.add(txn);
Callable<Object> callable = new Callable<Object>()
{
@Override
public Object call() throws Exception
{
operation.execute(txn);
return this;
}
};
Future<?> fut = executor.submitIfRunning(callable, "paralell sstable operation");
if (!fut.isCancelled())
futures.add(fut);
else
return AllSSTableOpStatus.ABORTED;
if (jobs > 0 && futures.size() == jobs)
{
Future<?> f = FBUtilities.waitOnFirstFuture(futures);
futures.remove(f);
}
}
FBUtilities.waitOnFutures(futures);
assert compacting.originals().isEmpty();
return AllSSTableOpStatus.SUCCESSFUL;
}
finally
{
Throwable fail = Throwables.close(null, transactions);
if (fail != null)
logger.error("Failed to cleanup lifecycle transactions", fail);
}
}
private static interface OneSSTableOperation
{
Iterable<SSTableReader> filterSSTables(LifecycleTransaction transaction);
void execute(LifecycleTransaction input) throws IOException;
}
public enum AllSSTableOpStatus
{
SUCCESSFUL(0),
ABORTED(1),
UNABLE_TO_CANCEL(2);
public final int statusCode;
AllSSTableOpStatus(int statusCode)
{
this.statusCode = statusCode;
}
}
public AllSSTableOpStatus performScrub(final ColumnFamilyStore cfs, final boolean skipCorrupted, final boolean checkData,
int jobs)
throws InterruptedException, ExecutionException
{
return performScrub(cfs, skipCorrupted, checkData, false, jobs);
}
public AllSSTableOpStatus performScrub(final ColumnFamilyStore cfs, final boolean skipCorrupted, final boolean checkData,
final boolean reinsertOverflowedTTL, int jobs)
throws InterruptedException, ExecutionException
{
return parallelAllSSTableOperation(cfs, new OneSSTableOperation()
{
@Override
public Iterable<SSTableReader> filterSSTables(LifecycleTransaction input)
{
return input.originals();
}
@Override
public void execute(LifecycleTransaction input)
{
scrubOne(cfs, input, skipCorrupted, checkData, reinsertOverflowedTTL);
}
}, jobs, OperationType.SCRUB);
}
public AllSSTableOpStatus performVerify(ColumnFamilyStore cfs, Verifier.Options options) throws InterruptedException, ExecutionException
{
assert !cfs.isIndex();
return parallelAllSSTableOperation(cfs, new OneSSTableOperation()
{
@Override
public Iterable<SSTableReader> filterSSTables(LifecycleTransaction input)
{
return input.originals();
}
@Override
public void execute(LifecycleTransaction input)
{
verifyOne(cfs, input.onlyOne(), options);
}
}, 0, OperationType.VERIFY);
}
public AllSSTableOpStatus performSSTableRewrite(final ColumnFamilyStore cfs, final boolean excludeCurrentVersion, int jobs) throws InterruptedException, ExecutionException
{
return parallelAllSSTableOperation(cfs, new OneSSTableOperation()
{
@Override
public Iterable<SSTableReader> filterSSTables(LifecycleTransaction transaction)
{
List<SSTableReader> sortedSSTables = Lists.newArrayList(transaction.originals());
Collections.sort(sortedSSTables, SSTableReader.sizeComparator.reversed());
Iterator<SSTableReader> iter = sortedSSTables.iterator();
while (iter.hasNext())
{
SSTableReader sstable = iter.next();
if (excludeCurrentVersion && sstable.descriptor.version.equals(sstable.descriptor.getFormat().getLatestVersion()))
{
transaction.cancel(sstable);
iter.remove();
}
}
return sortedSSTables;
}
@Override
public void execute(LifecycleTransaction txn)
{
AbstractCompactionTask task = cfs.getCompactionStrategyManager().getCompactionTask(txn, NO_GC, Long.MAX_VALUE);
task.setUserDefined(true);
task.setCompactionType(OperationType.UPGRADE_SSTABLES);
task.execute(metrics);
}
}, jobs, OperationType.UPGRADE_SSTABLES);
}
public AllSSTableOpStatus performCleanup(final ColumnFamilyStore cfStore, int jobs) throws InterruptedException, ExecutionException
{
assert !cfStore.isIndex();
Keyspace keyspace = cfStore.keyspace;
if (!StorageService.instance.isJoined())
{
logger.info("Cleanup cannot run before a node has joined the ring");
return AllSSTableOpStatus.ABORTED;
}
// if local ranges is empty, it means no data should remain
final Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(keyspace.getName());
final boolean hasIndexes = cfStore.indexManager.hasIndexes();
return parallelAllSSTableOperation(cfStore, new OneSSTableOperation()
{
@Override
public Iterable<SSTableReader> filterSSTables(LifecycleTransaction transaction)
{
List<SSTableReader> sortedSSTables = Lists.newArrayList(transaction.originals());
Collections.sort(sortedSSTables, SSTableReader.sizeComparator);
return sortedSSTables;
}
@Override
public void execute(LifecycleTransaction txn) throws IOException
{
CleanupStrategy cleanupStrategy = CleanupStrategy.get(cfStore, ranges, FBUtilities.nowInSeconds());
doCleanupOne(cfStore, txn, cleanupStrategy, ranges, hasIndexes);
}
}, jobs, OperationType.CLEANUP);
}
public AllSSTableOpStatus performGarbageCollection(final ColumnFamilyStore cfStore, TombstoneOption tombstoneOption, int jobs) throws InterruptedException, ExecutionException
{
assert !cfStore.isIndex();
return parallelAllSSTableOperation(cfStore, new OneSSTableOperation()
{
@Override
public Iterable<SSTableReader> filterSSTables(LifecycleTransaction transaction)
{
Iterable<SSTableReader> originals = transaction.originals();
if (cfStore.getCompactionStrategyManager().onlyPurgeRepairedTombstones())
originals = Iterables.filter(originals, SSTableReader::isRepaired);
List<SSTableReader> sortedSSTables = Lists.newArrayList(originals);
Collections.sort(sortedSSTables, SSTableReader.maxTimestampComparator);
return sortedSSTables;
}
@Override
public void execute(LifecycleTransaction txn) throws IOException
{
logger.debug("Garbage collecting {}", txn.originals());
CompactionTask task = new CompactionTask(cfStore, txn, getDefaultGcBefore(cfStore, FBUtilities.nowInSeconds()))
{
@Override
protected CompactionController getCompactionController(Set<SSTableReader> toCompact)
{
return new CompactionController(cfStore, toCompact, gcBefore, null, tombstoneOption);
}
};
task.setUserDefined(true);
task.setCompactionType(OperationType.GARBAGE_COLLECT);
task.execute(metrics);
}
}, jobs, OperationType.GARBAGE_COLLECT);
}
public AllSSTableOpStatus relocateSSTables(final ColumnFamilyStore cfs, int jobs) throws ExecutionException, InterruptedException
{
if (!cfs.getPartitioner().splitter().isPresent())
{
logger.info("Partitioner does not support splitting");
return AllSSTableOpStatus.ABORTED;
}
final Collection<Range<Token>> r = StorageService.instance.getLocalRanges(cfs.keyspace.getName());
if (r.isEmpty())
{
logger.info("Relocate cannot run before a node has joined the ring");
return AllSSTableOpStatus.ABORTED;
}
final DiskBoundaries diskBoundaries = cfs.getDiskBoundaries();
return parallelAllSSTableOperation(cfs, new OneSSTableOperation()
{
@Override
public Iterable<SSTableReader> filterSSTables(LifecycleTransaction transaction)
{
Set<SSTableReader> originals = Sets.newHashSet(transaction.originals());
Set<SSTableReader> needsRelocation = originals.stream().filter(s -> !inCorrectLocation(s)).collect(Collectors.toSet());
transaction.cancel(Sets.difference(originals, needsRelocation));
Map<Integer, List<SSTableReader>> groupedByDisk = groupByDiskIndex(needsRelocation);
int maxSize = 0;
for (List<SSTableReader> diskSSTables : groupedByDisk.values())
maxSize = Math.max(maxSize, diskSSTables.size());
List<SSTableReader> mixedSSTables = new ArrayList<>();
for (int i = 0; i < maxSize; i++)
for (List<SSTableReader> diskSSTables : groupedByDisk.values())
if (i < diskSSTables.size())
mixedSSTables.add(diskSSTables.get(i));
return mixedSSTables;
}
public Map<Integer, List<SSTableReader>> groupByDiskIndex(Set<SSTableReader> needsRelocation)
{
return needsRelocation.stream().collect(Collectors.groupingBy((s) -> diskBoundaries.getDiskIndex(s)));
}
private boolean inCorrectLocation(SSTableReader sstable)
{
if (!cfs.getPartitioner().splitter().isPresent())
return true;
int diskIndex = diskBoundaries.getDiskIndex(sstable);
File diskLocation = diskBoundaries.directories.get(diskIndex).location;
PartitionPosition diskLast = diskBoundaries.positions.get(diskIndex);
// the location we get from directoryIndex is based on the first key in the sstable
// now we need to make sure the last key is less than the boundary as well:
return sstable.descriptor.directory.getAbsolutePath().startsWith(diskLocation.getAbsolutePath()) && sstable.last.compareTo(diskLast) <= 0;
}
@Override
public void execute(LifecycleTransaction txn)
{
logger.debug("Relocating {}", txn.originals());
AbstractCompactionTask task = cfs.getCompactionStrategyManager().getCompactionTask(txn, NO_GC, Long.MAX_VALUE);
task.setUserDefined(true);
task.setCompactionType(OperationType.RELOCATE);
task.execute(metrics);
}
}, jobs, OperationType.RELOCATE);
}
/**
* Splits the given token ranges of the given sstables into a pending repair silo
*/
public ListenableFuture<?> submitPendingAntiCompaction(ColumnFamilyStore cfs, Collection<Range<Token>> ranges, Refs<SSTableReader> sstables, LifecycleTransaction txn, UUID sessionId)
{
Runnable runnable = new WrappedRunnable()
{
protected void runMayThrow() throws Exception
{
try (TableMetrics.TableTimer.Context ctx = cfs.metric.anticompactionTime.time())
{
performAnticompaction(cfs, ranges, sstables, txn, ActiveRepairService.UNREPAIRED_SSTABLE, sessionId, sessionId);
}
}
};
ListenableFuture<?> task = null;
try
{
task = executor.submitIfRunning(runnable, "pending anticompaction");
return task;
}
finally
{
if (task == null || task.isCancelled())
{
sstables.release();
txn.abort();
}
}
}
/**
* Make sure the {validatedForRepair} are marked for compaction before calling this.
*
* Caller must reference the validatedForRepair sstables (via ParentRepairSession.getActiveRepairedSSTableRefs(..)).
*
* @param cfs
* @param ranges Ranges that the repair was carried out on
* @param validatedForRepair SSTables containing the repaired ranges. Should be referenced before passing them.
* @param parentRepairSession parent repair session ID
* @throws InterruptedException
* @throws IOException
*/
public void performAnticompaction(ColumnFamilyStore cfs,
Collection<Range<Token>> ranges,
Refs<SSTableReader> validatedForRepair,
LifecycleTransaction txn,
long repairedAt,
UUID pendingRepair,
UUID parentRepairSession) throws InterruptedException, IOException
{
try
{
ActiveRepairService.ParentRepairSession prs = ActiveRepairService.instance.getParentRepairSession(parentRepairSession);
Preconditions.checkArgument(!prs.isPreview(), "Cannot anticompact for previews");
logger.info("{} Starting anticompaction for {}.{} on {}/{} sstables", PreviewKind.NONE.logPrefix(parentRepairSession), cfs.keyspace.getName(), cfs.getTableName(), validatedForRepair.size(), cfs.getLiveSSTables().size());
logger.trace("{} Starting anticompaction for ranges {}", PreviewKind.NONE.logPrefix(parentRepairSession), ranges);
Set<SSTableReader> sstables = new HashSet<>(validatedForRepair);
Set<SSTableReader> nonAnticompacting = new HashSet<>();
Iterator<SSTableReader> sstableIterator = sstables.iterator();
List<Range<Token>> normalizedRanges = Range.normalize(ranges);
Set<SSTableReader> fullyContainedSSTables = new HashSet<>();
while (sstableIterator.hasNext())
{
SSTableReader sstable = sstableIterator.next();
Range<Token> sstableRange = new Range<>(sstable.first.getToken(), sstable.last.getToken());
boolean shouldAnticompact = false;
for (Range<Token> r : normalizedRanges)
{
if (r.contains(sstableRange))
{
logger.info("{} SSTable {} fully contained in range {}, mutating repairedAt instead of anticompacting", PreviewKind.NONE.logPrefix(parentRepairSession), sstable, r);
fullyContainedSSTables.add(sstable);
sstableIterator.remove();
shouldAnticompact = true;
break;
}
else if (sstableRange.intersects(r))
{
logger.info("{} SSTable {} ({}) will be anticompacted on range {}", PreviewKind.NONE.logPrefix(parentRepairSession), sstable, sstableRange, r);
shouldAnticompact = true;
}
}
if (!shouldAnticompact)
{
logger.info("{} SSTable {} ({}) does not intersect repaired ranges {}, not touching repairedAt.", PreviewKind.NONE.logPrefix(parentRepairSession), sstable, sstableRange, normalizedRanges);
nonAnticompacting.add(sstable);
sstableIterator.remove();
}
}
cfs.metric.bytesMutatedAnticompaction.inc(SSTableReader.getTotalBytes(fullyContainedSSTables));
cfs.getCompactionStrategyManager().mutateRepaired(fullyContainedSSTables, repairedAt, pendingRepair);
txn.cancel(Sets.union(nonAnticompacting, fullyContainedSSTables));
validatedForRepair.release(Sets.union(nonAnticompacting, fullyContainedSSTables));
assert txn.originals().equals(sstables);
if (!sstables.isEmpty())
doAntiCompaction(cfs, ranges, txn, repairedAt, pendingRepair);
txn.finish();
}
finally
{
validatedForRepair.release();
txn.close();
}
logger.info("{} Completed anticompaction successfully", PreviewKind.NONE.logPrefix(parentRepairSession));
}
public void performMaximal(final ColumnFamilyStore cfStore, boolean splitOutput)
{
FBUtilities.waitOnFutures(submitMaximal(cfStore, getDefaultGcBefore(cfStore, FBUtilities.nowInSeconds()), splitOutput));
}
public List<Future<?>> submitMaximal(final ColumnFamilyStore cfStore, final int gcBefore, boolean splitOutput)
{
// here we compute the task off the compaction executor, so having that present doesn't
// confuse runWithCompactionsDisabled -- i.e., we don't want to deadlock ourselves, waiting
// for ourselves to finish/acknowledge cancellation before continuing.
final Collection<AbstractCompactionTask> tasks = cfStore.getCompactionStrategyManager().getMaximalTasks(gcBefore, splitOutput);
if (tasks == null)
return Collections.emptyList();
List<Future<?>> futures = new ArrayList<>();
int nonEmptyTasks = 0;
for (final AbstractCompactionTask task : tasks)
{
if (task.transaction.originals().size() > 0)
nonEmptyTasks++;
Runnable runnable = new WrappedRunnable()
{
protected void runMayThrow()
{
task.execute(metrics);
}
};
Future<?> fut = executor.submitIfRunning(runnable, "maximal task");
if (!fut.isCancelled())
futures.add(fut);
}
if (nonEmptyTasks > 1)
logger.info("Major compaction will not result in a single sstable - repaired and unrepaired data is kept separate and compaction runs per data_file_directory.");
return futures;
}
public void forceCompactionForTokenRange(ColumnFamilyStore cfStore, Collection<Range<Token>> ranges)
{
final Collection<AbstractCompactionTask> tasks = cfStore.runWithCompactionsDisabled(() ->
{
Collection<SSTableReader> sstables = sstablesInBounds(cfStore, ranges);
if (sstables == null || sstables.isEmpty())
{
logger.debug("No sstables found for the provided token range");
return null;
}
return cfStore.getCompactionStrategyManager().getUserDefinedTasks(sstables, getDefaultGcBefore(cfStore, FBUtilities.nowInSeconds()));
}, false, false);
if (tasks == null)
return;
Runnable runnable = new WrappedRunnable()
{
protected void runMayThrow()
{
for (AbstractCompactionTask task : tasks)
if (task != null)
task.execute(metrics);
}
};
if (executor.isShutdown())
{
logger.info("Compaction executor has shut down, not submitting task");
return;
}
FBUtilities.waitOnFuture(executor.submit(runnable));
}
private static Collection<SSTableReader> sstablesInBounds(ColumnFamilyStore cfs, Collection<Range<Token>> tokenRangeCollection)
{
final Set<SSTableReader> sstables = new HashSet<>();
Iterable<SSTableReader> liveTables = cfs.getTracker().getView().select(SSTableSet.LIVE);
SSTableIntervalTree tree = SSTableIntervalTree.build(liveTables);
for (Range<Token> tokenRange : tokenRangeCollection)
{
Iterable<SSTableReader> ssTableReaders = View.sstablesInBounds(tokenRange.left.minKeyBound(), tokenRange.right.maxKeyBound(), tree);
Iterables.addAll(sstables, ssTableReaders);
}
return sstables;
}
public void forceUserDefinedCompaction(String dataFiles)
{
String[] filenames = dataFiles.split(",");
Multimap<ColumnFamilyStore, Descriptor> descriptors = ArrayListMultimap.create();
for (String filename : filenames)
{
// extract keyspace and columnfamily name from filename
Descriptor desc = Descriptor.fromFilename(filename.trim());
if (Schema.instance.getTableMetadataRef(desc) == null)
{
logger.warn("Schema does not exist for file {}. Skipping.", filename);
continue;
}
// group by keyspace/columnfamily
ColumnFamilyStore cfs = Keyspace.open(desc.ksname).getColumnFamilyStore(desc.cfname);
descriptors.put(cfs, cfs.getDirectories().find(new File(filename.trim()).getName()));
}
List<Future<?>> futures = new ArrayList<>(descriptors.size());
int nowInSec = FBUtilities.nowInSeconds();
for (ColumnFamilyStore cfs : descriptors.keySet())
futures.add(submitUserDefined(cfs, descriptors.get(cfs), getDefaultGcBefore(cfs, nowInSec)));
FBUtilities.waitOnFutures(futures);
}
public void forceUserDefinedCleanup(String dataFiles)
{
String[] filenames = dataFiles.split(",");
HashMap<ColumnFamilyStore, Descriptor> descriptors = Maps.newHashMap();
for (String filename : filenames)
{
// extract keyspace and columnfamily name from filename
Descriptor desc = Descriptor.fromFilename(filename.trim());
if (Schema.instance.getTableMetadataRef(desc) == null)
{
logger.warn("Schema does not exist for file {}. Skipping.", filename);
continue;
}
// group by keyspace/columnfamily
ColumnFamilyStore cfs = Keyspace.open(desc.ksname).getColumnFamilyStore(desc.cfname);
desc = cfs.getDirectories().find(new File(filename.trim()).getName());
if (desc != null)
descriptors.put(cfs, desc);
}
if (!StorageService.instance.isJoined())
{
logger.error("Cleanup cannot run before a node has joined the ring");
return;
}
for (Map.Entry<ColumnFamilyStore,Descriptor> entry : descriptors.entrySet())
{
ColumnFamilyStore cfs = entry.getKey();
Keyspace keyspace = cfs.keyspace;
Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(keyspace.getName());
boolean hasIndexes = cfs.indexManager.hasIndexes();
SSTableReader sstable = lookupSSTable(cfs, entry.getValue());
if (sstable == null)
{
logger.warn("Will not clean {}, it is not an active sstable", entry.getValue());
}
else
{
CleanupStrategy cleanupStrategy = CleanupStrategy.get(cfs, ranges, FBUtilities.nowInSeconds());
try (LifecycleTransaction txn = cfs.getTracker().tryModify(sstable, OperationType.CLEANUP))
{
doCleanupOne(cfs, txn, cleanupStrategy, ranges, hasIndexes);
}
catch (IOException e)
{
logger.error("forceUserDefinedCleanup failed: {}", e.getLocalizedMessage());
}
}
}
}
public Future<?> submitUserDefined(final ColumnFamilyStore cfs, final Collection<Descriptor> dataFiles, final int gcBefore)
{
Runnable runnable = new WrappedRunnable()
{
protected void runMayThrow()
{
// look up the sstables now that we're on the compaction executor, so we don't try to re-compact
// something that was already being compacted earlier.
Collection<SSTableReader> sstables = new ArrayList<>(dataFiles.size());
for (Descriptor desc : dataFiles)
{
// inefficient but not in a performance sensitive path
SSTableReader sstable = lookupSSTable(cfs, desc);
if (sstable == null)
{
logger.info("Will not compact {}: it is not an active sstable", desc);
}
else
{
sstables.add(sstable);
}
}
if (sstables.isEmpty())
{
logger.info("No files to compact for user defined compaction");
}
else
{
List<AbstractCompactionTask> tasks = cfs.getCompactionStrategyManager().getUserDefinedTasks(sstables, gcBefore);
for (AbstractCompactionTask task : tasks)
{
if (task != null)
task.execute(metrics);
}
}
}
};
return executor.submitIfRunning(runnable, "user defined task");
}
// This acquire a reference on the sstable
// This is not efficient, do not use in any critical path
private SSTableReader lookupSSTable(final ColumnFamilyStore cfs, Descriptor descriptor)
{
for (SSTableReader sstable : cfs.getSSTables(SSTableSet.CANONICAL))
{
if (sstable.descriptor.equals(descriptor))
return sstable;
}
return null;
}
public Future<?> submitValidation(Callable<Object> validation)
{
return validationExecutor.submitIfRunning(validation, "validation");
}
/* Used in tests. */
public void disableAutoCompaction()
{
for (String ksname : Schema.instance.getNonSystemKeyspaces())
{
for (ColumnFamilyStore cfs : Keyspace.open(ksname).getColumnFamilyStores())
cfs.disableAutoCompaction();
}
}
private void scrubOne(ColumnFamilyStore cfs, LifecycleTransaction modifier, boolean skipCorrupted, boolean checkData, boolean reinsertOverflowedTTL)
{
CompactionInfo.Holder scrubInfo = null;
try (Scrubber scrubber = new Scrubber(cfs, modifier, skipCorrupted, checkData, reinsertOverflowedTTL))
{
scrubInfo = scrubber.getScrubInfo();
metrics.beginCompaction(scrubInfo);
scrubber.scrub();
}
finally
{
if (scrubInfo != null)
metrics.finishCompaction(scrubInfo);
}
}
private void verifyOne(ColumnFamilyStore cfs, SSTableReader sstable, Verifier.Options options)
{
CompactionInfo.Holder verifyInfo = null;
try (Verifier verifier = new Verifier(cfs, sstable, false, options))
{
verifyInfo = verifier.getVerifyInfo();
metrics.beginCompaction(verifyInfo);
verifier.verify();
}
finally
{
if (verifyInfo != null)
metrics.finishCompaction(verifyInfo);
}
}
/**
* Determines if a cleanup would actually remove any data in this SSTable based
* on a set of owned ranges.
*/
@VisibleForTesting
public static boolean needsCleanup(SSTableReader sstable, Collection<Range<Token>> ownedRanges)
{
if (ownedRanges.isEmpty())
{
return true; // all data will be cleaned
}
// unwrap and sort the ranges by LHS token
List<Range<Token>> sortedRanges = Range.normalize(ownedRanges);
// see if there are any keys LTE the token for the start of the first range
// (token range ownership is exclusive on the LHS.)
Range<Token> firstRange = sortedRanges.get(0);
if (sstable.first.getToken().compareTo(firstRange.left) <= 0)
return true;
// then, iterate over all owned ranges and see if the next key beyond the end of the owned
// range falls before the start of the next range
for (int i = 0; i < sortedRanges.size(); i++)
{
Range<Token> range = sortedRanges.get(i);
if (range.right.isMinimum())
{
// we split a wrapping range and this is the second half.
// there can't be any keys beyond this (and this is the last range)
return false;
}
DecoratedKey firstBeyondRange = sstable.firstKeyBeyond(range.right.maxKeyBound());
if (firstBeyondRange == null)
{
// we ran off the end of the sstable looking for the next key; we don't need to check any more ranges
return false;
}
if (i == (sortedRanges.size() - 1))
{
// we're at the last range and we found a key beyond the end of the range
return true;
}
Range<Token> nextRange = sortedRanges.get(i + 1);
if (firstBeyondRange.getToken().compareTo(nextRange.left) <= 0)
{
// we found a key in between the owned ranges
return true;
}
}
return false;
}
/**
* This function goes over a file and removes the keys that the node is not responsible for
* and only keeps keys that this node is responsible for.
*
* @throws IOException
*/
private void doCleanupOne(final ColumnFamilyStore cfs, LifecycleTransaction txn, CleanupStrategy cleanupStrategy, Collection<Range<Token>> ranges, boolean hasIndexes) throws IOException
{
assert !cfs.isIndex();
SSTableReader sstable = txn.onlyOne();
// if ranges is empty and no index, entire sstable is discarded
if (!hasIndexes && !new Bounds<>(sstable.first.getToken(), sstable.last.getToken()).intersects(ranges))
{
txn.obsoleteOriginals();
txn.finish();
return;
}
if (!needsCleanup(sstable, ranges))
{
logger.trace("Skipping {} for cleanup; all rows should be kept", sstable);
return;
}
long start = System.nanoTime();
long totalkeysWritten = 0;
long expectedBloomFilterSize = Math.max(cfs.metadata().params.minIndexInterval,
SSTableReader.getApproximateKeyCount(txn.originals()));
if (logger.isTraceEnabled())
logger.trace("Expected bloom filter size : {}", expectedBloomFilterSize);
logger.info("Cleaning up {}", sstable);
File compactionFileLocation = sstable.descriptor.directory;
RateLimiter limiter = getRateLimiter();
double compressionRatio = sstable.getCompressionRatio();
if (compressionRatio == MetadataCollector.NO_COMPRESSION_RATIO)
compressionRatio = 1.0;
List<SSTableReader> finished;
int nowInSec = FBUtilities.nowInSeconds();
try (SSTableRewriter writer = SSTableRewriter.construct(cfs, txn, false, sstable.maxDataAge);
ISSTableScanner scanner = cleanupStrategy.getScanner(sstable);
CompactionController controller = new CompactionController(cfs, txn.originals(), getDefaultGcBefore(cfs, nowInSec));
Refs<SSTableReader> refs = Refs.ref(Collections.singleton(sstable));
CompactionIterator ci = new CompactionIterator(OperationType.CLEANUP, Collections.singletonList(scanner), controller, nowInSec, UUIDGen.getTimeUUID(), metrics))
{
StatsMetadata metadata = sstable.getSSTableMetadata();
writer.switchWriter(createWriter(cfs, compactionFileLocation, expectedBloomFilterSize, metadata.repairedAt, metadata.pendingRepair, sstable, txn));
long lastBytesScanned = 0;
while (ci.hasNext())
{
if (ci.isStopRequested())
throw new CompactionInterruptedException(ci.getCompactionInfo());
try (UnfilteredRowIterator partition = ci.next();
UnfilteredRowIterator notCleaned = cleanupStrategy.cleanup(partition))
{
if (notCleaned == null)
continue;
if (writer.append(notCleaned) != null)
totalkeysWritten++;
long bytesScanned = scanner.getBytesScanned();
compactionRateLimiterAcquire(limiter, bytesScanned, lastBytesScanned, compressionRatio);
lastBytesScanned = bytesScanned;
}
}
// flush to ensure we don't lose the tombstones on a restart, since they are not commitlog'd
cfs.indexManager.flushAllIndexesBlocking();
finished = writer.finish();
}
if (!finished.isEmpty())
{
String format = "Cleaned up to %s. %s to %s (~%d%% of original) for %,d keys. Time: %,dms.";
long dTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
long startsize = sstable.onDiskLength();
long endsize = 0;
for (SSTableReader newSstable : finished)
endsize += newSstable.onDiskLength();
double ratio = (double) endsize / (double) startsize;
logger.info(String.format(format, finished.get(0).getFilename(), FBUtilities.prettyPrintMemory(startsize),
FBUtilities.prettyPrintMemory(endsize), (int) (ratio * 100), totalkeysWritten, dTime));
}
}
static void compactionRateLimiterAcquire(RateLimiter limiter, long bytesScanned, long lastBytesScanned, double compressionRatio)
{
long lengthRead = (long) ((bytesScanned - lastBytesScanned) * compressionRatio) + 1;
while (lengthRead >= Integer.MAX_VALUE)
{
limiter.acquire(Integer.MAX_VALUE);
lengthRead -= Integer.MAX_VALUE;
}
if (lengthRead > 0)
{
limiter.acquire((int) lengthRead);
}
}
private static abstract class CleanupStrategy
{
protected final Collection<Range<Token>> ranges;
protected final int nowInSec;
protected CleanupStrategy(Collection<Range<Token>> ranges, int nowInSec)
{
this.ranges = ranges;
this.nowInSec = nowInSec;
}
public static CleanupStrategy get(ColumnFamilyStore cfs, Collection<Range<Token>> ranges, int nowInSec)
{
return cfs.indexManager.hasIndexes()
? new Full(cfs, ranges, nowInSec)
: new Bounded(cfs, ranges, nowInSec);
}
public abstract ISSTableScanner getScanner(SSTableReader sstable);
public abstract UnfilteredRowIterator cleanup(UnfilteredRowIterator partition);
private static final class Bounded extends CleanupStrategy
{
public Bounded(final ColumnFamilyStore cfs, Collection<Range<Token>> ranges, int nowInSec)
{
super(ranges, nowInSec);
cacheCleanupExecutor.submit(new Runnable()
{
@Override
public void run()
{
cfs.cleanupCache();
}
});
}
@Override
public ISSTableScanner getScanner(SSTableReader sstable)
{
return sstable.getScanner(ranges);
}
@Override
public UnfilteredRowIterator cleanup(UnfilteredRowIterator partition)
{
return partition;
}
}
private static final class Full extends CleanupStrategy
{
private final ColumnFamilyStore cfs;
public Full(ColumnFamilyStore cfs, Collection<Range<Token>> ranges, int nowInSec)
{
super(ranges, nowInSec);
this.cfs = cfs;
}
@Override
public ISSTableScanner getScanner(SSTableReader sstable)
{
return sstable.getScanner();
}
@Override
public UnfilteredRowIterator cleanup(UnfilteredRowIterator partition)
{
if (Range.isInRanges(partition.partitionKey().getToken(), ranges))
return partition;
cfs.invalidateCachedPartition(partition.partitionKey());
cfs.indexManager.deletePartition(partition, nowInSec);
return null;
}
}
}
public static SSTableWriter createWriter(ColumnFamilyStore cfs,
File compactionFileLocation,
long expectedBloomFilterSize,
long repairedAt,
UUID pendingRepair,
SSTableReader sstable,
LifecycleTransaction txn)
{
FileUtils.createDirectory(compactionFileLocation);
return SSTableWriter.create(cfs.metadata,
cfs.newSSTableDescriptor(compactionFileLocation),
expectedBloomFilterSize,
repairedAt,
pendingRepair,
sstable.getSSTableLevel(),
sstable.header,
cfs.indexManager.listIndexes(),
txn);
}
public static SSTableWriter createWriterForAntiCompaction(ColumnFamilyStore cfs,
File compactionFileLocation,
int expectedBloomFilterSize,
long repairedAt,
UUID pendingRepair,
Collection<SSTableReader> sstables,
LifecycleTransaction txn)
{
FileUtils.createDirectory(compactionFileLocation);
int minLevel = Integer.MAX_VALUE;
// if all sstables have the same level, we can compact them together without creating overlap during anticompaction
// note that we only anticompact from unrepaired sstables, which is not leveled, but we still keep original level
// after first migration to be able to drop the sstables back in their original place in the repaired sstable manifest
for (SSTableReader sstable : sstables)
{
if (minLevel == Integer.MAX_VALUE)
minLevel = sstable.getSSTableLevel();
if (minLevel != sstable.getSSTableLevel())
{
minLevel = 0;
break;
}
}
return SSTableWriter.create(cfs.newSSTableDescriptor(compactionFileLocation),
(long) expectedBloomFilterSize,
repairedAt,
pendingRepair,
cfs.metadata,
new MetadataCollector(sstables, cfs.metadata().comparator, minLevel),
SerializationHeader.make(cfs.metadata(), sstables),
cfs.indexManager.listIndexes(),
txn);
}
/**
* Splits up an sstable into two new sstables. The first of the new tables will store repaired ranges, the second
* will store the non-repaired ranges. Once anticompation is completed, the original sstable is marked as compacted
* and subsequently deleted.
* @param cfs
* @param repaired a transaction over the repaired sstables to anticompacy
* @param ranges Repaired ranges to be placed into one of the new sstables. The repaired table will be tracked via
* the {@link org.apache.cassandra.io.sstable.metadata.StatsMetadata#repairedAt} field.
*/
private void doAntiCompaction(ColumnFamilyStore cfs, Collection<Range<Token>> ranges, LifecycleTransaction repaired, long repairedAt, UUID pendingRepair)
{
logger.info("Performing anticompaction on {} sstables", repaired.originals().size());
//Group SSTables
Set<SSTableReader> sstables = repaired.originals();
// Repairs can take place on both unrepaired (incremental + full) and repaired (full) data.
// Although anti-compaction could work on repaired sstables as well and would result in having more accurate
// repairedAt values for these, we still avoid anti-compacting already repaired sstables, as we currently don't
// make use of any actual repairedAt value and splitting up sstables just for that is not worth it at this point.
Set<SSTableReader> unrepairedSSTables = sstables.stream().filter((s) -> !s.isRepaired()).collect(Collectors.toSet());
cfs.metric.bytesAnticompacted.inc(SSTableReader.getTotalBytes(unrepairedSSTables));
Collection<Collection<SSTableReader>> groupedSSTables = cfs.getCompactionStrategyManager().groupSSTablesForAntiCompaction(unrepairedSSTables);
// iterate over sstables to check if the repaired / unrepaired ranges intersect them.
int antiCompactedSSTableCount = 0;
for (Collection<SSTableReader> sstableGroup : groupedSSTables)
{
try (LifecycleTransaction txn = repaired.split(sstableGroup))
{
int antiCompacted = antiCompactGroup(cfs, ranges, txn, repairedAt, pendingRepair);
antiCompactedSSTableCount += antiCompacted;
}
}
String format = "Anticompaction completed successfully, anticompacted from {} to {} sstable(s).";
logger.info(format, repaired.originals().size(), antiCompactedSSTableCount);
}
private int antiCompactGroup(ColumnFamilyStore cfs, Collection<Range<Token>> ranges,
LifecycleTransaction anticompactionGroup, long repairedAt, UUID pendingRepair)
{
long groupMaxDataAge = -1;
for (Iterator<SSTableReader> i = anticompactionGroup.originals().iterator(); i.hasNext();)
{
SSTableReader sstable = i.next();
if (groupMaxDataAge < sstable.maxDataAge)
groupMaxDataAge = sstable.maxDataAge;
}
if (anticompactionGroup.originals().size() == 0)
{
logger.info("No valid anticompactions for this group, All sstables were compacted and are no longer available");
return 0;
}
logger.info("Anticompacting {}", anticompactionGroup);
Set<SSTableReader> sstableAsSet = anticompactionGroup.originals();
File destination = cfs.getDirectories().getWriteableLocationAsFile(cfs.getExpectedCompactedFileSize(sstableAsSet, OperationType.ANTICOMPACTION));
long repairedKeyCount = 0;
long unrepairedKeyCount = 0;
int nowInSec = FBUtilities.nowInSeconds();
CompactionStrategyManager strategy = cfs.getCompactionStrategyManager();
try (SSTableRewriter repairedSSTableWriter = SSTableRewriter.constructWithoutEarlyOpening(anticompactionGroup, false, groupMaxDataAge);
SSTableRewriter unRepairedSSTableWriter = SSTableRewriter.constructWithoutEarlyOpening(anticompactionGroup, false, groupMaxDataAge);
AbstractCompactionStrategy.ScannerList scanners = strategy.getScanners(anticompactionGroup.originals());
CompactionController controller = new CompactionController(cfs, sstableAsSet, getDefaultGcBefore(cfs, nowInSec));
CompactionIterator ci = new CompactionIterator(OperationType.ANTICOMPACTION, scanners.scanners, controller, nowInSec, UUIDGen.getTimeUUID(), metrics))
{
int expectedBloomFilterSize = Math.max(cfs.metadata().params.minIndexInterval, (int)(SSTableReader.getApproximateKeyCount(sstableAsSet)));
repairedSSTableWriter.switchWriter(CompactionManager.createWriterForAntiCompaction(cfs, destination, expectedBloomFilterSize, repairedAt, pendingRepair, sstableAsSet, anticompactionGroup));
unRepairedSSTableWriter.switchWriter(CompactionManager.createWriterForAntiCompaction(cfs, destination, expectedBloomFilterSize, ActiveRepairService.UNREPAIRED_SSTABLE, null, sstableAsSet, anticompactionGroup));
Range.OrderedRangeContainmentChecker containmentChecker = new Range.OrderedRangeContainmentChecker(ranges);
while (ci.hasNext())
{
try (UnfilteredRowIterator partition = ci.next())
{
// if current range from sstable is repaired, save it into the new repaired sstable
if (containmentChecker.contains(partition.partitionKey().getToken()))
{
repairedSSTableWriter.append(partition);
repairedKeyCount++;
}
// otherwise save into the new 'non-repaired' table
else
{
unRepairedSSTableWriter.append(partition);
unrepairedKeyCount++;
}
}
}
List<SSTableReader> anticompactedSSTables = new ArrayList<>();
// since both writers are operating over the same Transaction, we cannot use the convenience Transactional.finish() method,
// as on the second finish() we would prepareToCommit() on a Transaction that has already been committed, which is forbidden by the API
// (since it indicates misuse). We call permitRedundantTransitions so that calls that transition to a state already occupied are permitted.
anticompactionGroup.permitRedundantTransitions();
repairedSSTableWriter.setRepairedAt(repairedAt).prepareToCommit();
unRepairedSSTableWriter.prepareToCommit();
anticompactedSSTables.addAll(repairedSSTableWriter.finished());
anticompactedSSTables.addAll(unRepairedSSTableWriter.finished());
repairedSSTableWriter.commit();
unRepairedSSTableWriter.commit();
logger.trace("Repaired {} keys out of {} for {}/{} in {}", repairedKeyCount,
repairedKeyCount + unrepairedKeyCount,
cfs.keyspace.getName(),
cfs.getTableName(),
anticompactionGroup);
return anticompactedSSTables.size();
}
catch (Throwable e)
{
JVMStabilityInspector.inspectThrowable(e);
logger.error("Error anticompacting " + anticompactionGroup, e);
}
return 0;
}
/**
* Is not scheduled, because it is performing disjoint work from sstable compaction.
*/
public ListenableFuture<?> submitIndexBuild(final SecondaryIndexBuilder builder)
{
Runnable runnable = new Runnable()
{
public void run()
{
metrics.beginCompaction(builder);
try
{
builder.build();
}
finally
{
metrics.finishCompaction(builder);
}
}
};
return executor.submitIfRunning(runnable, "index build");
}
public Future<?> submitCacheWrite(final AutoSavingCache.Writer writer)
{
Runnable runnable = new Runnable()
{
public void run()
{
if (!AutoSavingCache.flushInProgress.add(writer.cacheType()))
{
logger.trace("Cache flushing was already in progress: skipping {}", writer.getCompactionInfo());
return;
}
try
{
metrics.beginCompaction(writer);
try
{
writer.saveCache();
}
finally
{
metrics.finishCompaction(writer);
}
}
finally
{
AutoSavingCache.flushInProgress.remove(writer.cacheType());
}
}
};
return executor.submitIfRunning(runnable, "cache write");
}
public List<SSTableReader> runIndexSummaryRedistribution(IndexSummaryRedistribution redistribution) throws IOException
{
metrics.beginCompaction(redistribution);
try
{
return redistribution.redistributeSummaries();
}
finally
{
metrics.finishCompaction(redistribution);
}
}
public static int getDefaultGcBefore(ColumnFamilyStore cfs, int nowInSec)
{
// 2ndary indexes have ExpiringColumns too, so we need to purge tombstones deleted before now. We do not need to
// add any GcGrace however since 2ndary indexes are local to a node.
return cfs.isIndex() ? nowInSec : cfs.gcBefore(nowInSec);
}
public ListenableFuture<Long> submitViewBuilder(final ViewBuilderTask task)
{
return viewBuildExecutor.submitIfRunning(() -> {
metrics.beginCompaction(task);
try
{
return task.call();
}
finally
{
metrics.finishCompaction(task);
}
}, "view build");
}
public int getActiveCompactions()
{
return CompactionMetrics.getCompactions().size();
}
static class CompactionExecutor extends JMXEnabledThreadPoolExecutor
{
protected CompactionExecutor(int minThreads, int maxThreads, String name, BlockingQueue<Runnable> queue)
{
super(minThreads, maxThreads, 60, TimeUnit.SECONDS, queue, new NamedThreadFactory(name, Thread.MIN_PRIORITY), "internal");
}
private CompactionExecutor(int threadCount, String name)
{
this(threadCount, threadCount, name, new LinkedBlockingQueue<Runnable>());
}
public CompactionExecutor()
{
this(Math.max(1, DatabaseDescriptor.getConcurrentCompactors()), "CompactionExecutor");
}
protected void beforeExecute(Thread t, Runnable r)
{
// can't set this in Thread factory, so we do it redundantly here
isCompactionManager.set(true);
super.beforeExecute(t, r);
}
// modified from DebuggableThreadPoolExecutor so that CompactionInterruptedExceptions are not logged
@Override
public void afterExecute(Runnable r, Throwable t)
{
DebuggableThreadPoolExecutor.maybeResetTraceSessionWrapper(r);
if (t == null)
t = DebuggableThreadPoolExecutor.extractThrowable(r);
if (t != null)
{
if (t instanceof CompactionInterruptedException)
{
logger.info(t.getMessage());
if (t.getSuppressed() != null && t.getSuppressed().length > 0)
logger.warn("Interruption of compaction encountered exceptions:", t);
else
logger.trace("Full interruption stack trace:", t);
}
else
{
DebuggableThreadPoolExecutor.handleOrLog(t);
}
}
// Snapshots cannot be deleted on Windows while segments of the root element are mapped in NTFS. Compactions
// unmap those segments which could free up a snapshot for successful deletion.
SnapshotDeletingTask.rescheduleFailedTasks();
}
public ListenableFuture<?> submitIfRunning(Runnable task, String name)
{
return submitIfRunning(Executors.callable(task, null), name);
}
/**
* Submit the task but only if the executor has not been shutdown.If the executor has
* been shutdown, or in case of a rejected execution exception return a cancelled future.
*
* @param task - the task to submit
* @param name - the task name to use in log messages
*
* @return the future that will deliver the task result, or a future that has already been
* cancelled if the task could not be submitted.
*/
public <T> ListenableFuture<T> submitIfRunning(Callable<T> task, String name)
{
if (isShutdown())
{
logger.info("Executor has been shut down, not submitting {}", name);
return Futures.immediateCancelledFuture();
}
try
{
ListenableFutureTask<T> ret = ListenableFutureTask.create(task);
execute(ret);
return ret;
}
catch (RejectedExecutionException ex)
{
if (isShutdown())
logger.info("Executor has shut down, could not submit {}", name);
else
logger.error("Failed to submit {}", name, ex);
return Futures.immediateCancelledFuture();
}
}
}
// TODO: pull out relevant parts of CompactionExecutor and move to ValidationManager
public static class ValidationExecutor extends CompactionExecutor
{
public ValidationExecutor()
{
super(1, DatabaseDescriptor.getConcurrentValidations(), "ValidationExecutor", new SynchronousQueue<Runnable>());
}
}
private static class ViewBuildExecutor extends CompactionExecutor
{
public ViewBuildExecutor()
{
super(DatabaseDescriptor.getConcurrentViewBuilders(), "ViewBuildExecutor");
}
}
private static class CacheCleanupExecutor extends CompactionExecutor
{
public CacheCleanupExecutor()
{
super(1, "CacheCleanupExecutor");
}
}
public interface CompactionExecutorStatsCollector
{
void beginCompaction(CompactionInfo.Holder ci);
void finishCompaction(CompactionInfo.Holder ci);
}
public void incrementAborted()
{
metrics.compactionsAborted.inc();
}
public void incrementCompactionsReduced()
{
metrics.compactionsReduced.inc();
}
public void incrementSstablesDropppedFromCompactions(long num)
{
metrics.sstablesDropppedFromCompactions.inc(num);
}
public List<Map<String, String>> getCompactions()
{
List<Holder> compactionHolders = CompactionMetrics.getCompactions();
List<Map<String, String>> out = new ArrayList<Map<String, String>>(compactionHolders.size());
for (CompactionInfo.Holder ci : compactionHolders)
out.add(ci.getCompactionInfo().asMap());
return out;
}
public List<String> getCompactionSummary()
{
List<Holder> compactionHolders = CompactionMetrics.getCompactions();
List<String> out = new ArrayList<String>(compactionHolders.size());
for (CompactionInfo.Holder ci : compactionHolders)
out.add(ci.getCompactionInfo().toString());
return out;
}
public TabularData getCompactionHistory()
{
try
{
return SystemKeyspace.getCompactionHistory();
}
catch (OpenDataException e)
{
throw new RuntimeException(e);
}
}
public long getTotalBytesCompacted()
{
return metrics.bytesCompacted.getCount();
}
public long getTotalCompactionsCompleted()
{
return metrics.totalCompactionsCompleted.getCount();
}
public int getPendingTasks()
{
return metrics.pendingTasks.getValue();
}
public long getCompletedTasks()
{
return metrics.completedTasks.getValue();
}
public void stopCompaction(String type)
{
OperationType operation = OperationType.valueOf(type);
for (Holder holder : CompactionMetrics.getCompactions())
{
if (holder.getCompactionInfo().getTaskType() == operation)
holder.stop();
}
}
public void stopCompactionById(String compactionId)
{
for (Holder holder : CompactionMetrics.getCompactions())
{
UUID holderId = holder.getCompactionInfo().compactionId();
if (holderId != null && holderId.equals(UUID.fromString(compactionId)))
holder.stop();
}
}
public void setConcurrentCompactors(int value)
{
if (value > executor.getCorePoolSize())
{
// we are increasing the value
executor.setMaximumPoolSize(value);
executor.setCorePoolSize(value);
}
else if (value < executor.getCorePoolSize())
{
// we are reducing the value
executor.setCorePoolSize(value);
executor.setMaximumPoolSize(value);
}
}
public void setConcurrentValidations(int value)
{
value = value > 0 ? value : Integer.MAX_VALUE;
validationExecutor.setMaximumPoolSize(value);
}
public void setConcurrentViewBuilders(int value)
{
if (value > viewBuildExecutor.getCorePoolSize())
{
// we are increasing the value
viewBuildExecutor.setMaximumPoolSize(value);
viewBuildExecutor.setCorePoolSize(value);
}
else if (value < viewBuildExecutor.getCorePoolSize())
{
// we are reducing the value
viewBuildExecutor.setCorePoolSize(value);
viewBuildExecutor.setMaximumPoolSize(value);
}
}
public int getCoreCompactorThreads()
{
return executor.getCorePoolSize();
}
public void setCoreCompactorThreads(int number)
{
executor.setCorePoolSize(number);
}
public int getMaximumCompactorThreads()
{
return executor.getMaximumPoolSize();
}
public void setMaximumCompactorThreads(int number)
{
executor.setMaximumPoolSize(number);
}
public int getCoreValidationThreads()
{
return validationExecutor.getCorePoolSize();
}
public void setCoreValidationThreads(int number)
{
validationExecutor.setCorePoolSize(number);
}
public int getMaximumValidatorThreads()
{
return validationExecutor.getMaximumPoolSize();
}
public void setMaximumValidatorThreads(int number)
{
validationExecutor.setMaximumPoolSize(number);
}
public int getCoreViewBuildThreads()
{
return viewBuildExecutor.getCorePoolSize();
}
public void setCoreViewBuildThreads(int number)
{
viewBuildExecutor.setCorePoolSize(number);
}
public int getMaximumViewBuildThreads()
{
return viewBuildExecutor.getMaximumPoolSize();
}
public void setMaximumViewBuildThreads(int number)
{
viewBuildExecutor.setMaximumPoolSize(number);
}
/**
* Try to stop all of the compactions for given ColumnFamilies.
*
* Note that this method does not wait for all compactions to finish; you'll need to loop against
* isCompacting if you want that behavior.
*
* @param columnFamilies The ColumnFamilies to try to stop compaction upon.
* @param interruptValidation true if validation operations for repair should also be interrupted
*
*/
public void interruptCompactionFor(Iterable<TableMetadata> columnFamilies, boolean interruptValidation)
{
assert columnFamilies != null;
// interrupt in-progress compactions
for (Holder compactionHolder : CompactionMetrics.getCompactions())
{
CompactionInfo info = compactionHolder.getCompactionInfo();
if ((info.getTaskType() == OperationType.VALIDATION) && !interruptValidation)
continue;
if (Iterables.contains(columnFamilies, info.getTableMetadata()))
compactionHolder.stop(); // signal compaction to stop
}
}
public void interruptCompactionForCFs(Iterable<ColumnFamilyStore> cfss, boolean interruptValidation)
{
List<TableMetadata> metadata = new ArrayList<>();
for (ColumnFamilyStore cfs : cfss)
metadata.add(cfs.metadata());
interruptCompactionFor(metadata, interruptValidation);
}
public void waitForCessation(Iterable<ColumnFamilyStore> cfss)
{
long start = System.nanoTime();
long delay = TimeUnit.MINUTES.toNanos(1);
while (System.nanoTime() - start < delay)
{
if (CompactionManager.instance.isCompacting(cfss))
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MILLISECONDS);
else
break;
}
}
}
| apache-2.0 |
twitter-forks/presto | presto-hive/src/main/java/com/facebook/presto/hive/InternalHiveSplit.java | 9553 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.hive;
import com.facebook.presto.hive.HiveSplit.BucketConversion;
import com.facebook.presto.hive.metastore.Column;
import com.facebook.presto.spi.HostAddress;
import com.facebook.presto.spi.schedule.NodeSelectionStrategy;
import com.google.common.collect.ImmutableList;
import org.apache.hadoop.fs.Path;
import org.openjdk.jol.info.ClassLayout;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.slice.SizeOf.sizeOf;
import static io.airlift.slice.SizeOf.sizeOfObjectArray;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
@NotThreadSafe
public class InternalHiveSplit
{
// Overhead of ImmutableList and ImmutableMap is not accounted because of its complexity.
private static final int INSTANCE_SIZE = ClassLayout.parseClass(InternalHiveSplit.class).instanceSize();
private static final int HOST_ADDRESS_INSTANCE_SIZE = ClassLayout.parseClass(HostAddress.class).instanceSize() +
ClassLayout.parseClass(String.class).instanceSize();
private final byte[] relativeUri;
private final long end;
private final long fileSize;
// encode the hive blocks as an array of longs and list of list of addresses to save memory
//if all blockAddress lists are empty, store only the empty list
private final long[] blockEndOffsets;
private final List<List<HostAddress>> blockAddresses;
// stored as ints rather than Optionals to save memory
// -1 indicates an absent value
private final int readBucketNumber;
private final int tableBucketNumber;
private final boolean splittable;
private final NodeSelectionStrategy nodeSelectionStrategy;
private final boolean s3SelectPushdownEnabled;
private final HiveSplitPartitionInfo partitionInfo;
private final Optional<byte[]> extraFileInfo;
private final Optional<EncryptionInformation> encryptionInformation;
private long start;
private int currentBlockIndex;
public InternalHiveSplit(
String relativeUri,
long start,
long end,
long fileSize,
List<InternalHiveBlock> blocks,
OptionalInt readBucketNumber,
OptionalInt tableBucketNumber,
boolean splittable,
NodeSelectionStrategy nodeSelectionStrategy,
boolean s3SelectPushdownEnabled,
HiveSplitPartitionInfo partitionInfo,
Optional<byte[]> extraFileInfo,
Optional<EncryptionInformation> encryptionInformation)
{
checkArgument(start >= 0, "start must be positive");
checkArgument(end >= 0, "end must be positive");
checkArgument(fileSize >= 0, "fileSize must be positive");
requireNonNull(relativeUri, "relativeUri is null");
requireNonNull(readBucketNumber, "readBucketNumber is null");
requireNonNull(tableBucketNumber, "tableBucketNumber is null");
requireNonNull(nodeSelectionStrategy, "nodeSelectionStrategy is null");
requireNonNull(partitionInfo, "partitionInfo is null");
requireNonNull(extraFileInfo, "extraFileInfo is null");
requireNonNull(encryptionInformation, "encryptionInformation is null");
this.relativeUri = relativeUri.getBytes(UTF_8);
this.start = start;
this.end = end;
this.fileSize = fileSize;
this.readBucketNumber = readBucketNumber.orElse(-1);
this.tableBucketNumber = tableBucketNumber.orElse(-1);
this.splittable = splittable;
this.nodeSelectionStrategy = nodeSelectionStrategy;
this.s3SelectPushdownEnabled = s3SelectPushdownEnabled;
this.partitionInfo = partitionInfo;
this.extraFileInfo = extraFileInfo;
ImmutableList.Builder<List<HostAddress>> addressesBuilder = ImmutableList.builder();
blockEndOffsets = new long[blocks.size()];
boolean allAddressesEmpty = true;
for (int i = 0; i < blocks.size(); i++) {
InternalHiveBlock block = blocks.get(i);
List<HostAddress> addresses = block.getAddresses();
allAddressesEmpty = allAddressesEmpty && addresses.isEmpty();
addressesBuilder.add(addresses);
blockEndOffsets[i] = block.getEnd();
}
blockAddresses = allAddressesEmpty ? ImmutableList.of() : addressesBuilder.build();
this.encryptionInformation = encryptionInformation;
}
public String getPath()
{
String relativePathString = new String(relativeUri, UTF_8);
return new Path(partitionInfo.getPath().resolve(relativePathString)).toString();
}
public long getStart()
{
return start;
}
public long getEnd()
{
return end;
}
public long getFileSize()
{
return fileSize;
}
public boolean isS3SelectPushdownEnabled()
{
return s3SelectPushdownEnabled;
}
public List<HivePartitionKey> getPartitionKeys()
{
return partitionInfo.getPartitionKeys();
}
public String getPartitionName()
{
return partitionInfo.getPartitionName();
}
public OptionalInt getReadBucketNumber()
{
return readBucketNumber >= 0 ? OptionalInt.of(readBucketNumber) : OptionalInt.empty();
}
public OptionalInt getTableBucketNumber()
{
return tableBucketNumber >= 0 ? OptionalInt.of(tableBucketNumber) : OptionalInt.empty();
}
public boolean isSplittable()
{
return splittable;
}
public NodeSelectionStrategy getNodeSelectionStrategy()
{
return nodeSelectionStrategy;
}
public Map<Integer, Column> getPartitionSchemaDifference()
{
return partitionInfo.getPartitionSchemaDifference();
}
public Optional<BucketConversion> getBucketConversion()
{
return partitionInfo.getBucketConversion();
}
public InternalHiveBlock currentBlock()
{
checkState(!isDone(), "All blocks have been consumed");
List<HostAddress> addresses = blockAddresses.isEmpty() ? ImmutableList.of() : blockAddresses.get(currentBlockIndex);
return new InternalHiveBlock(blockEndOffsets[currentBlockIndex], addresses);
}
public boolean isDone()
{
return currentBlockIndex == blockEndOffsets.length;
}
public void increaseStart(long value)
{
start += value;
if (start == currentBlock().getEnd()) {
currentBlockIndex++;
}
}
public HiveSplitPartitionInfo getPartitionInfo()
{
return partitionInfo;
}
public Optional<byte[]> getExtraFileInfo()
{
return extraFileInfo;
}
public Optional<EncryptionInformation> getEncryptionInformation()
{
return this.encryptionInformation;
}
public void reset()
{
currentBlockIndex = 0;
start = 0;
}
/**
* Estimate the size of this InternalHiveSplit. Note that
* PartitionInfo is a shared object, so its memory usage is
* tracked separately in HiveSplitSource.
*/
public int getEstimatedSizeInBytes()
{
int result = INSTANCE_SIZE;
result += sizeOf(relativeUri);
result += sizeOf(blockEndOffsets);
if (!blockAddresses.isEmpty()) {
result += sizeOfObjectArray(blockAddresses.size());
for (List<HostAddress> addresses : blockAddresses) {
result += sizeOfObjectArray(addresses.size());
for (HostAddress address : addresses) {
result += HOST_ADDRESS_INSTANCE_SIZE + address.getHostText().length() * Character.BYTES;
}
}
}
if (extraFileInfo.isPresent()) {
result += sizeOf(extraFileInfo.get());
}
return result;
}
@Override
public String toString()
{
return toStringHelper(this)
.add("relativeUri", new String(relativeUri, UTF_8))
.add("start", start)
.add("end", end)
.add("fileSize", fileSize)
.toString();
}
public static class InternalHiveBlock
{
private final long end;
private final List<HostAddress> addresses;
public InternalHiveBlock(long end, List<HostAddress> addresses)
{
checkArgument(end >= 0, "block end must be >= 0");
this.end = end;
this.addresses = ImmutableList.copyOf(addresses);
}
public long getEnd()
{
return end;
}
public List<HostAddress> getAddresses()
{
return addresses;
}
}
}
| apache-2.0 |
1551250249/Wei.Lib2A | Wei.Lib2A/src/com/wei/c/utils/Manifest.java | 3058 | /*
* Copyright (C) 2014 Wei Chou (weichou2010@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wei.c.utils;
import java.lang.ref.WeakReference;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
/**
* @author 周伟 Wei Chou(weichou2010@gmail.com)
*/
public class Manifest {
private static WeakReference<PackageInfo> ref;
private static PackageInfo getPackageInfo(Context context) {
PackageInfo info = null;
if(ref != null) info = ref.get();
if(info == null) {
try {
info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); //0代表是获取版本信息
ref = new WeakReference<PackageInfo>(info);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
return info;
}
public static String getVersionName(Context context) {
return getPackageInfo(context).versionName;
}
public static int getVersionCode(Context context) {
return getPackageInfo(context).versionCode;
}
/**
* 有以下三个属性:<br>
* android:name<br>
* android:resource 可通过Bundle.getInt()获取到<br>
* android:value 可通过getString()、getFloat()、getBoolean()获取到<br>
*
* @author WeiChou
*/
public static class MetaData {
private static WeakReference<Bundle> ref;
private static Bundle getBundle(Context context) {
Bundle b = null;
if(ref != null) b = ref.get();
if(b == null) {
try {
ApplicationInfo appi = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
b = appi.metaData;
ref = new WeakReference<Bundle>(b);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
return b;
}
public static int getResourceId(Context context, String keyName) {
return getBundle(context).getInt(keyName);
}
public static String getString(Context context, String keyName) {
return getBundle(context).getString(keyName);
}
public static boolean getBoolean(Context context, String keyName, boolean defValue) {
return getBundle(context).getBoolean(keyName, defValue);
}
public static float getFloat(Context context, String keyName, float defValue) {
return getBundle(context).getFloat(keyName, defValue);
}
}
}
| apache-2.0 |
pine613/RxBindroid | rxbindroid/src/test/java/moe/pine/rx/bindroid/view/OnSubscribeViewDetachedFromWindowFirstTest.java | 3419 | /**
* 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
* <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.
*/
package moe.pine.rx.bindroid.view;
import android.view.View;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.robolectric.RobolectricTestRunner;
import rx.Observable;
import rx.Subscriber;
import rx.observers.TestSubscriber;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@RunWith(RobolectricTestRunner.class)
public class OnSubscribeViewDetachedFromWindowFirstTest {
@Test
public void testGivenSubscriptionWhenViewDetachedThenUnsubscribesAndRemovesListener() {
final Subscriber<View> subscriber = spy(new TestSubscriber<View>());
final View view = mock(View.class);
final Observable<View> observable = Observable.create(new OnSubscribeViewDetachedFromWindowFirst(view));
observable.subscribe(subscriber);
verify(subscriber, never()).onNext(view);
verify(subscriber, never()).onError(Matchers.any(Throwable.class));
verify(subscriber, never()).onCompleted();
final ArgumentCaptor<View.OnAttachStateChangeListener> captor =
ArgumentCaptor.forClass(View.OnAttachStateChangeListener.class);
verify(view).addOnAttachStateChangeListener(captor.capture());
final View.OnAttachStateChangeListener listener = captor.getValue();
Assert.assertNotNull("Should have added listener on subscription.", listener);
listener.onViewDetachedFromWindow(view);
verify(subscriber, never()).onError(Matchers.any(Throwable.class));
verify(subscriber).onNext(view);
verify(subscriber).onCompleted();
verify(view).removeOnAttachStateChangeListener(listener);
}
@Test
public void testGivenSubscriptionWhenUnsubscribedThenStateListenerRemoved() {
final Subscriber<View> subscriber = spy(new TestSubscriber<View>());
final View view = mock(View.class);
final Observable<View> observable = Observable.create(new OnSubscribeViewDetachedFromWindowFirst(view));
observable.subscribe(subscriber).unsubscribe();
verify(subscriber, never()).onNext(view);
verify(subscriber, never()).onError(Matchers.any(Throwable.class));
verify(subscriber, never()).onCompleted();
final ArgumentCaptor<View.OnAttachStateChangeListener> captor =
ArgumentCaptor.forClass(View.OnAttachStateChangeListener.class);
verify(view).addOnAttachStateChangeListener(captor.capture());
final View.OnAttachStateChangeListener listener = captor.getValue();
Assert.assertNotNull("Should have added listener on subscription.", listener);
verify(view).removeOnAttachStateChangeListener(listener);
}
} | apache-2.0 |
malakasilva/carbon-identity | components/identity/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/internal/ApplicationManagementServiceComponent.java | 7233 | /*
*Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. licenses this file to you under the Apache License,
*Version 2.0 (the "License"); you may not use this file except
*in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
package org.wso2.carbon.identity.application.mgt.internal;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.identity.application.common.model.IdentityProvider;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.ApplicationManagementOSGIService;
import org.wso2.carbon.identity.application.mgt.ApplicationManagementService;
import org.wso2.carbon.identity.application.mgt.ApplicationMgtSystemConfig;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService;
/**
* @scr.component name="identity.application.management.component" immediate="true"
* @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService"
* cardinality="1..1" policy="dynamic" bind="setRegistryService"
* unbind="unsetRegistryService"
* @scr.reference name="user.realmservice.default"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1" policy="dynamic" bind="setRealmService"
* unbind="unsetRealmService"
*
* @scr.reference name="configuration.context.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService"
* cardinality="1..1" policy="dynamic"
* bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService"
*/
public class ApplicationManagementServiceComponent {
private static Log log = LogFactory.getLog(ApplicationManagementServiceComponent.class);
private static BundleContext bundleContext;
private static Map<String, ServiceProvider> fileBasedSPs = new HashMap<String, ServiceProvider>();
protected void activate(ComponentContext context) {
// Registering OAuth2Service as a OSGIService
bundleContext = context.getBundleContext();
bundleContext.registerService(ApplicationManagementService.class.getName(),
new ApplicationManagementService(), null);
bundleContext.registerService(ApplicationManagementOSGIService.class.getName(),
new ApplicationManagementOSGIService(), null);
ApplicationMgtSystemConfig.getInstance();
buidFileBasedSPList();
log.info("Identity ApplicationManagementComponent bundle is activated");
}
protected void deactivate(ComponentContext context) {
if (log.isDebugEnabled()) {
log.info("Identity ApplicationManagementComponent bundle is deactivated");
}
}
protected void setRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) {
log.info("RegistryService set in Identity ApplicationManagementComponent bundle");
}
ApplicationManagementServiceComponentHolder.setRegistryService(registryService);
}
protected void unsetRegistryService(RegistryService registryService) {
if (log.isDebugEnabled()) {
log.info("RegistryService unset in Identity ApplicationManagementComponent bundle");
}
ApplicationManagementServiceComponentHolder.setRegistryService(null);
}
protected void setRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.info("Setting the Realm Service");
}
ApplicationManagementServiceComponentHolder.setRealmService(realmService);
}
protected void unsetRealmService(RealmService realmService) {
if (log.isDebugEnabled()) {
log.info("Unsetting the Realm Service");
}
ApplicationManagementServiceComponentHolder.setRealmService(null);
}
protected void setConfigurationContextService(ConfigurationContextService configContextService) {
if (log.isDebugEnabled()) {
log.info("Setting the Configuration Context Service");
}
ApplicationManagementServiceComponentHolder.setConfigContextService(configContextService);
}
protected void unsetConfigurationContextService(ConfigurationContextService configContextService) {
if (log.isDebugEnabled()) {
log.info("Unsetting the Configuration Context Service");
}
ApplicationManagementServiceComponentHolder.setConfigContextService(null);
}
private void buidFileBasedSPList() {
String spConfigDirPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "identity"
+ File.separator + "service-providers";
FileInputStream fileInputStream = null;
File spConfigDir = new File(spConfigDirPath);
OMElement documentElement = null;
if (spConfigDir.exists()) {
for (final File fileEntry : spConfigDir.listFiles()) {
try {
if (!fileEntry.isDirectory()) {
fileInputStream = new FileInputStream(new File(fileEntry.getAbsolutePath()));
documentElement = new StAXOMBuilder(fileInputStream).getDocumentElement();
ServiceProvider sp = ServiceProvider.build(documentElement);
if (sp != null) {
fileBasedSPs.put(sp.getApplicationName(), sp);
}
}
} catch (Exception e) {
log.error("Error while loading idp from file system.", e);
} finally {
if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
}
}
public static Map<String, ServiceProvider> getFileBasedSPs() {
return fileBasedSPs;
}
}
| apache-2.0 |
erichwang/presto | presto-main/src/test/java/io/prestosql/operator/BenchmarkGroupByHash.java | 14943 | /*
* 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.prestosql.operator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.airlift.slice.XxHash64;
import io.prestosql.array.LongBigArray;
import io.prestosql.spi.Page;
import io.prestosql.spi.PageBuilder;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.type.AbstractLongType;
import io.prestosql.spi.type.Type;
import io.prestosql.spi.type.TypeOperators;
import io.prestosql.sql.gen.JoinCompiler;
import io.prestosql.type.BlockTypeOperators;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.profile.GCProfiler;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.VerboseMode;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import static io.prestosql.operator.UpdateMemory.NOOP;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.VarcharType.VARCHAR;
import static it.unimi.dsi.fastutil.HashCommon.arraySize;
@SuppressWarnings("MethodMayBeStatic")
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(2)
@Warmup(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
public class BenchmarkGroupByHash
{
private static final int POSITIONS = 10_000_000;
private static final String GROUP_COUNT_STRING = "3000000";
private static final int GROUP_COUNT = Integer.parseInt(GROUP_COUNT_STRING);
private static final int EXPECTED_SIZE = 10_000;
private static final TypeOperators TYPE_OPERATORS = new TypeOperators();
private static final BlockTypeOperators TYPE_OPERATOR_FACTORY = new BlockTypeOperators(TYPE_OPERATORS);
@Benchmark
@OperationsPerInvocation(POSITIONS)
public Object groupByHashPreCompute(BenchmarkData data)
{
GroupByHash groupByHash = new MultiChannelGroupByHash(data.getTypes(), data.getChannels(), data.getHashChannel(), EXPECTED_SIZE, false, getJoinCompiler(), TYPE_OPERATOR_FACTORY, NOOP);
data.getPages().forEach(p -> groupByHash.getGroupIds(p).process());
ImmutableList.Builder<Page> pages = ImmutableList.builder();
PageBuilder pageBuilder = new PageBuilder(groupByHash.getTypes());
for (int groupId = 0; groupId < groupByHash.getGroupCount(); groupId++) {
pageBuilder.declarePosition();
groupByHash.appendValuesTo(groupId, pageBuilder, 0);
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pageBuilder.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public Object addPagePreCompute(BenchmarkData data)
{
GroupByHash groupByHash = new MultiChannelGroupByHash(data.getTypes(), data.getChannels(), data.getHashChannel(), EXPECTED_SIZE, false, getJoinCompiler(), TYPE_OPERATOR_FACTORY, NOOP);
data.getPages().forEach(p -> groupByHash.addPage(p).process());
ImmutableList.Builder<Page> pages = ImmutableList.builder();
PageBuilder pageBuilder = new PageBuilder(groupByHash.getTypes());
for (int groupId = 0; groupId < groupByHash.getGroupCount(); groupId++) {
pageBuilder.declarePosition();
groupByHash.appendValuesTo(groupId, pageBuilder, 0);
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pageBuilder.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public Object bigintGroupByHash(SingleChannelBenchmarkData data)
{
GroupByHash groupByHash = new BigintGroupByHash(0, data.getHashEnabled(), EXPECTED_SIZE, NOOP);
data.getPages().forEach(p -> groupByHash.addPage(p).process());
ImmutableList.Builder<Page> pages = ImmutableList.builder();
PageBuilder pageBuilder = new PageBuilder(groupByHash.getTypes());
for (int groupId = 0; groupId < groupByHash.getGroupCount(); groupId++) {
pageBuilder.declarePosition();
groupByHash.appendValuesTo(groupId, pageBuilder, 0);
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pageBuilder.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public long baseline(BaselinePagesData data)
{
int hashSize = arraySize(GROUP_COUNT, 0.9f);
int mask = hashSize - 1;
long[] table = new long[hashSize];
Arrays.fill(table, -1);
long groupIds = 0;
for (Page page : data.getPages()) {
Block block = page.getBlock(0);
int positionCount = block.getPositionCount();
for (int position = 0; position < positionCount; position++) {
long value = block.getLong(position, 0);
int tablePosition = (int) (value & mask);
while (table[tablePosition] != -1 && table[tablePosition] != value) {
tablePosition++;
}
if (table[tablePosition] == -1) {
table[tablePosition] = value;
groupIds++;
}
}
}
return groupIds;
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public long baselineBigArray(BaselinePagesData data)
{
int hashSize = arraySize(GROUP_COUNT, 0.9f);
int mask = hashSize - 1;
LongBigArray table = new LongBigArray(-1);
table.ensureCapacity(hashSize);
long groupIds = 0;
for (Page page : data.getPages()) {
Block block = page.getBlock(0);
int positionCount = block.getPositionCount();
for (int position = 0; position < positionCount; position++) {
long value = BIGINT.getLong(block, position);
int tablePosition = (int) XxHash64.hash(value) & mask;
while (table.get(tablePosition) != -1 && table.get(tablePosition) != value) {
tablePosition++;
}
if (table.get(tablePosition) == -1) {
table.set(tablePosition, value);
groupIds++;
}
}
}
return groupIds;
}
private static List<Page> createBigintPages(int positionCount, int groupCount, int channelCount, boolean hashEnabled)
{
List<Type> types = Collections.nCopies(channelCount, BIGINT);
ImmutableList.Builder<Page> pages = ImmutableList.builder();
if (hashEnabled) {
types = ImmutableList.copyOf(Iterables.concat(types, ImmutableList.of(BIGINT)));
}
PageBuilder pageBuilder = new PageBuilder(types);
for (int position = 0; position < positionCount; position++) {
int rand = ThreadLocalRandom.current().nextInt(groupCount);
pageBuilder.declarePosition();
for (int numChannel = 0; numChannel < channelCount; numChannel++) {
BIGINT.writeLong(pageBuilder.getBlockBuilder(numChannel), rand);
}
if (hashEnabled) {
BIGINT.writeLong(pageBuilder.getBlockBuilder(channelCount), AbstractLongType.hash((long) rand));
}
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pages.build();
}
private static List<Page> createVarcharPages(int positionCount, int groupCount, int channelCount, boolean hashEnabled)
{
List<Type> types = Collections.nCopies(channelCount, VARCHAR);
ImmutableList.Builder<Page> pages = ImmutableList.builder();
if (hashEnabled) {
types = ImmutableList.copyOf(Iterables.concat(types, ImmutableList.of(BIGINT)));
}
PageBuilder pageBuilder = new PageBuilder(types);
for (int position = 0; position < positionCount; position++) {
int rand = ThreadLocalRandom.current().nextInt(groupCount);
Slice value = Slices.wrappedBuffer(ByteBuffer.allocate(4).putInt(rand));
pageBuilder.declarePosition();
for (int channel = 0; channel < channelCount; channel++) {
VARCHAR.writeSlice(pageBuilder.getBlockBuilder(channel), value);
}
if (hashEnabled) {
BIGINT.writeLong(pageBuilder.getBlockBuilder(channelCount), XxHash64.hash(value));
}
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pages.build();
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class BaselinePagesData
{
@Param("1")
private int channelCount = 1;
@Param("false")
private boolean hashEnabled;
@Param(GROUP_COUNT_STRING)
private int groupCount;
private List<Page> pages;
@Setup
public void setup()
{
pages = createBigintPages(POSITIONS, groupCount, channelCount, hashEnabled);
}
public List<Page> getPages()
{
return pages;
}
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class SingleChannelBenchmarkData
{
@Param("1")
private int channelCount = 1;
@Param({"true", "false"})
private boolean hashEnabled = true;
private List<Page> pages;
private List<Type> types;
private int[] channels;
@Setup
public void setup()
{
pages = createBigintPages(POSITIONS, GROUP_COUNT, channelCount, hashEnabled);
types = Collections.nCopies(1, BIGINT);
channels = new int[1];
for (int i = 0; i < 1; i++) {
channels[i] = i;
}
}
public List<Page> getPages()
{
return pages;
}
public List<Type> getTypes()
{
return types;
}
public boolean getHashEnabled()
{
return hashEnabled;
}
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class BenchmarkData
{
@Param({"1", "5", "10", "15", "20"})
private int channelCount = 1;
// todo add more group counts when JMH support programmatic ability to set OperationsPerInvocation
@Param(GROUP_COUNT_STRING)
private int groupCount = GROUP_COUNT;
@Param({"true", "false"})
private boolean hashEnabled;
@Param({"VARCHAR", "BIGINT"})
private String dataType = "VARCHAR";
private List<Page> pages;
private Optional<Integer> hashChannel;
private List<Type> types;
private int[] channels;
@Setup
public void setup()
{
switch (dataType) {
case "VARCHAR":
types = Collections.nCopies(channelCount, VARCHAR);
pages = createVarcharPages(POSITIONS, groupCount, channelCount, hashEnabled);
break;
case "BIGINT":
types = Collections.nCopies(channelCount, BIGINT);
pages = createBigintPages(POSITIONS, groupCount, channelCount, hashEnabled);
break;
default:
throw new UnsupportedOperationException("Unsupported dataType");
}
hashChannel = hashEnabled ? Optional.of(channelCount) : Optional.empty();
channels = new int[channelCount];
for (int i = 0; i < channelCount; i++) {
channels[i] = i;
}
}
public List<Page> getPages()
{
return pages;
}
public Optional<Integer> getHashChannel()
{
return hashChannel;
}
public List<Type> getTypes()
{
return types;
}
public int[] getChannels()
{
return channels;
}
}
private static JoinCompiler getJoinCompiler()
{
return new JoinCompiler(TYPE_OPERATORS);
}
public static void main(String[] args)
throws RunnerException
{
// assure the benchmarks are valid before running
BenchmarkData data = new BenchmarkData();
data.setup();
new BenchmarkGroupByHash().groupByHashPreCompute(data);
new BenchmarkGroupByHash().addPagePreCompute(data);
SingleChannelBenchmarkData singleChannelBenchmarkData = new SingleChannelBenchmarkData();
singleChannelBenchmarkData.setup();
new BenchmarkGroupByHash().bigintGroupByHash(singleChannelBenchmarkData);
Options options = new OptionsBuilder()
.verbosity(VerboseMode.NORMAL)
.include(".*" + BenchmarkGroupByHash.class.getSimpleName() + ".*")
.addProfiler(GCProfiler.class)
.jvmArgs("-Xmx10g")
.build();
new Runner(options).run();
}
}
| apache-2.0 |
HKMOpen/android-advancedrecyclerview | example/src/main/java/com/h6ah4i/android/example/advrecyclerview/demo_e_already_expanded/AlreadyExpandedGroupsExpandableExampleFragment.java | 7329 | /*
* Copyright (C) 2015 Haruki Hasegawa
*
* 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.h6ah4i.android.example.advrecyclerview.demo_e_already_expanded;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.h6ah4i.android.example.advrecyclerview.R;
import com.h6ah4i.android.example.advrecyclerview.common.data.AbstractAddRemoveExpandableDataProvider;
import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.animator.RefactoredDefaultItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.decoration.ItemShadowDecorator;
import com.h6ah4i.android.widget.advrecyclerview.decoration.SimpleListDividerDecorator;
import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager;
import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils;
public class AlreadyExpandedGroupsExpandableExampleFragment extends Fragment {
private static final String SAVED_STATE_EXPANDABLE_ITEM_MANAGER = "RecyclerViewExpandableItemManager";
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private AlreadyExpandedGroupsExpandableExampleAdapter mAdapter;
private RecyclerView.Adapter mWrappedAdapter;
private RecyclerViewExpandableItemManager mRecyclerViewExpandableItemManager;
public AlreadyExpandedGroupsExpandableExampleFragment() {
super();
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recycler_list_view, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//noinspection ConstantConditions
mRecyclerView = (RecyclerView) getView().findViewById(R.id.recycler_view);
mLayoutManager = new LinearLayoutManager(getContext());
final Parcelable eimSavedState = (savedInstanceState != null) ? savedInstanceState.getParcelable(SAVED_STATE_EXPANDABLE_ITEM_MANAGER) : null;
mRecyclerViewExpandableItemManager = new RecyclerViewExpandableItemManager(eimSavedState);
//adapter
final AlreadyExpandedGroupsExpandableExampleAdapter myItemAdapter = new AlreadyExpandedGroupsExpandableExampleAdapter(mRecyclerViewExpandableItemManager, getDataProvider());
mAdapter = myItemAdapter;
mWrappedAdapter = mRecyclerViewExpandableItemManager.createWrappedAdapter(myItemAdapter); // wrap for expanding
// Expand all group items if no saved state exists.
// The expandAll() method should be called here (before attaching the RecyclerView instance),
// because it can reduce overheads of updating item views.
if (eimSavedState == null) {
mRecyclerViewExpandableItemManager.expandAll();
}
final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator();
// Change animations are enabled by default since support-v7-recyclerview v22.
// Need to disable them when using animation indicator.
animator.setSupportsChangeAnimations(false);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mWrappedAdapter); // requires *wrapped* adapter
mRecyclerView.setItemAnimator(animator);
mRecyclerView.setHasFixedSize(false);
// additional decorations
//noinspection StatementWithEmptyBody
if (supportsViewElevation()) {
// Lollipop or later has native drop shadow feature. ItemShadowDecorator is not required.
} else {
mRecyclerView.addItemDecoration(new ItemShadowDecorator((NinePatchDrawable) ContextCompat.getDrawable(getContext(), R.drawable.material_shadow_z1)));
}
mRecyclerView.addItemDecoration(new SimpleListDividerDecorator(ContextCompat.getDrawable(getContext(), R.drawable.list_divider_h), true));
mRecyclerViewExpandableItemManager.attachRecyclerView(mRecyclerView);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save current state to support screen rotation, etc...
if (mRecyclerViewExpandableItemManager != null) {
outState.putParcelable(
SAVED_STATE_EXPANDABLE_ITEM_MANAGER,
mRecyclerViewExpandableItemManager.getSavedState());
}
}
@Override
public void onDestroyView() {
if (mRecyclerViewExpandableItemManager != null) {
mRecyclerViewExpandableItemManager.release();
mRecyclerViewExpandableItemManager = null;
}
if (mRecyclerView != null) {
mRecyclerView.setItemAnimator(null);
mRecyclerView.setAdapter(null);
mRecyclerView = null;
}
if (mWrappedAdapter != null) {
WrapperAdapterUtils.releaseAll(mWrappedAdapter);
mWrappedAdapter = null;
}
mAdapter = null;
mLayoutManager = null;
super.onDestroyView();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_e_already_expanded, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add_group_bottom_2:
mAdapter.addGroupAndChildItemsBottom(2, 3);
return true;
case R.id.menu_remove_group_bottom_2:
mAdapter.removeGroupItemsBottom(2);
return true;
case R.id.menu_clear_groups:
mAdapter.clearGroupItems();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private boolean supportsViewElevation() {
return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
}
public AbstractAddRemoveExpandableDataProvider getDataProvider() {
return ((AlreadyExpandedGroupsExpandableExampleActivity) getActivity()).getDataProvider();
}
}
| apache-2.0 |
fugeritaetas/morozko-lib | java14-morozko/org.morozko.java.mod.db/src/org/morozko/java/mod/db/dao/idgen/BasicIdGenerator.java | 2793 | /*****************************************************************
<copyright>
Morozko Java Library org.morozko.java.mod.db
Copyright (c) 2006 Morozko
All rights reserved. This program and the accompanying materials
are made available under the terms of the Apache License v2.0
which accompanies this distribution, and is available at
http://www.apache.org/licenses/
(txt version : http://www.apache.org/licenses/LICENSE-2.0.txt
html version : http://www.apache.org/licenses/LICENSE-2.0.html)
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
</copyright>
*****************************************************************/
/*
* @(#)BasicIdGenerator.java
*
* @project : org.morozko.java.mod.db
* @package : org.morozko.java.mod.db.dao.idgen
* @creation : 09/ago/06
* @license : META-INF/LICENSE.TXT
*/
package org.morozko.java.mod.db.dao.idgen;
import java.io.InputStream;
import java.util.Properties;
import org.morozko.java.core.cfg.ConfigException;
import org.morozko.java.core.log.BasicLogObject;
import org.morozko.java.mod.db.connect.ConnectionFactory;
import org.morozko.java.mod.db.dao.DAOException;
import org.morozko.java.mod.db.dao.DAOID;
import org.morozko.java.mod.db.dao.IdGenerator;
import org.w3c.dom.Element;
/**
* <p></p>
*
* @author mfranci
*
*/
public abstract class BasicIdGenerator extends BasicLogObject implements IdGenerator {
/* (non-Javadoc)
* @see org.opinf.jlib.std.cfg.ConfigurableObject#configureProperties(java.io.InputStream)
*/
public void configureProperties(InputStream source) throws ConfigException {
}
/* (non-Javadoc)
* @see org.opinf.jlib.std.cfg.ConfigurableObject#configureXML(java.io.InputStream)
*/
public void configureXML(InputStream source) throws ConfigException {
}
/* (non-Javadoc)
* @see org.opinf.jlib.std.cfg.ConfigurableObject#configure(org.w3c.dom.Element)
*/
public void configure(Element tag) throws ConfigException {
}
/* (non-Javadoc)
* @see org.opinf.jlib.std.cfg.ConfigurableObject#configure(java.util.Properties)
*/
public void configure(Properties props) throws ConfigException {
}
/* (non-Javadoc)
* @see org.morozko.java.mod.db.dao.IdGenerator#generateID()
*/
public abstract DAOID generateId() throws DAOException;
private ConnectionFactory connectionFactory;
/**
* @return the connectionFactory
*/
public ConnectionFactory getConnectionFactory() {
return connectionFactory;
}
/**
* @param connectionFactory the connectionFactory to set
*/
public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
}
| apache-2.0 |
ramoncenturion/apps-informaticas | src/componente/pared/TipoRevestimientoExtPared.java | 677 | package componente.pared;
public enum TipoRevestimientoExtPared {
LADRILLO_VISTA("ladrillo a la vista",1), CERAMICOS("cerámico",2),
MADERA("madera",3), PIEDRA("piedra",4),
PETROS_CALIZOS("pétreos y calizos",3), LIGEROS("ligeros",4);
private String descripcion;
private int valor;
private TipoRevestimientoExtPared(String descripcion, int valor){
this.setDescripcion(descripcion);
this.setValor(valor);
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public int getValor() {
return valor;
}
public void setValor(int valor) {
this.valor = valor;
}
}
| apache-2.0 |
fhanik/spring-security | ldap/src/test/java/org/springframework/security/ldap/userdetails/LdapUserDetailsImplTests.java | 1502 | /*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.ldap.userdetails;
import org.junit.Test;
import org.springframework.security.core.CredentialsContainer;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests {@link LdapUserDetailsImpl}
*
* @author Joe Grandja
*/
public class LdapUserDetailsImplTests {
@Test
public void credentialsAreCleared() {
LdapUserDetailsImpl.Essence mutableLdapUserDetails = new LdapUserDetailsImpl.Essence();
mutableLdapUserDetails.setDn("uid=username1,ou=people,dc=example,dc=com");
mutableLdapUserDetails.setUsername("username1");
mutableLdapUserDetails.setPassword("password");
LdapUserDetails ldapUserDetails = mutableLdapUserDetails.createUserDetails();
assertThat(ldapUserDetails).isInstanceOf(CredentialsContainer.class);
ldapUserDetails.eraseCredentials();
assertThat(ldapUserDetails.getPassword()).isNull();
}
}
| apache-2.0 |
opetrovski/development | oscm-dataservice-unittests/javasrc-it/org/oscm/domobjects/ProductReferenceIT.java | 6982 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: 10.06.2009
*
*******************************************************************************/
package org.oscm.domobjects;
import static org.oscm.test.Numbers.TIMESTAMP;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.Assert;
import org.junit.Test;
import org.oscm.internal.types.enumtypes.ServiceAccessType;
import org.oscm.internal.types.enumtypes.ServiceStatus;
import org.oscm.internal.types.enumtypes.ServiceType;
import org.oscm.test.ReflectiveCompare;
import org.oscm.test.data.Organizations;
import org.oscm.test.data.TechnicalProducts;
/**
* Test of the product reference object.
*/
public class ProductReferenceIT extends DomainObjectTestBase {
private Product prod1;
private Product prod2;
private String organizationId;
private final List<ProductReference> references = new ArrayList<ProductReference>();
@Override
protected void dataSetup() throws Exception {
Organization organization = Organizations.createOrganization(mgr);
organizationId = organization.getOrganizationId();
// create technical product
TechnicalProduct tProd = TechnicalProducts.createTechnicalProduct(mgr,
organization, "TP_ID", false, ServiceAccessType.LOGIN);
// create two products for it
prod1 = new Product();
prod1.setVendor(organization);
prod1.setProductId("Product1");
prod1.setTechnicalProduct(tProd);
prod1.setProvisioningDate(TIMESTAMP);
prod1.setStatus(ServiceStatus.ACTIVE);
prod1.setType(ServiceType.TEMPLATE);
PriceModel pi = new PriceModel();
prod1.setPriceModel(pi);
ParameterSet emptyPS1 = new ParameterSet();
prod1.setParameterSet(emptyPS1);
mgr.persist(prod1);
prod2 = new Product();
prod2.setVendor(organization);
prod2.setProductId("Product2");
prod2.setTechnicalProduct(tProd);
prod2.setProvisioningDate(TIMESTAMP);
prod2.setStatus(ServiceStatus.ACTIVE);
prod2.setType(ServiceType.TEMPLATE);
pi = new PriceModel();
prod2.setPriceModel(pi);
ParameterSet emptyPS2 = new ParameterSet();
prod2.setParameterSet(emptyPS2);
mgr.persist(prod2);
}
@Test
public void testCreation() throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
doTestAdd();
return null;
}
});
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
doTestCheckCreation();
return null;
}
});
}
@Test
public void testDeletion() throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
doTestAdd();
return null;
}
});
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
doTestDelete();
return null;
}
});
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
doCheckDeletion();
return null;
}
});
}
@Test
public void testCreateWrongParameters() throws Exception {
Product prod1 = new Product();
Product prod2 = new Product();
TechnicalProduct tProd1 = new TechnicalProduct();
TechnicalProduct tProd2 = new TechnicalProduct();
tProd1.setKey(1);
tProd2.setKey(2);
prod1.setTechnicalProduct(tProd1);
prod2.setTechnicalProduct(tProd2);
try {
new ProductReference(prod1, prod2);
Assert.fail("Products do not refer to same technical product, so creation must fail");
} catch (IllegalArgumentException e) {
}
}
@Test
public void testRetrieveFromProduct() throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
doTestAdd();
return null;
}
});
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
doRetrieveFromProduct();
return null;
}
});
}
private void doTestAdd() throws Exception {
ProductReference prodRef = new ProductReference(prod1, prod2);
mgr.persist(prodRef);
references.add(prodRef);
}
private void doTestCheckCreation() throws Exception {
for (ProductReference ref : references) {
DomainObject<?> savedRef = mgr.getReference(ProductReference.class,
ref.getKey());
// now compare the objects themselves
Assert.assertTrue(ReflectiveCompare.showDiffs(ref, savedRef),
ReflectiveCompare.compare(ref, savedRef));
}
}
private void doTestDelete() {
for (ProductReference ref : references) {
DomainObject<?> savedRef = mgr.find(ProductReference.class,
ref.getKey());
mgr.remove(savedRef);
}
}
private void doCheckDeletion() throws Exception {
for (ProductReference ref : references) {
DomainObject<?> savedRef = mgr.find(ProductReference.class,
ref.getKey());
Assert.assertNull("Object was deleted and must not be found",
savedRef);
}
}
private void doRetrieveFromProduct() {
Organization organization = new Organization();
organization.setOrganizationId(organizationId);
organization = (Organization) mgr.find(organization);
Product product = new Product();
product.setVendor(organization);
product.setProductId(prod1.getProductId());
product = (Product) mgr.find(product);
List<Product> compatibleProducts = product.getCompatibleProductsList();
Assert.assertEquals("Wrong number of compatible products stored", 1,
compatibleProducts.size());
Product compatibleProduct = compatibleProducts.get(0);
Assert.assertTrue(
ReflectiveCompare.showDiffs(prod2, compatibleProduct),
ReflectiveCompare.compare(prod2, compatibleProduct));
}
}
| apache-2.0 |
marques-work/gocd | api/api-secret-configs-v2/src/main/java/com/thoughtworks/go/apiv2/secretconfigs/representers/SecretConfigRepresenter.java | 2981 | /*
* Copyright 2021 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.apiv2.secretconfigs.representers;
import com.thoughtworks.go.api.base.OutputWriter;
import com.thoughtworks.go.api.representers.ConfigurationPropertyRepresenter;
import com.thoughtworks.go.api.representers.ErrorGetter;
import com.thoughtworks.go.api.representers.JsonReader;
import com.thoughtworks.go.config.SecretConfig;
import com.thoughtworks.go.spark.Routes;
import org.apache.commons.collections4.CollectionUtils;
import java.util.Collections;
import java.util.Map;
public class SecretConfigRepresenter {
public static void toJSON(OutputWriter jsonWriter, SecretConfig secretConfig) {
if (secretConfig == null)
return;
jsonWriter.addLinks(linksWriter -> linksWriter
.addLink("self", Routes.SecretConfigsAPI.id(secretConfig.getId()))
.addAbsoluteLink("doc", Routes.SecretConfigsAPI.DOC)
.addLink("find", Routes.SecretConfigsAPI.find()))
.add("id", secretConfig.getId())
.add("plugin_id", secretConfig.getPluginId())
.addIfNotNull("description", secretConfig.getDescription());
if (secretConfig.hasErrors()) {
Map<String, String> fieldMapping = Collections.singletonMap("pluginId", "plugin_id");
jsonWriter.addChild("errors", errorWriter -> new ErrorGetter(fieldMapping).toJSON(errorWriter, secretConfig));
}
jsonWriter.addChildList("properties", listWriter -> {
ConfigurationPropertyRepresenter.toJSON(listWriter, secretConfig.getConfiguration());
});
if (!CollectionUtils.isEmpty(secretConfig.getRules())) {
jsonWriter.addChildList("rules", rulesWriter -> RulesRepresenter.toJSON(rulesWriter, secretConfig.getRules()));
}
}
public static SecretConfig fromJSON(JsonReader jsonReader) {
SecretConfig secretConfig = new SecretConfig(jsonReader.getString("id"), jsonReader.getString("plugin_id"));
jsonReader.optString("description").ifPresent(description -> secretConfig.setDescription(description));
secretConfig.addConfigurations(ConfigurationPropertyRepresenter.fromJSONArray(jsonReader, "properties"));
jsonReader.readArrayIfPresent("rules", array -> {
secretConfig.setRules(RulesRepresenter.fromJSON(array));
});
return secretConfig;
}
}
| apache-2.0 |
AlberWall/android-component-build | libB/src/androidTest/java/component/libb/ExampleInstrumentedTest.java | 737 | package component.libb;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("component.libb.test", appContext.getPackageName());
}
}
| apache-2.0 |
pongasoft/kiwidoc | kiwidoc/com.pongasoft.kiwidoc.builder/src/main/java/com/pongasoft/kiwidoc/builder/serializer/EnumSerializer.java | 1281 |
/*
* Copyright (c) 2012 Yan Pujante
*
* 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.pongasoft.kiwidoc.builder.serializer;
import com.pongasoft.util.core.enums.EnumCodec;
/**
* @author yan@pongasoft.com
*/
public class EnumSerializer<E extends Enum<E>, C> implements Serializer<E, C>
{
private final Class<E> _enumClass;
/**
* Constructor
*/
public EnumSerializer(Class<E> enumClass)
{
_enumClass = enumClass;
}
public E deserialize(C context, Object objectToDeserialize) throws SerializerException
{
return EnumCodec.INSTANCE.decode(_enumClass, (String) objectToDeserialize);
}
public Object serialize(E objectToSerialize) throws SerializerException
{
return EnumCodec.INSTANCE.encode(objectToSerialize);
}
}
| apache-2.0 |
mleger/CoordinateSelection | test/mechanical/modeling/components/MechanicalComponentTest.java | 2851 | package mechanical.modeling.components;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MechanicalComponentTest {
@Test
public void createMechanicalComponent_allThePublicGetterMethodsShouldWork() {
ReferenceFrame cs1 = new ReferenceFrame("cs1");
ReferenceFrame cs2 = new ReferenceFrame("cs2");
MechanicalComponent c1 = new MechanicalComponent ("c1", cs1, cs2, ComponentType.RIGID_BODY);
assertEquals("The mechanical edge is not returning its name properly","c1",c1.getName());
assertEquals("The mechanical edge is not returning its source referene frame properly",cs1,c1.getSourceReferenceFrame());
assertEquals("The mechanical edge is not returning its target referene frame properly",cs2,c1.getTargetReferenceFrame());
assertEquals("The mechanical component is not returning the type properly",ComponentType.RIGID_BODY,c1.getType());
}
@Test
public void createMechanicalComponent_allProtectedGetterMethodsShouldWork() {
ReferenceFrame cs1 = new ReferenceFrame("cs1");
ReferenceFrame cs2 = new ReferenceFrame("cs2");
MechanicalComponent c1 = new MechanicalComponent ("c1", cs1, cs2, ComponentType.RIGID_BODY);
MechanicalEdge rotEdge = c1.getRotationalEdge();
assertEquals("The mechanical edge is not returning the domain properly",Domain.ROTATIONAL,rotEdge.getDomain());
assertEquals("The mechanical edge variables were not proprely formatted","phi_c1",rotEdge.getVariables()[0]);
assertEquals("The mechanical edge variables were not proprely formatted","theta_c1",rotEdge.getVariables()[1]);
assertEquals("The mechanical edge variables were not proprely formatted","psi_c1",rotEdge.getVariables()[2]);
assertEquals("The mechanical edge is not reteruning the right number of variables",3,rotEdge.getNumberOfVariables());
assertEquals("The mechanical edge is not returning the type properly",ComponentType.RIGID_BODY,rotEdge.getType());
MechanicalEdge transEdge = c1.getTranslationalEdge();
assertEquals("The mechanical edge is not returning the domain properly",Domain.TRANSLATIONAL,transEdge.getDomain());
assertEquals("The mechanical edge variables were not proprely formatted","x_c1",transEdge.getVariables()[0]);
assertEquals("The mechanical edge variables were not proprely formatted","y_c1",transEdge.getVariables()[1]);
assertEquals("The mechanical edge variables were not proprely formatted","z_c1",transEdge.getVariables()[2]);
assertEquals("The mechanical edge is not reteruning the right number of variables",3,transEdge.getNumberOfVariables());
assertEquals("The mechanical edge is not returning the type properly",ComponentType.RIGID_BODY,transEdge.getType());
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201601/cm/BiddingStrategyServiceInterfacequery.java | 1743 |
package com.google.api.ads.adwords.jaxws.v201601.cm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Returns a list of bidding strategies that match the query.
*
* @param query The SQL-like AWQL query string.
* @throws ApiException when there are one or more errors with the request.
*
*
* <p>Java class for query element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="query">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="query" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"query"
})
@XmlRootElement(name = "query")
public class BiddingStrategyServiceInterfacequery {
protected String query;
/**
* Gets the value of the query property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getQuery() {
return query;
}
/**
* Sets the value of the query property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQuery(String value) {
this.query = value;
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201509/cm/SystemServingStatus.java | 1221 |
package com.google.api.ads.adwords.jaxws.v201509.cm;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SystemServingStatus.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="SystemServingStatus">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="ELIGIBLE"/>
* <enumeration value="RARELY_SERVED"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "SystemServingStatus")
@XmlEnum
public enum SystemServingStatus {
/**
*
* Criterion is eligible to serve.
*
*
*/
ELIGIBLE,
/**
*
* Indicates low search volume.
* <p>For more information, visit
* <a href="https://support.google.com/adwords/answer/2616014">Low Search Volume</a>.</p>
*
*
*/
RARELY_SERVED;
public String value() {
return name();
}
public static SystemServingStatus fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
bshp/midPoint | model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbacLightInitialProjection.java | 1135 | /*
* Copyright (c) 2010-2017 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.model.intest.rbac;
import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.xml.ns._public.common.common_3.PartialProcessingOptionsType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import static com.evolveum.midpoint.xml.ns._public.common.common_3.PartialProcessingTypeType.SKIP;
/**
* @author mederly
*
*/
@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestRbacLightInitialProjection extends TestRbac {
@Override
protected ModelExecuteOptions getDefaultOptions() {
return ModelExecuteOptions.createInitialPartialProcessing(
new PartialProcessingOptionsType().inbound(SKIP).projection(SKIP));
}
}
| apache-2.0 |
jffnothing/phoenix-4.0.0-incubating | phoenix-core/src/it/java/org/apache/phoenix/end2end/MultiCfQueryExecIT.java | 9309 | /*
* 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.phoenix.end2end;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Properties;
import org.junit.Test;
import org.apache.phoenix.util.PhoenixRuntime;
public class MultiCfQueryExecIT extends BaseClientManagedTimeIT {
private static final String MULTI_CF = "MULTI_CF";
protected static void initTableValues(long ts) throws Exception {
ensureTableCreated(getUrl(),MULTI_CF,null, ts-2);
String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + ts;
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(url, props);
conn.setAutoCommit(true);
// Insert all rows at ts
PreparedStatement stmt = conn.prepareStatement(
"upsert into " +
"MULTI_CF(" +
" ID, " +
" TRANSACTION_COUNT, " +
" CPU_UTILIZATION, " +
" DB_CPU_UTILIZATION," +
" UNIQUE_USER_COUNT," +
" F.RESPONSE_TIME," +
" G.RESPONSE_TIME)" +
"VALUES (?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, "000000000000001");
stmt.setInt(2, 100);
stmt.setBigDecimal(3, BigDecimal.valueOf(0.5));
stmt.setBigDecimal(4, BigDecimal.valueOf(0.2));
stmt.setInt(5, 1000);
stmt.setLong(6, 11111);
stmt.setLong(7, 11112);
stmt.execute();
stmt.setString(1, "000000000000002");
stmt.setInt(2, 200);
stmt.setBigDecimal(3, BigDecimal.valueOf(2.5));
stmt.setBigDecimal(4, BigDecimal.valueOf(2.2));
stmt.setInt(5, 2000);
stmt.setLong(6, 2222);
stmt.setLong(7, 22222);
stmt.execute();
}
@Test
public void testConstantCount() throws Exception {
long ts = nextTimestamp();
String query = "SELECT count(1) from multi_cf";
String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(url, props);
try {
initTableValues(ts);
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals(2, rs.getLong(1));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testCFToDisambiguateInSelectOnly1() throws Exception {
long ts = nextTimestamp();
String query = "SELECT F.RESPONSE_TIME,G.RESPONSE_TIME from multi_cf where ID = '000000000000002'";
String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(url, props);
try {
initTableValues(ts);
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals(2222, rs.getLong(1));
assertEquals(22222, rs.getLong(2));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testCFToDisambiguateInSelectOnly2() throws Exception {
long ts = nextTimestamp();
String query = "SELECT F.RESPONSE_TIME,G.RESPONSE_TIME from multi_cf where TRANSACTION_COUNT = 200";
String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(url, props);
try {
initTableValues(ts);
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals(2222, rs.getLong(1));
assertEquals(22222, rs.getLong(2));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testCFToDisambiguate1() throws Exception {
long ts = nextTimestamp();
String query = "SELECT F.RESPONSE_TIME,G.RESPONSE_TIME from multi_cf where F.RESPONSE_TIME = 2222";
String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(url, props);
try {
initTableValues(ts);
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals(2222, rs.getLong(1));
assertEquals(22222, rs.getLong(2));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testCFToDisambiguate2() throws Exception {
long ts = nextTimestamp();
String query = "SELECT F.RESPONSE_TIME,G.RESPONSE_TIME from multi_cf where G.RESPONSE_TIME-1 = F.RESPONSE_TIME";
String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(url, props);
try {
initTableValues(ts);
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals(11111, rs.getLong(1));
assertEquals(11112, rs.getLong(2));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testDefaultCFToDisambiguate() throws Exception {
long ts = nextTimestamp();
initTableValues(ts);
String ddl = "ALTER TABLE multi_cf ADD response_time BIGINT";
String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 3);
Connection conn = DriverManager.getConnection(url);
conn.createStatement().execute(ddl);
conn.close();
String dml = "upsert into " +
"MULTI_CF(" +
" ID, " +
" RESPONSE_TIME)" +
"VALUES ('000000000000003', 333)";
url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 4); // Run query at timestamp 5
conn = DriverManager.getConnection(url);
conn.createStatement().execute(dml);
conn.commit();
conn.close();
String query = "SELECT ID,RESPONSE_TIME from multi_cf where RESPONSE_TIME = 333";
url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
conn = DriverManager.getConnection(url);
try {
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals("000000000000003", rs.getString(1));
assertEquals(333, rs.getLong(2));
assertFalse(rs.next());
} finally {
conn.close();
}
}
@Test
public void testEssentialColumnFamilyForRowKeyFilter() throws Exception {
long ts = nextTimestamp();
String query = "SELECT F.RESPONSE_TIME,G.RESPONSE_TIME from multi_cf where SUBSTR(ID, 15) = '2'";
String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
Properties props = new Properties(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(url, props);
try {
initTableValues(ts);
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals(2222, rs.getLong(1));
assertEquals(22222, rs.getLong(2));
assertFalse(rs.next());
} finally {
conn.close();
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/UpdateProjectRequest.java | 7308 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.devicefarm.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Represents a request to the update project operation.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/devicefarm-2015-06-23/UpdateProject" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateProjectRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) of the project whose name to update.
* </p>
*/
private String arn;
/**
* <p>
* A string that represents the new name of the project that you are updating.
* </p>
*/
private String name;
/**
* <p>
* The number of minutes a test run in the project executes before it times out.
* </p>
*/
private Integer defaultJobTimeoutMinutes;
/**
* <p>
* The Amazon Resource Name (ARN) of the project whose name to update.
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the project whose name to update.
*/
public void setArn(String arn) {
this.arn = arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the project whose name to update.
* </p>
*
* @return The Amazon Resource Name (ARN) of the project whose name to update.
*/
public String getArn() {
return this.arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the project whose name to update.
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the project whose name to update.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateProjectRequest withArn(String arn) {
setArn(arn);
return this;
}
/**
* <p>
* A string that represents the new name of the project that you are updating.
* </p>
*
* @param name
* A string that represents the new name of the project that you are updating.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* A string that represents the new name of the project that you are updating.
* </p>
*
* @return A string that represents the new name of the project that you are updating.
*/
public String getName() {
return this.name;
}
/**
* <p>
* A string that represents the new name of the project that you are updating.
* </p>
*
* @param name
* A string that represents the new name of the project that you are updating.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateProjectRequest withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The number of minutes a test run in the project executes before it times out.
* </p>
*
* @param defaultJobTimeoutMinutes
* The number of minutes a test run in the project executes before it times out.
*/
public void setDefaultJobTimeoutMinutes(Integer defaultJobTimeoutMinutes) {
this.defaultJobTimeoutMinutes = defaultJobTimeoutMinutes;
}
/**
* <p>
* The number of minutes a test run in the project executes before it times out.
* </p>
*
* @return The number of minutes a test run in the project executes before it times out.
*/
public Integer getDefaultJobTimeoutMinutes() {
return this.defaultJobTimeoutMinutes;
}
/**
* <p>
* The number of minutes a test run in the project executes before it times out.
* </p>
*
* @param defaultJobTimeoutMinutes
* The number of minutes a test run in the project executes before it times out.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateProjectRequest withDefaultJobTimeoutMinutes(Integer defaultJobTimeoutMinutes) {
setDefaultJobTimeoutMinutes(defaultJobTimeoutMinutes);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getArn() != null)
sb.append("Arn: ").append(getArn()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getDefaultJobTimeoutMinutes() != null)
sb.append("DefaultJobTimeoutMinutes: ").append(getDefaultJobTimeoutMinutes());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateProjectRequest == false)
return false;
UpdateProjectRequest other = (UpdateProjectRequest) obj;
if (other.getArn() == null ^ this.getArn() == null)
return false;
if (other.getArn() != null && other.getArn().equals(this.getArn()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getDefaultJobTimeoutMinutes() == null ^ this.getDefaultJobTimeoutMinutes() == null)
return false;
if (other.getDefaultJobTimeoutMinutes() != null && other.getDefaultJobTimeoutMinutes().equals(this.getDefaultJobTimeoutMinutes()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getDefaultJobTimeoutMinutes() == null) ? 0 : getDefaultJobTimeoutMinutes().hashCode());
return hashCode;
}
@Override
public UpdateProjectRequest clone() {
return (UpdateProjectRequest) super.clone();
}
}
| apache-2.0 |
Legioth/vaadin | client/src/main/java/com/vaadin/client/ui/dd/VHtml5DragEvent.java | 3432 | /*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.client.ui.dd;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.dom.client.NativeEvent;
/**
* Helper class to access html5 style drag events.
*
* TODO Gears support ?
*/
public class VHtml5DragEvent extends NativeEvent {
protected VHtml5DragEvent() {
}
public final native JsArrayString getTypes()
/*-{
// IE does not support types, return some basic values
return this.dataTransfer.types ? this.dataTransfer.types : ["Text","Url","Html"];
}-*/;
public final native String getDataAsText(String type)
/*-{
var v = this.dataTransfer.getData(type);
return v;
}-*/;
/**
* Works on FF 3.6 and possibly with gears.
*
* @param index
* @return
*/
public final native String getFileAsString(int index)
/*-{
if(this.dataTransfer.files.length > 0 && this.dataTransfer.files[0].getAsText) {
return this.dataTransfer.files[index].getAsText("UTF-8");
}
return null;
}-*/;
public final native void setDropEffect(String effect)
/*-{
try {
this.dataTransfer.dropEffect = effect;
} catch (e){}
}-*/;
public final native String getEffectAllowed()
/*-{
return this.dataTransfer.effectAllowed;
}-*/;
public final native void setEffectAllowed(String effect)
/*-{
this.dataTransfer.effectAllowed = effect;
}-*/;
public final native int getFileCount()
/*-{
return this.dataTransfer.files ? this.dataTransfer.files.length : 0;
}-*/;
public final native VHtml5File getFile(int fileIndex)
/*-{
return this.dataTransfer.files[fileIndex];
}-*/;
/**
* Detects if dropped element is a file. <br>
* Always returns <code>true</code> on Safari even if the dropped element is
* a folder.
*/
public final native boolean isFile(int fileIndex)
/*-{
// Chrome >= v21 and Opera >= v?
if (this.dataTransfer.items) {
var item = this.dataTransfer.items[fileIndex];
if (typeof item.webkitGetAsEntry == "function") {
var entry = item.webkitGetAsEntry();
if (typeof entry !== "undefined" && entry !== null) {
return entry.isFile;
}
}
}
// Zero sized files without a type are also likely to be folders
var file = this.dataTransfer.files[fileIndex];
if (file.size == 0 && !file.type) {
return false;
}
// TODO Make it detect folders on all browsers
return true;
}-*/;
public final native void setHtml5DataFlavor(String flavor, String data)
/*-{
this.dataTransfer.setData(flavor, data);
}-*/;
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/transform/ServerSideEncryptionMarshaller.java | 2352 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.macie2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.macie2.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ServerSideEncryptionMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ServerSideEncryptionMarshaller {
private static final MarshallingInfo<String> ENCRYPTIONTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("encryptionType").build();
private static final MarshallingInfo<String> KMSMASTERKEYID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("kmsMasterKeyId").build();
private static final ServerSideEncryptionMarshaller instance = new ServerSideEncryptionMarshaller();
public static ServerSideEncryptionMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ServerSideEncryption serverSideEncryption, ProtocolMarshaller protocolMarshaller) {
if (serverSideEncryption == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(serverSideEncryption.getEncryptionType(), ENCRYPTIONTYPE_BINDING);
protocolMarshaller.marshall(serverSideEncryption.getKmsMasterKeyId(), KMSMASTERKEYID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
powertac/powertac-server | household-customer/src/main/java/org/powertac/householdcustomer/enumerations/Mode.java | 1122 | /*
* Copyright 2009-2012 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.powertac.householdcustomer.enumerations;
/**
* This enumerator defines the four different modes of semi-automatic appliances
* Mode one: the washing has to finish within five hours from the loading point.
* Mode two: finish within five to ten hours. Mode three: finish in more than
* ten hours, but at the same day. Mode four: finish laundry between loading
* point and end of day.
*
* @author Antonios Chrysopoulos
* @version 1.5, Date: 2.25.12
*/
public enum Mode
{
One, Two, Three, Four
}
| apache-2.0 |
apigee-labs/apibaas-monitoring | service/src/main/java/org/apache/usergrid/apm/service/util/MailConfig.java | 3122 | /*
* 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.apm.service.util;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class MailConfig {
private static final Log log = LogFactory.getLog(MailConfig.class);
String senderEmail;
String smtpUser;
String senderName;
String senderPassword;
String emailtoCC;
String adminUsers;
private static MailConfig mailConfig = null;
private MailConfig() {
}
public static MailConfig getMailConfig() {
if (mailConfig != null)
return mailConfig;
Properties props = new Properties();
try {
props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/email.properties"));
} catch (IOException e) {
e.printStackTrace();
}
String senderEmail = props.getProperty("mail.smtp.sender.email");
String smtpUser = props.getProperty("mail.smtp.user");
String senderName = props.getProperty("mail.smtp.sender.name");
String senderPassword = props.getProperty("senderPassword");
String emailtoCC = props.getProperty("instaopsOpsEmailtoCC");
String adminUsers = props.getProperty("adminUsers");
mailConfig = new MailConfig();
mailConfig.senderEmail = senderEmail;
mailConfig.smtpUser = smtpUser;
mailConfig.senderName = senderName;
mailConfig.senderPassword = senderPassword;
mailConfig.emailtoCC = emailtoCC;
mailConfig.adminUsers = adminUsers;
return mailConfig;
}
public String getSenderEmail() {
return senderEmail;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
public String getSmtpUser() {
return smtpUser;
}
public void setSmtpUser(String smtpUser) {
this.smtpUser = smtpUser;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getSenderPassword() {
return senderPassword;
}
public void setSenderPassword(String senderPassword) {
this.senderPassword = senderPassword;
}
public String getEmailtoCC() {
return emailtoCC;
}
public void setEmailtoCC(String emailtoCC) {
this.emailtoCC = emailtoCC;
}
public String getAdminUsers() {
return adminUsers;
}
public void setAdminUsers(String adminUsers) {
this.adminUsers = adminUsers;
}
}
| apache-2.0 |
China-ls/wechat4java | src/main/java/weixin/popular/bean/datacube/getcardcardinfo/CardInfo.java | 1336 | package weixin.popular.bean.datacube.getcardcardinfo;
import com.google.gson.annotations.SerializedName;
import weixin.popular.bean.datacube.getcardbizuininfo.BizuinInfo;
/**
* 获取免费券数据接口-提交对象<br>
* 1. 该接口目前仅支持拉取免费券(优惠券、团购券、折扣券、礼品券)的卡券相关数据,暂不支持特殊票券(电影票、会议门票、景区门票、飞机票)数据。<br>
* 2. 查询时间区间需<=62天,否则报错;<br>
* 3. 传入时间格式需严格参照示例填写如”2015-06-15”,否则报错;<br>
* 4. 该接口只能拉取非当天的数据,不能拉取当天的卡券数据,否则报错。
*
* @author Moyq5
*/
public class CardInfo extends BizuinInfo {
/**
* 卡券ID。填写后,指定拉出该卡券的相关数据。<br>
* 必填:否
*/
@SerializedName("card_id")
private String cardId;
/**
* 卡券ID。填写后,指定拉出该卡券的相关数据。
*
* @return 卡券ID
*/
public String getCardId() {
return cardId;
}
/**
* 卡券ID。填写后,指定拉出该卡券的相关数据。<br>
* 必填:否
*
* @param cardId 卡券ID
*/
public void setCardId(String cardId) {
this.cardId = cardId;
}
}
| apache-2.0 |
midhunhk/ae-apps-library | modules/sms-api/src/main/java/com/ae/apps/lib/api/sms/package-info.java | 749 | /*
* Copyright (c) 2018 Midhun Harikumar
*
* 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.
*
*/
/**
* GatewayApi that provides an abstraction over the Android SMS API
*
* @since 4.0
* @author midhunhk
*/
package com.ae.apps.lib.api.sms; | apache-2.0 |
harsha89/carbon-apimgt | components/apimgt/org.wso2.carbon.apimgt.keymgt/src/main/java/org/wso2/carbon/apimgt/keymgt/internal/APIKeyMgtServiceComponent.java | 16648 | /*
*Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. licenses this file to you under the Apache License,
*Version 2.0 (the "License"); you may not use this file except
*in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
package org.wso2.carbon.apimgt.keymgt.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.apimgt.impl.dto.ThrottleProperties;
import org.wso2.carbon.apimgt.keymgt.ScopesIssuer;
import org.wso2.carbon.apimgt.keymgt.events.APIMOAuthEventInterceptor;
import org.wso2.carbon.apimgt.keymgt.handlers.SessionDataPublisherImpl;
import org.wso2.carbon.apimgt.keymgt.issuers.AbstractScopesIssuer;
import org.wso2.carbon.apimgt.keymgt.issuers.PermissionBasedScopeIssuer;
import org.wso2.carbon.apimgt.keymgt.issuers.RoleBasedScopesIssuer;
import org.wso2.carbon.apimgt.keymgt.listeners.KeyManagerUserOperationListener;
import org.wso2.carbon.apimgt.keymgt.util.APIKeyMgtDataHolder;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
import org.wso2.carbon.identity.application.authentication.framework.AuthenticationDataPublisher;
import org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.listener.UserOperationEventListener;
import org.wso2.carbon.user.core.service.RealmService;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
@Component(
name = "api.keymgt.component",
immediate = true)
public class APIKeyMgtServiceComponent {
private static Log log = LogFactory.getLog(APIKeyMgtServiceComponent.class);
private static KeyManagerUserOperationListener listener = null;
private ServiceRegistration serviceRegistration = null;
private boolean tokenRevocationEnabled;
@Activate
protected void activate(ComponentContext ctxt) {
try {
APIKeyMgtDataHolder.initData();
listener = new KeyManagerUserOperationListener();
serviceRegistration = ctxt.getBundleContext().registerService(UserOperationEventListener.class.getName(), listener, null);
log.debug("Key Manager User Operation Listener is enabled.");
// Checking token revocation feature enabled config
tokenRevocationEnabled = APIManagerConfiguration.isTokenRevocationEnabled();
if (tokenRevocationEnabled) {
// object creation for implemented OAuthEventInterceptor interface in IS
APIMOAuthEventInterceptor interceptor = new APIMOAuthEventInterceptor();
// registering the interceptor class to the bundle
serviceRegistration = ctxt.getBundleContext().registerService(OAuthEventInterceptor.class.getName(), interceptor, null);
// Creating an event adapter to receive token revocation messages
configureTokenRevocationEventPublisher();
configureCacheInvalidationEventPublisher();
log.debug("Key Manager OAuth Event Interceptor is enabled.");
} else {
log.debug("Token Revocation Notifier Feature is disabled.");
}
// registering logout token revoke listener
try {
SessionDataPublisherImpl dataPublisher = new SessionDataPublisherImpl();
ctxt.getBundleContext().registerService(AuthenticationDataPublisher.class.getName(), dataPublisher, null);
log.debug("SessionDataPublisherImpl bundle is activated");
} catch (Throwable e) {
log.error("SessionDataPublisherImpl bundle activation Failed", e);
}
// loading white listed scopes
List<String> whitelist = null;
APIManagerConfigurationService configurationService = org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService();
if (configurationService != null) {
// Read scope whitelist from Configuration.
whitelist = configurationService.getAPIManagerConfiguration().getProperty(APIConstants.WHITELISTED_SCOPES);
// If whitelist is null, default scopes will be put.
if (whitelist == null) {
whitelist = new ArrayList<String>();
whitelist.add(APIConstants.OPEN_ID_SCOPE_NAME);
whitelist.add(APIConstants.DEVICE_SCOPE_PATTERN);
}
} else {
log.debug("API Manager Configuration couldn't be read successfully. Scopes might not work correctly.");
}
PermissionBasedScopeIssuer permissionBasedScopeIssuer = new PermissionBasedScopeIssuer();
RoleBasedScopesIssuer roleBasedScopesIssuer = new RoleBasedScopesIssuer();
APIKeyMgtDataHolder.addScopesIssuer(permissionBasedScopeIssuer.getPrefix(), permissionBasedScopeIssuer);
APIKeyMgtDataHolder.addScopesIssuer(roleBasedScopesIssuer.getPrefix(), roleBasedScopesIssuer);
if (log.isDebugEnabled()) {
log.debug("Permission based scope Issuer and Role based scope issuers are loaded.");
}
ScopesIssuer.loadInstance(whitelist);
if (log.isDebugEnabled()) {
log.debug("Identity API Key Mgt Bundle is started.");
}
} catch (Exception e) {
log.error("Failed to initialize key management service.", e);
}
}
@Deactivate
protected void deactivate(ComponentContext context) {
if (serviceRegistration != null) {
serviceRegistration.unregister();
}
if (log.isDebugEnabled()) {
log.info("Key Manager User Operation Listener is deactivated.");
}
}
@Reference(
name = "registry.service",
service = org.wso2.carbon.registry.core.service.RegistryService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetRegistryService")
protected void setRegistryService(RegistryService registryService) {
APIKeyMgtDataHolder.setRegistryService(registryService);
if (log.isDebugEnabled()) {
log.debug("Registry Service is set in the API KeyMgt bundle.");
}
}
protected void unsetRegistryService(RegistryService registryService) {
APIKeyMgtDataHolder.setRegistryService(null);
if (log.isDebugEnabled()) {
log.debug("Registry Service is unset in the API KeyMgt bundle.");
}
}
@Reference(
name = "user.realmservice.default",
service = org.wso2.carbon.user.core.service.RealmService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) {
APIKeyMgtDataHolder.setRealmService(realmService);
if (log.isDebugEnabled()) {
log.debug("Realm Service is set in the API KeyMgt bundle.");
}
}
protected void unsetRealmService(RealmService realmService) {
APIKeyMgtDataHolder.setRealmService(null);
if (log.isDebugEnabled()) {
log.debug("Realm Service is unset in the API KeyMgt bundle.");
}
}
@Reference(
name = "api.manager.config.service",
service = org.wso2.carbon.apimgt.impl.APIManagerConfigurationService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetAPIManagerConfigurationService")
protected void setAPIManagerConfigurationService(APIManagerConfigurationService amcService) {
if (log.isDebugEnabled()) {
log.debug("API manager configuration service bound to the API handlers");
}
APIKeyMgtDataHolder.setAmConfigService(amcService);
ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(amcService);
}
protected void unsetAPIManagerConfigurationService(APIManagerConfigurationService amcService) {
if (log.isDebugEnabled()) {
log.debug("API manager configuration service unbound from the API handlers");
}
APIKeyMgtDataHolder.setAmConfigService(null);
ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(null);
}
/**
* Add scope issuer to the map.
* @param scopesIssuer scope issuer.
*/
@Reference(
name = "scope.issuer.service",
service = org.wso2.carbon.apimgt.keymgt.issuers.AbstractScopesIssuer.class,
cardinality = ReferenceCardinality.MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
unbind = "removeScopeIssuers")
protected void addScopeIssuer(AbstractScopesIssuer scopesIssuer) {
APIKeyMgtDataHolder.addScopesIssuer(scopesIssuer.getPrefix(), scopesIssuer);
}
/**
* unset scope issuer.
* @param scopesIssuer
*/
protected void removeScopeIssuers(AbstractScopesIssuer scopesIssuer) {
APIKeyMgtDataHolder.setScopesIssuers(null);
}
/**
* Get INetAddress by host name or IP Address
*
* @param host name or host IP String
* @return InetAddress
* @throws java.net.UnknownHostException
*/
private InetAddress getHostAddress(String host) throws UnknownHostException {
String[] splittedString = host.split("\\.");
boolean value = checkIfIP(splittedString);
if (!value) {
return InetAddress.getByName(host);
}
byte[] byteAddress = new byte[4];
for (int i = 0; i < splittedString.length; i++) {
if (Integer.parseInt(splittedString[i]) > 127) {
byteAddress[i] = Integer.valueOf(Integer.parseInt(splittedString[i]) - 256).byteValue();
} else {
byteAddress[i] = Byte.parseByte(splittedString[i]);
}
}
return InetAddress.getByAddress(byteAddress);
}
/**
* Check the hostname is IP or String
*
* @param ip IP
* @return true/false
*/
private boolean checkIfIP(String[] ip) {
for (int i = 0; i < ip.length; i++) {
try {
Integer.parseInt(ip[i]);
} catch (NumberFormatException ex) {
return false;
}
}
return true;
}
/**
* Method to configure wso2event type event adapter to be used for token revocation.
*/
private void configureTokenRevocationEventPublisher() {
OutputEventAdapterConfiguration adapterConfiguration = new OutputEventAdapterConfiguration();
adapterConfiguration.setName(APIConstants.TOKEN_REVOCATION_EVENT_PUBLISHER);
adapterConfiguration.setType(APIConstants.BLOCKING_EVENT_TYPE);
adapterConfiguration.setMessageFormat(APIConstants.BLOCKING_EVENT_TYPE);
Map<String, String> adapterParameters = new HashMap<>();
APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
ThrottleProperties.TrafficManager trafficManager = configuration.getThrottleProperties().getTrafficManager();
adapterParameters.put(APIConstants.RECEIVER_URL, trafficManager.getReceiverUrlGroup());
adapterParameters.put(APIConstants.AUTHENTICATOR_URL, trafficManager.getAuthUrlGroup());
adapterParameters.put(APIConstants.USERNAME, trafficManager.getUsername());
adapterParameters.put(APIConstants.PASSWORD, trafficManager.getPassword());
adapterParameters.put(APIConstants.PROTOCOL, trafficManager.getType());
adapterParameters.put(APIConstants.PUBLISHING_MODE, APIConstants.NON_BLOCKING);
adapterParameters.put(APIConstants.PUBLISHING_TIME_OUT, "0");
adapterConfiguration.setStaticProperties(adapterParameters);
try {
ServiceReferenceHolder.getInstance().getOutputEventAdapterService().create(adapterConfiguration);
} catch (OutputEventAdapterException e) {
log.warn("Exception occurred while creating token revocation event adapter. Token Revocation may not " + "work properly", e);
}
}
/**
* Method to configure wso2event type event adapter to be used for token revocation.
*/
private void configureCacheInvalidationEventPublisher() {
OutputEventAdapterConfiguration adapterConfiguration = new OutputEventAdapterConfiguration();
adapterConfiguration.setName(APIConstants.CACHE_INVALIDATION_EVENT_PUBLISHER);
adapterConfiguration.setType(APIConstants.BLOCKING_EVENT_TYPE);
adapterConfiguration.setMessageFormat(APIConstants.BLOCKING_EVENT_TYPE);
Map<String, String> adapterParameters = new HashMap<>();
APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
ThrottleProperties.TrafficManager trafficManager = configuration.getThrottleProperties().getTrafficManager();
adapterParameters.put(APIConstants.RECEIVER_URL, trafficManager.getReceiverUrlGroup());
adapterParameters.put(APIConstants.AUTHENTICATOR_URL, trafficManager.getAuthUrlGroup());
adapterParameters.put(APIConstants.USERNAME, trafficManager.getUsername());
adapterParameters.put(APIConstants.PASSWORD, trafficManager.getPassword());
adapterParameters.put(APIConstants.PROTOCOL, trafficManager.getType());
adapterParameters.put(APIConstants.PUBLISHING_MODE, APIConstants.NON_BLOCKING);
adapterParameters.put(APIConstants.PUBLISHING_TIME_OUT, "0");
adapterConfiguration.setStaticProperties(adapterParameters);
try {
ServiceReferenceHolder.getInstance().getOutputEventAdapterService().create(adapterConfiguration);
} catch (OutputEventAdapterException e) {
log.warn("Exception occurred while creating cache invalidation event adapter. Cache invalidation may not " +
"work properly", e);
}
}
/**
* Initialize the Output EventAdapter Service dependency
*
* @param outputEventAdapterService Output EventAdapter Service reference
*/
@Reference(
name = "event.output.adapter.service",
service = org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetOutputEventAdapterService")
protected void setOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
ServiceReferenceHolder.getInstance().setOutputEventAdapterService(outputEventAdapterService);
}
/**
* De-reference the Output EventAdapter Service dependency.
*
* @param outputEventAdapterService
*/
protected void unsetOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
ServiceReferenceHolder.getInstance().setOutputEventAdapterService(null);
}
}
| apache-2.0 |
rometools/rome | rome-core/src/main/java/com/rometools/rome/io/impl/RSS092Generator.java | 6078 | /*
* Copyright 2004 Sun Microsystems, 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.rometools.rome.io.impl;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Element;
import com.rometools.rome.feed.rss.Category;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Cloud;
import com.rometools.rome.feed.rss.Enclosure;
import com.rometools.rome.feed.rss.Item;
import com.rometools.rome.feed.rss.Source;
import com.rometools.rome.io.FeedException;
/**
* Feed Generator for RSS 0.92
*/
public class RSS092Generator extends RSS091UserlandGenerator {
public RSS092Generator() {
this("rss_0.92", "0.92");
}
protected RSS092Generator(final String type, final String version) {
super(type, version);
}
@Override
protected void populateChannel(final Channel channel, final Element eChannel) {
super.populateChannel(channel, eChannel);
final Cloud cloud = channel.getCloud();
if (cloud != null) {
eChannel.addContent(generateCloud(cloud));
}
}
protected Element generateCloud(final Cloud cloud) {
final Element eCloud = new Element("cloud", getFeedNamespace());
final String domain = cloud.getDomain();
if (domain != null) {
eCloud.setAttribute(new Attribute("domain", domain));
}
final int port = cloud.getPort();
if (port != 0) {
eCloud.setAttribute(new Attribute("port", String.valueOf(port)));
}
final String path = cloud.getPath();
if (path != null) {
eCloud.setAttribute(new Attribute("path", path));
}
final String registerProcedure = cloud.getRegisterProcedure();
if (registerProcedure != null) {
eCloud.setAttribute(new Attribute("registerProcedure", registerProcedure));
}
final String protocol = cloud.getProtocol();
if (protocol != null) {
eCloud.setAttribute(new Attribute("protocol", protocol));
}
return eCloud;
}
// Another one to thanks DW for
protected int getNumberOfEnclosures(final List<Enclosure> enclosures) {
if (!enclosures.isEmpty()) {
return 1;
} else {
return 0;
}
}
@Override
protected void populateItem(final Item item, final Element eItem, final int index) {
super.populateItem(item, eItem, index);
final Source source = item.getSource();
if (source != null) {
eItem.addContent(generateSourceElement(source));
}
final List<Enclosure> enclosures = item.getEnclosures();
for (int i = 0; i < getNumberOfEnclosures(enclosures); i++) {
eItem.addContent(generateEnclosure(enclosures.get(i)));
}
final List<Category> categories = item.getCategories();
for (final Category category : categories) {
eItem.addContent(generateCategoryElement(category));
}
}
protected Element generateSourceElement(final Source source) {
final Element sourceElement = new Element("source", getFeedNamespace());
final String url = source.getUrl();
if (url != null) {
sourceElement.setAttribute(new Attribute("url", url));
}
sourceElement.addContent(source.getValue());
return sourceElement;
}
protected Element generateEnclosure(final Enclosure enclosure) {
final Element enclosureElement = new Element("enclosure", getFeedNamespace());
final String url = enclosure.getUrl();
if (url != null) {
enclosureElement.setAttribute("url", url);
}
final long length = enclosure.getLength();
if (length != 0) {
enclosureElement.setAttribute("length", String.valueOf(length));
}
final String type = enclosure.getType();
if (type != null) {
enclosureElement.setAttribute("type", type);
}
return enclosureElement;
}
protected Element generateCategoryElement(final Category category) {
final Element categoryElement = new Element("category", getFeedNamespace());
final String domain = category.getDomain();
if (domain != null) {
categoryElement.setAttribute("domain", domain);
}
categoryElement.addContent(category.getValue());
return categoryElement;
}
@Override
protected void checkChannelConstraints(final Element eChannel) throws FeedException {
checkNotNullAndLength(eChannel, "title", 0, -1);
checkNotNullAndLength(eChannel, "description", 0, -1);
checkNotNullAndLength(eChannel, "link", 0, -1);
}
@Override
protected void checkImageConstraints(final Element eImage) throws FeedException {
checkNotNullAndLength(eImage, "title", 0, -1);
checkNotNullAndLength(eImage, "url", 0, -1);
}
@Override
protected void checkTextInputConstraints(final Element eTextInput) throws FeedException {
checkNotNullAndLength(eTextInput, "title", 0, -1);
checkNotNullAndLength(eTextInput, "description", 0, -1);
checkNotNullAndLength(eTextInput, "name", 0, -1);
checkNotNullAndLength(eTextInput, "link", 0, -1);
}
@Override
protected void checkItemsConstraints(final Element parent) throws FeedException {
}
@Override
protected void checkItemConstraints(final Element eItem) throws FeedException {
}
}
| apache-2.0 |
kuali/kpme | tk-lm/impl/src/main/java/org/kuali/kpme/tklm/leave/payout/authorization/LeavePayoutAuthorizer.java | 1955 | /**
* Copyright 2004-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kpme.tklm.leave.payout.authorization;
import java.util.Map;
import org.kuali.kpme.core.authorization.KPMEMaintenanceDocumentAuthorizerBase;
import org.kuali.kpme.core.role.KPMERoleMemberAttribute;
import org.kuali.rice.kew.api.document.DocumentStatus;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.krad.document.Document;
@SuppressWarnings("deprecation")
public class LeavePayoutAuthorizer extends KPMEMaintenanceDocumentAuthorizerBase {
private static final long serialVersionUID = 8233452898311917126L;
protected void addRoleQualification(Object dataObject, Map<String, String> attributes) {
super.addRoleQualification(dataObject, attributes);
attributes.put(KPMERoleMemberAttribute.DEPARTMENT.getRoleMemberAttributeName(), "%");
attributes.put(KPMERoleMemberAttribute.GROUP_KEY_CODE.getRoleMemberAttributeName(), "%");
attributes.put(KPMERoleMemberAttribute.LOCATION.getRoleMemberAttributeName(), "%");
}
@Override
public boolean canEdit(Document document, Person user) {
if(document.getDocumentHeader().hasWorkflowDocument()) {
//only editable when creating a new document.
return(document.getDocumentHeader().getWorkflowDocument().getStatus().equals(DocumentStatus.INITIATED));
}
return false;
}
}
| apache-2.0 |
tec-ustp/SIIEScanner | app/src/main/java/st/ustp/siie/scanner/fragments/ScannerSenderFragment.java | 6748 | package st.ustp.siie.scanner.fragments;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import st.zudamue.support.android.adapter.ItemDataSet;
import st.zudamue.support.android.adapter.ItemViewHolder;
import st.zudamue.support.android.adapter.RecyclerViewAdapter;
import st.ustp.siie.scanner.R;
import st.ustp.siie.scanner.item.ItemSenderUser;
import st.ustp.siie.scanner.model.Department;
import st.ustp.siie.scanner.model.User;
/**
* Created by siie2 on 5/23/17.
*/
public class ScannerSenderFragment extends AbstractMainFrag {
private View rootView;
private RecyclerViewAdapter adapter;
private RecyclerView recyclerView;
private User user;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//Reade saved
if( savedInstanceState == null ){
savedInstanceState = this.getArguments();
}
if( savedInstanceState != null )
this.loadSaved( savedInstanceState );
this.rootView = inflater.inflate( R.layout.main_send, container, false );
this.recyclerView = (RecyclerView) this.rootView.findViewById( R.id.rv );
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager( 1, StaggeredGridLayoutManager.VERTICAL );
recyclerView.setLayoutManager( layoutManager );
this.adapter = new RecyclerViewAdapter( this.context );
this.adapter.registerFactory( R.layout.main_send_client, new RecyclerViewAdapter.ViewHolderFactory() {
@Override
public ItemViewHolder factory(View view) {
return new ItemSenderUser( view )
.setUserClicked(new ItemViewHolder.DataSetCallback<ItemSenderUser.DataSet>() {
@Override
protected void onDataSetCallback(ItemSenderUser.DataSet itemDataSet, int adapterPosition) {
userClicked( itemDataSet );
}
})
;
}
});
if( currentDepartment != null ){
this.onDepartmentChange(currentDepartment);
}
//this.adapter.addItem( new ItemSenderUser.ItemReaderContentExamAccessNoteDataSet( this.user = new User( "bin", "Mester Bin")));
recyclerView.setAdapter( this.adapter );
return rootView;
}
private void userClicked( ItemSenderUser.DataSet dataSet ) {
this.user = dataSet.getUser();
if( onChoseUser != null ) this.onChoseUser.onChoseUser( user );
this.scanCallback.newScannerNow( user );
}
@Override
public void onSaveInstanceState( Bundle outState ) {
this.onSaveArguments( outState );
}
@Override
public void onSaveArguments( Bundle outState ) {
super.onSaveArguments( outState );
if( user != null )
outState.putString( User.INSTANCE, user.getKey() );
}
/**
* Carregar os departamentos
* @param savedInstanceState
*/
protected void loadSaved( Bundle savedInstanceState ){
super.loadSaved( savedInstanceState );
String colaboradorKey = savedInstanceState.getString( User.INSTANCE );
this.user = ( this.currentDepartment != null )? this.currentDepartment.getColaborador( colaboradorKey ) : null;
}
@Override
public void onDepartmentChange(final Department department) {
this.currentDepartment = department;
adapter.clear();
if( currentDepartment == null ){
return;
}
for ( User user : ScannerSenderFragment.this.currentDepartment.getColaborators() ) {
ItemSenderUser.DataSet userDataSet = ItemSenderUser.newDataSet( user );
adapter.addItem( userDataSet );
}
reLayout();
this.user = null;
}
private void reLayout( ) {
int orientation = this.context.getResources().getConfiguration().orientation;
int newCountItem = adapter.getItemCount();
int spanCount;
if( newCountItem <= 1) {
spanCount = 1;
}else if(newCountItem >= 3 && orientation == Configuration.ORIENTATION_LANDSCAPE ){
spanCount = 3;
}else spanCount = 2;
StaggeredGridLayoutManager current = (StaggeredGridLayoutManager) this.recyclerView.getLayoutManager();
if( current.getSpanCount() != spanCount ){
current.setSpanCount( spanCount );
}
}
@Override
public void onClientExit(Department department, final User colaborador ) {
if( this.currentDepartment != null && currentDepartment.equals(department) ){
for( int i = 0; i<adapter.getItemCount(); i++ ){
ItemSenderUser.DataSet user = (ItemSenderUser.DataSet) adapter.getItemAt( i );
if( user.getUser().getKey().equals( colaborador.getKey() ) ) {
adapter.removeItem( i );
reLayout();
break;
}
}
if( ! this.currentDepartment.hasColaborador() )
this.currentDepartment = null;
}
}
@Override
public void onClientEnter(Department department, final User user) {
ItemDataSet userItem = ItemSenderUser.newDataSet(user);
if( this.currentDepartment == null )
this.currentDepartment = department;
//Quando o utilizador ja existe na lista entao sair
if( this.adapter.exist( userItem ) ) return;
if( currentDepartment.equals(department)){
adapter.addItem( userItem );
reLayout( );
}
}
@Override
public void onFetchPhotos(User user, String photoData) {
if( this.currentDepartment != null && currentDepartment.existsUser(user) ){
int iCount = 0;
for( ItemDataSet itemDataSet : this.adapter.getListItem() ){
ItemSenderUser.DataSet colaboradorSend = (ItemSenderUser.DataSet) itemDataSet;
if( colaboradorSend.getUser().equals(user) ){
this.adapter.notifyItemChanged( iCount );
break;
}
iCount ++;
}
}
}
@Override
public void onClose( boolean connect ) {
if( this.adapter.getItemCount() > 0 ) {
adapter.clear();
adapter.notifyDataSetChanged();
}
}
}
| apache-2.0 |
WI13C/Jgui-creator | code/data/src/main/java/de/dhbw/wi13c/jguicreator/data/uielements/UiElementData.java | 679 | package de.dhbw.wi13c.jguicreator.data.uielements;
import de.dhbw.wi13c.jguicreator.data.GuiVisitor;
public abstract class UiElementData<T>
{
private Datafield<T> datafield;
private String name;
public UiElementData()
{
initDatafield();
}
protected abstract void initDatafield();
public abstract void accept(GuiVisitor visitor);
public Datafield<T> getDatafield()
{
return datafield;
}
public abstract T getValue();
public abstract void setValue(T value);
public void setDatafield(Datafield datafield)
{
this.datafield = datafield;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
| apache-2.0 |
data-integrations/wrangler | wrangler-core/src/test/java/io/cdap/directives/transformation/TextDistanceMeasureTest.java | 2751 | /*
* Copyright © 2017-2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.directives.transformation;
import io.cdap.wrangler.TestingRig;
import io.cdap.wrangler.api.Row;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
/**
* Tests {@link TextDistanceMeasure}
*/
public class TextDistanceMeasureTest {
private static final List<Row> ROWS = Arrays.asList(
// Correct Row.
new Row("string1", "This is an example for distance measure.").add("string2", "This test is made of works that " +
"are similar. This is an example for distance measure."),
// Row that has one string empty.
new Row("string1", "This is an example for distance measure.").add("string2", ""),
// Row that has one string as different type.
new Row("string1", "This is an example for distance measure.").add("string2", 1L),
// Row that has only one column.
new Row("string1", "This is an example for distance measure.")
);
@Test
public void testTextDistanceMeasure() throws Exception {
String[] directives = new String[] {
"text-distance cosine string1 string2 cosine",
"text-distance euclidean string1 string2 euclidean",
"text-distance block-distance string1 string2 block_distance",
"text-distance identity string1 string2 identity",
"text-distance block string1 string2 block",
"text-distance dice string1 string2 dice",
"text-distance jaro string1 string2 jaro",
"text-distance longest-common-subsequence string1 string2 lcs1",
"text-distance longest-common-substring string1 string2 lcs2",
"text-distance overlap-cofficient string1 string2 oc",
"text-distance damerau-levenshtein string1 string2 dl",
"text-distance simon-white string1 string2 sw",
"text-distance levenshtein string1 string2 levenshtein",
};
List<Row> results = TestingRig.execute(directives, ROWS);
Assert.assertTrue(results.size() == 4);
Assert.assertEquals(15, results.get(0).width());
Assert.assertEquals(15, results.get(1).width());
Assert.assertEquals(15, results.get(2).width());
Assert.assertEquals(14, results.get(3).width());
}
}
| apache-2.0 |
kjetilv/vanadis | lang/piji/src/main/java/vanadis/lang/piji/fun/ArraySetFunction.java | 3454 | /*
* Copyright 2009 Kjetil Valstadsve
*
* 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 vanadis.lang.piji.fun;
import vanadis.core.lang.EntryPoint;
import vanadis.lang.piji.*;
import vanadis.lang.piji.hold.PrimitiveDataHolder;
import vanadis.lang.piji.hold.PrimitiveIntegerHolder;
import vanadis.lang.piji.hold.PrimitiveNumberHolder;
import java.lang.reflect.Array;
@EntryPoint("Reflection")
public final class ArraySetFunction extends AbstractFunction {
@EntryPoint("Reflection")
public ArraySetFunction(Context ctx) {
super("<array> <index> <value>", 3, ctx);
}
@Override
public Object apply(Context context, Expression[] args)
throws Throwable {
checkArgumentCount(args);
Object object = args[2].evaluate(context);
if (!(object instanceof PrimitiveIntegerHolder)) {
throw new BadArgumentException
(this + " got non-integer index: " + object);
}
int index = ((PrimitiveIntegerHolder) object).getInt();
Object value = args[3].evaluate(context);
Object array = args[1].evaluate(context);
if (!array.getClass().isArray()) {
throw new EvaluationException
(this + " got non-array " + array +
", index:" + index + ", value:" + value);
}
if (array instanceof int[]) {
Array.setInt(array, index,
((PrimitiveNumberHolder) value).getInt());
} else if (array instanceof Object[]) {
Array.set(array, index, value);
} else if (array instanceof char[]) {
Array.setChar(array, index,
((PrimitiveDataHolder) value).getChar());
} else if (array instanceof long[]) {
Array.setLong(array, index,
((PrimitiveNumberHolder) value).getLong());
} else if (array instanceof float[]) {
Array.setFloat(array, index,
((PrimitiveNumberHolder) value).getFloat());
} else if (array instanceof double[]) {
Array.setDouble(array, index,
((PrimitiveNumberHolder) value).getDouble());
} else if (array instanceof byte[]) {
Array.setByte(array, index,
((PrimitiveNumberHolder) value).getByte());
} else if (array instanceof short[]) {
Array.setShort(array, index,
((PrimitiveNumberHolder) value).getShort());
} else if (array instanceof boolean[]) {
Array.setBoolean(array, index,
((PrimitiveDataHolder) value).getBoolean());
} else {
throw new EvaluationException
(this + " got unknown array type: " + array +
", index:" + index + ", value:" + value);
}
return value;
}
}
| apache-2.0 |
droolsjbpm/jbpm-wb | jbpm-wb-process-runtime/jbpm-wb-process-runtime-client/src/main/java/org/jbpm/workbench/pr/client/editors/diagram/ProcessDiagramWidgetViewImpl.java | 9095 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.workbench.pr.client.editors.diagram;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RequiresResize;
import elemental2.dom.HTMLDivElement;
import elemental2.dom.HTMLElement;
import org.gwtbootstrap3.client.ui.Anchor;
import org.gwtbootstrap3.client.ui.constants.IconType;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.jbpm.workbench.pr.events.ProcessDiagramExpandEvent;
import org.uberfire.client.callbacks.Callback;
import org.uberfire.client.views.pfly.widgets.D3;
import org.uberfire.ext.widgets.common.client.common.BusyPopup;
@Dependent
@Templated
public class ProcessDiagramWidgetViewImpl extends Composite implements ProcessDiagramWidgetView,
RequiresResize {
@Inject
@DataField("processDiagramDiv")
private HTMLDivElement processDiagramDiv;
@Inject
@DataField("diagramContainerDiv")
private HTMLDivElement diagramContainerDiv;
@Inject
@DataField("message")
@Named("span")
private HTMLElement heading;
@Inject
@DataField
private HTMLDivElement alert;
@Inject
@DataField("expand-diagram")
private Anchor expandAnchor;
@Inject
private ZoomControlView zoomControlView;
@Inject
private Event<ProcessDiagramExpandEvent> processDiagramExpandEvent;
private Callback<String> nodeSelectionCallback;
private Callback<String> nodeSelectionDoubleClick;
private D3 d3;
private boolean isExpand = false;
protected boolean isDoubleClick;
public void setD3Component(D3 d3) {
this.d3 = d3;
}
@PostConstruct
public void init() {
d3 = D3.Builder.get();
expandAnchor.setIcon(IconType.EXPAND);
this.isDoubleClick = false;
processDiagramDiv.id = DOM.createUniqueId();
}
@Override
public void setOnDiagramNodeSelectionCallback(final Callback<String> callback) {
this.nodeSelectionCallback = callback;
}
@Override
public void setOnNodeSelectionDoubleClick(final Callback<String> callback) {
this.nodeSelectionDoubleClick = callback;
}
@Override
public void displayImage(final String svgContent) {
processDiagramDiv.innerHTML = svgContent;
final D3 svg = d3.select("#" + processDiagramDiv.id + " svg");
String[] viewBoxValues = svg.attr("viewBox").toString().split(" ");
double svgWidth = Double.parseDouble(viewBoxValues[2]);
double svgHeight = Double.parseDouble(viewBoxValues[3]);
svg.attr("width", svgWidth);
svg.attr("height", svgHeight);
final D3.Zoom zoom = d3.zoom();
double[] scaleExtent = new double[2];
scaleExtent[0] = 0.1;
scaleExtent[1] = 3;
zoom.scaleExtent(scaleExtent);
D3.CallbackFunction callback = () -> {
D3.ZoomEvent event = d3.getEvent();
double k = event.getTransform().getK();
event.getTransform().setX(((svgWidth * k) - svgWidth) / 2);
event.getTransform().setY(((svgHeight * k) - svgHeight) / 2);
refreshExtent(zoom, 0, 0, svgWidth * k, svgHeight * k);
svg.attr("transform",
event.getTransform());
zoomControlView.disablePlusButton(k >= 3);
zoomControlView.disableMinusButton(k <= 0.1);
double zoomTxt = Math.round(100 + (event.getTransform().getK() - 1) * 100);
zoomControlView.setZoomText(zoomTxt + "%");
};
svg.call(zoom.on("zoom",
callback));
zoomControlView.setScaleTo100Command(() -> zoom.transform(svg.transition().duration(500), d3.getZoomIdentity()));
zoomControlView.setScaleTo300Command(() -> zoom.scaleTo(svg.transition().duration(500), 3.0));
zoomControlView.setScaleTo150Command(() -> zoom.scaleTo(svg.transition().duration(500), 1.5));
zoomControlView.setScaleTo50Command(() -> zoom.scaleTo(svg.transition().duration(500), 0.5));
zoomControlView.setScaleMinusCommand(() -> zoom.scaleBy(svg.transition().duration(200), 0.95));
zoomControlView.setScalePlusCommand(() -> zoom.scaleBy(svg.transition().duration(200), 1.05));
processDiagramDiv.appendChild(zoomControlView.getElement());
if (nodeSelectionCallback == null) {
return;
}
final D3.Selection selectAll = select();
d3.select("svg").on("dblclick.zoom", () -> {
});
selectAll.on("mouseenter", () -> {
Object target = D3.Builder.get().getEvent().getCurrentTarget();
D3 node = d3.select(target);
node.style("cursor", "pointer");
node.attr("opacity", 0.7);
});
selectAll.on("mouseleave", () -> {
Object target = D3.Builder.get().getEvent().getCurrentTarget();
D3 node = d3.select(target);
node.style("cursor", "default");
node.attr("opacity", 1);
});
DoubleClickTimer timer = new DoubleClickTimer();
selectAll.on("click", () -> {
isDoubleClick = false;
Object target = D3.Builder.get().getEvent().getCurrentTarget();
D3 node = d3.select(target);
timer.setTarget(node);
timer.schedule(50);
});
selectAll.on("dblclick", () -> {
isDoubleClick = true;
timer.cancel();
Object target = D3.Builder.get().getEvent().getCurrentTarget();
D3 node = d3.select(target);
nodeSelectionDoubleClick.callback((String) node.attr("bpmn2nodeid"));
});
}
protected native D3.Selection select() /*-{
return $wnd.d3.selectAll("[bpmn2nodeid]");
}-*/;
private void refreshExtent(D3.Zoom zoom, double minX, double minY, double maxX, double maxY) {
double[][] translateExtent = new double[2][2];
translateExtent[0][0] = minX;
translateExtent[0][1] = minY;
translateExtent[1][0] = maxX;
translateExtent[1][1] = maxY;
zoom.translateExtent(translateExtent);
}
@Override
public void displayMessage(final String message) {
alert.classList.remove("hidden");
heading.textContent = message;
}
@Override
public void onResize() {
int height = getParent().getOffsetHeight();
int width = getParent().getOffsetWidth();
setPixelSize(width,
height);
}
@Override
public void showBusyIndicator(final String message) {
BusyPopup.showMessage(message);
}
@Override
public void hideBusyIndicator() {
BusyPopup.close();
}
@Override
public void expandDiagramContainer() {
diagramContainerDiv.classList.remove("col-md-10");
diagramContainerDiv.classList.add("col-md-12");
isExpand = true;
}
@EventHandler("expand-diagram")
protected void onClickExpandDiagram(final ClickEvent event) {
if (isExpand) {
diagramContainerDiv.classList.add("col-md-10");
diagramContainerDiv.classList.remove("col-md-12");
isExpand = false;
expandAnchor.setIcon(IconType.EXPAND);
} else {
expandDiagramContainer();
isExpand = true;
expandAnchor.setIcon(IconType.COMPRESS);
}
processDiagramExpandEvent.fire(new ProcessDiagramExpandEvent(isExpand));
}
@Override
public void disableExpandAnchor() {
expandAnchor.setEnabled(false);
}
private class DoubleClickTimer extends Timer {
public D3 node;
public void setTarget(D3 node) {
this.node = node;
}
@Override
public void run() {
if(!isDoubleClick) {
nodeSelectionCallback.callback((String) node.attr("bpmn2nodeid"));
}
}
}
public String getProcessDiagramDivId() {
return processDiagramDiv.id;
}
}
| apache-2.0 |
fabiowin98/sqldocgen | org.dgl.sqldocgen/src/org/dgl/manager/LangManager.java | 388 | package org.dgl.manager;
public class LangManager extends ConfigurationManager {
private static final String PROPERTIES_FILE_EXTENSION = ".properties";
public LangManager(String country) throws Exception {
super(country + PROPERTIES_FILE_EXTENSION);
}
public String translate(String attributeName) throws Exception {
return get(attributeName);
}
}
| apache-2.0 |
andy-goryachev/PasswordSafe | src/goryachev/swing/theme/AgCheckBoxUI.java | 1404 | // Copyright © 2009-2022 Andy Goryachev <andy@goryachev.com>
package goryachev.swing.theme;
import goryachev.swing.Theme;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.UIDefaults;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicCheckBoxUI;
import javax.swing.plaf.basic.BasicGraphicsUtils;
public class AgCheckBoxUI
extends BasicCheckBoxUI
{
private final static AgCheckBoxUI checkBoxUI = new AgCheckBoxUI();
public static void init(UIDefaults d)
{
d.put("CheckBoxUI", AgCheckBoxUI.class.getName());
d.put("CheckBoxUI.contentAreaFilled", Boolean.FALSE);
d.put("CheckBox.icon", new AgCheckBoxIcon());
d.put("CheckBox.foreground", Theme.TEXT_FG);
d.put("CheckBox.background", Theme.PANEL_BG);
}
protected void installDefaults(AbstractButton b)
{
super.installDefaults(b);
b.setOpaque(false);
}
public static ComponentUI createUI(JComponent b)
{
return checkBoxUI;
}
protected Color getFocusColor()
{
return Theme.FOCUS_COLOR;
}
protected void paintFocus(Graphics g, Rectangle textRect, Dimension d)
{
g.setColor(getFocusColor());
BasicGraphicsUtils.drawDashedRect(g, textRect.x, textRect.y, textRect.width, textRect.height);
}
}
| apache-2.0 |
hcoles/pitest | pitest-html-report/src/main/java/org/pitest/mutationtest/report/html/MutationHtmlReportListener.java | 8437 | /*
* Copyright 2010 Henry Coles
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package org.pitest.mutationtest.report.html;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.pitest.classinfo.ClassInfo;
import org.pitest.coverage.ReportCoverage;
import org.pitest.functional.FCollection;
import org.pitest.mutationtest.ClassMutationResults;
import org.pitest.mutationtest.MutationResultListener;
import org.pitest.mutationtest.SourceLocator;
import org.pitest.util.FileUtil;
import org.pitest.util.IsolationUtils;
import org.pitest.util.Log;
import org.pitest.util.ResultOutputStrategy;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
public class MutationHtmlReportListener implements MutationResultListener {
private final ResultOutputStrategy outputStrategy;
private final Collection<SourceLocator> sourceRoots;
private final PackageSummaryMap packageSummaryData = new PackageSummaryMap();
private final ReportCoverage coverage;
private final Set<String> mutatorNames;
private final String css;
public MutationHtmlReportListener(final ReportCoverage coverage,
final ResultOutputStrategy outputStrategy,
Collection<String> mutatorNames, final SourceLocator... locators) {
this.coverage = coverage;
this.outputStrategy = outputStrategy;
this.sourceRoots = new HashSet<>(Arrays.asList(locators));
this.mutatorNames = new HashSet<>(mutatorNames);
this.css = loadCss();
}
private String loadCss() {
try {
return FileUtil.readToString(IsolationUtils.getContextClassLoader()
.getResourceAsStream("templates/mutation/style.css"));
} catch (final IOException e) {
Log.getLogger().log(Level.SEVERE, "Error while loading css", e);
}
return "";
}
private void generateAnnotatedSourceFile(
final MutationTestSummaryData mutationMetaData) {
final String fileName = mutationMetaData.getPackageName()
+ File.separator + mutationMetaData.getFileName() + ".html";
try (Writer writer = this.outputStrategy.createWriterForFile(fileName)) {
final StringTemplateGroup group = new StringTemplateGroup("mutation_test");
final StringTemplate st = group
.getInstanceOf("templates/mutation/mutation_report");
st.setAttribute("css", this.css);
st.setAttribute("tests", mutationMetaData.getTests());
st.setAttribute("mutators", mutationMetaData.getMutators());
final SourceFile sourceFile = createAnnotatedSourceFile(mutationMetaData);
st.setAttribute("sourceFile", sourceFile);
st.setAttribute("mutatedClasses", mutationMetaData.getMutatedClasses());
writer.write(st.toString());
} catch (final IOException ex) {
Log.getLogger().log(Level.WARNING, "Error while writing report", ex);
}
}
private PackageSummaryData collectPackageSummaries(
final ClassMutationResults mutationMetaData) {
final String packageName = mutationMetaData.getPackageName();
return this.packageSummaryData.update(packageName,
createSummaryData(this.coverage, mutationMetaData));
}
public MutationTestSummaryData createSummaryData(
final ReportCoverage coverage, final ClassMutationResults data) {
return new MutationTestSummaryData(data.getFileName(), data.getMutations(),
this.mutatorNames, coverage.getClassInfo(Collections.singleton(data
.getMutatedClass())), coverage.getNumberOfCoveredLines(Collections
.singleton(data.getMutatedClass())));
}
private SourceFile createAnnotatedSourceFile(
final MutationTestSummaryData mutationMetaData) throws IOException {
final String fileName = mutationMetaData.getFileName();
final String packageName = mutationMetaData.getPackageName();
final MutationResultList mutationsForThisFile = mutationMetaData
.getResults();
final List<Line> lines = createAnnotatedSourceCodeLines(fileName,
packageName, mutationsForThisFile);
return new SourceFile(fileName, lines,
mutationsForThisFile.groupMutationsByLine());
}
private List<Line> createAnnotatedSourceCodeLines(final String sourceFile,
final String packageName, final MutationResultList mutationsForThisFile)
throws IOException {
final Collection<ClassInfo> classes = this.coverage.getClassesForFile(
sourceFile, packageName);
final Optional<Reader> reader = findSourceFile(classInfoToNames(classes),
sourceFile);
if (reader.isPresent()) {
final AnnotatedLineFactory alf = new AnnotatedLineFactory(
mutationsForThisFile.list(), this.coverage, classes);
return alf.convert(reader.get());
}
return Collections.emptyList();
}
private Collection<String> classInfoToNames(
final Collection<ClassInfo> classes) {
return FCollection.map(classes, classInfoToJavaName());
}
private Function<ClassInfo, String> classInfoToJavaName() {
return a -> a.getName().asJavaName();
}
private Optional<Reader> findSourceFile(final Collection<String> classes,
final String fileName) {
for (final SourceLocator each : this.sourceRoots) {
final Optional<Reader> maybe = each.locate(classes, fileName);
if (maybe.isPresent()) {
return maybe;
}
}
return Optional.empty();
}
public void onRunEnd() {
createIndexPages();
createCssFile();
}
private void createCssFile() {
final Writer cssWriter = this.outputStrategy.createWriterForFile("style.css");
try {
cssWriter.write(this.css);
cssWriter.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
private void createIndexPages() {
final StringTemplateGroup group = new StringTemplateGroup("mutation_test");
final StringTemplate st = group
.getInstanceOf("templates/mutation/mutation_package_index");
final Writer writer = this.outputStrategy.createWriterForFile("index.html");
final MutationTotals totals = new MutationTotals();
final List<PackageSummaryData> psd = new ArrayList<>(
this.packageSummaryData.values());
Collections.sort(psd);
for (final PackageSummaryData psData : psd) {
totals.add(psData.getTotals());
createPackageIndexPage(psData);
}
st.setAttribute("totals", totals);
st.setAttribute("packageSummaries", psd);
try {
writer.write(st.toString());
writer.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
private void createPackageIndexPage(final PackageSummaryData psData) {
final StringTemplateGroup group = new StringTemplateGroup("mutation_test");
final StringTemplate st = group
.getInstanceOf("templates/mutation/package_index");
final Writer writer = this.outputStrategy.createWriterForFile(psData
.getPackageDirectory() + File.separator + "index.html");
st.setAttribute("packageData", psData);
try {
writer.write(st.toString());
writer.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
@Override
public void runStart() {
// TODO Auto-generated method stub
}
@Override
public void runEnd() {
createIndexPages();
createCssFile();
}
@Override
public void handleMutationResult(final ClassMutationResults metaData) {
final PackageSummaryData packageData = collectPackageSummaries(metaData);
generateAnnotatedSourceFile(packageData.getForSourceFile(metaData
.getFileName()));
}
} | apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-appmesh/src/main/java/com/amazonaws/services/appmesh/model/transform/EgressFilterMarshaller.java | 1909 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.appmesh.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.appmesh.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* EgressFilterMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class EgressFilterMarshaller {
private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("type").build();
private static final EgressFilterMarshaller instance = new EgressFilterMarshaller();
public static EgressFilterMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(EgressFilter egressFilter, ProtocolMarshaller protocolMarshaller) {
if (egressFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(egressFilter.getType(), TYPE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
gwtproject/gwt-event-dom | gwt-event-dom/src/main/java/org/gwtproject/event/dom/client/ChangeEvent.java | 1585 | /*
* Copyright © 2019 The GWT Project 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.gwtproject.event.dom.client;
import org.gwtproject.dom.client.BrowserEvents;
/** Represents a native change event. */
public class ChangeEvent extends DomEvent<ChangeHandler> {
/** Event type for change events. Represents the meta-data associated with this event. */
private static final Type<ChangeHandler> TYPE =
new Type<>(BrowserEvents.CHANGE, new ChangeEvent());
/**
* Protected constructor, use {@link
* DomEvent#fireNativeEvent(org.gwtproject.dom.client.NativeEvent,
* org.gwtproject.event.shared.HasHandlers)} to fire change events.
*/
protected ChangeEvent() {}
/**
* Gets the event type associated with change events.
*
* @return the handler type
*/
public static Type<ChangeHandler> getType() {
return TYPE;
}
@Override
public final Type<ChangeHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(ChangeHandler handler) {
handler.onChange(this);
}
}
| apache-2.0 |
PantryChef/PantryChef | app/src/main/java/com/pantrychefapp/pantrychef/dao/DAOFactory.java | 377 | package com.pantrychefapp.pantrychef.dao;
import com.pantrychefapp.pantrychef.dao.sqlite.SQLiteDAOFactory;
public abstract class DAOFactory {
private static DAOFactory daoFactory = null;
public abstract RecipeDAO getRecipeDAO();
public static DAOFactory getDAOFactory() {
if (daoFactory == null) {
daoFactory = new SQLiteDAOFactory();
}
return daoFactory;
}
}
| apache-2.0 |
baigao2015/freshmommy-console | src/main/java/com/wonders/bud/freshmommy/service/user/baby/service/impl/BabyServiceImpl.java | 5279 | /**
*
* Copyright (c) 1995-2012 Wonders Information Co.,Ltd.
* 1518 Lianhang Rd,Shanghai 201112.P.R.C.
* All Rights Reserved.
*
* This software is the confidential and proprietary information of Wonders Group.
* (Social Security Department). You shall not disclose such
* Confidential Information and shall use it only in accordance with
* the terms of the license agreement you entered into with Wonders Group.
*
* Distributable under GNU LGPL license by gnu.org
*/
package com.wonders.bud.freshmommy.service.user.baby.service.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.wonders.bud.framework.common.page.Page;
import com.wonders.bud.framework.common.util.QueryParam;
import com.wonders.bud.framework.common.util.SeqUtils;
import com.wonders.bud.freshmommy.service.user.baby.dao.BabyDao;
import com.wonders.bud.freshmommy.service.user.baby.dao.BabyRecDao;
import com.wonders.bud.freshmommy.service.user.baby.dao.BabyRecMonDao;
import com.wonders.bud.freshmommy.service.user.baby.model.po.BabyPO;
import com.wonders.bud.freshmommy.service.user.baby.model.po.BabyRecMonPO;
import com.wonders.bud.freshmommy.service.user.baby.model.po.BabyRecPO;
import com.wonders.bud.freshmommy.service.user.baby.service.BabyService;
import com.wonders.bud.freshmommy.web.utils.Constant;
/**<p>
* Title: freshmommy_[用户]_[用户宝宝管理]
* </p>
* <p>
* Description: [宝宝管理Service接口实现]
* </p>
*
* @author linqin
* @version $Revision$ 2014-11-17
* @author (lastest modification by $Author$)
* @since 20100901
*/
@Service("babyServiceImpl")
public class BabyServiceImpl implements BabyService {
@Resource(name = "babyDaoImpl")
private BabyDao babyDao;
@Resource(name = "babyRecDaoImpl")
private BabyRecDao babyRecDao;
@Resource(name = "babyRecMonDaoImpl")
private BabyRecMonDao babyRecMonDao;
@Override
@Transactional(propagation=Propagation.REQUIRED)
public BabyPO addBaby(BabyPO po) {
po.setStatus(Constant.BABY_NORMAL);
return babyDao.save(po);
}
@Override
@Transactional(propagation=Propagation.REQUIRED)
public BabyPO deleteBaby(Integer bId) {
BabyPO po = babyDao.get(bId);
po.setStatus(Constant.BABY_REMOVED);
return babyDao.update(po);
}
@Override
@Transactional(propagation=Propagation.REQUIRED)
public BabyPO editBaby(BabyPO po) {
return babyDao.update(po);
}
@Override
public List<BabyPO> findBabiesByList(Map<String, Object> paramMap) {
paramMap.put("status", Constant.BABY_NORMAL);
return babyDao.findBy(paramMap);
}
@Override
@Transactional(propagation=Propagation.REQUIRED)
public BabyRecPO addBabyRec(BabyRecPO babyRec) {
// 完善“宝宝全纪录”数据
if(babyRec.getLogDate() == null){
babyRec.setLogDate(new Date());
}
BabyRecMonPO babyRecMon = new BabyRecMonPO();
BabyPO baby = babyDao.findUniqueByProperty("bId", babyRec.getbId());
if(baby == null){
return null;
}
//获取宝贝月龄or周龄
Map<String,Integer> newMon = babyRecMon.transtoMon(baby, babyRec.getLogDate());
if(newMon != null){
// 保存“宝宝全纪录”数据
babyRec.setId(SeqUtils.getLSH32());
babyRec = babyRecDao.save(babyRec);
// 查询是否有相同时间段“宝宝全记录月龄”数据
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("bId", babyRec.getbId());
paramMap.put("type", babyRec.getType());
paramMap.put("month", newMon.get("month"));
paramMap.put("ageType", newMon.get("agetype"));
List<BabyRecMonPO> list = babyRecMonDao.findBy(paramMap);
// 更新
if(list != null && list.size() > 0){
babyRecMon = list.get(0);
// 更新“记录值”
if(babyRec.getValue() != babyRecMon.getValue()){
babyRecMon.setValue(babyRec.getValue());
babyRecMon.setLogId(babyRec.getId());
babyRecMonDao.update(babyRecMon);
}
}
// 新增
else {
babyRecMon.setId(SeqUtils.getLSH32());
babyRecMon.setbId(babyRec.getbId());
babyRecMon.setLogId(babyRec.getId());
babyRecMon.setType(babyRec.getType());
babyRecMon.setValue(babyRec.getValue());
babyRecMon.setMonth(newMon.get("month"));
babyRecMon.setAgeType(newMon.get("agetype"));
babyRecMonDao.save(babyRecMon);
}
}
return babyRec;
}
@Override
public Page<BabyRecPO> findBabyRecByPage(Page<BabyRecPO> page) {
//时间倒序查询
QueryParam param = new QueryParam();
Map<String, String> order = new HashMap<String, String>();
if(null != page) {
if(null != page.getParam()) {
if(null != page.getParam().getOrder()) {
order = page.getParam().getOrder();
}
}
}
order.put("logDate","desc");
param.setOrder(order);
page.setParam(param);
return babyRecDao.findByPage(page);
}
@Override
public Page<BabyPO> findBabiesByPage(Page<BabyPO> page) {
return babyDao.findByPage(page);
}
@Override
public List<BabyRecMonPO> findBabyRecMonByList(Map<String, Object> paramMap) {
return babyRecMonDao.findBy(paramMap);
}
}
| apache-2.0 |
katsuster/strview | test_view/src/net/katsuster/strview/test/util/FloatTest.java | 20595 | package net.katsuster.strview.test.util;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import net.katsuster.strview.util.bit.*;
import net.katsuster.strview.io.*;
public class FloatTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public final void testFloat32IntLongInt() {
String msg1 = "Float32(int, long, int) failed.";
String msg2 = "Float32(int, long, int) illegal arguments check failed.";
LargeBitList la = new MemoryBitList(64);
Float32 va = new Float32("", la, 2, 3);
assertEquals(msg1, 0, va.getRaw());
assertEquals(msg1, 2, va.getRange().getStart());
assertEquals(msg1, 3, va.length());
}
@Test
public final void testFloat32Float32() {
String msg1 = "Float32(Float32) failed.";
String msg2 = "Float32.clone() failed.";
LargeBitList la = new MemoryBitList(64);
Float32 va = new Float32("", la, 2, 3);
Float32 vb = new Float32(va);
assertEquals(msg1, va.getRaw(), vb.getRaw());
assertEquals(msg1, va.getRange().getStart(), vb.getRange().getStart());
assertEquals(msg1, va.getRange().getEnd(), vb.getRange().getEnd());
vb.setRaw(10);
vb.getRange().setStart(20);
vb.getRange().setEnd(30);
assertNotEquals(msg1, va.getRaw(), vb.getRaw());
assertNotEquals(msg1, va.getRange().getStart(), vb.getRange().getStart());
assertNotEquals(msg1, va.getRange().getEnd(), vb.getRange().getEnd());
try {
Float32 vc = (Float32)va.clone();
assertEquals(msg2, va.getRaw(), vc.getRaw());
assertEquals(msg2, va.getRange().getStart(), vc.getRange().getStart());
assertEquals(msg2, va.getRange().getEnd(), vc.getRange().getEnd());
vc.setRaw(100);
vc.getRange().setStart(4);
vc.getRange().setEnd(10);
assertNotEquals(msg2, va.getRaw(), vc.getRaw());
assertNotEquals(msg2, va.getRange().getStart(), vc.getRange().getStart());
assertNotEquals(msg2, va.getRange().getEnd(), vc.getRange().getEnd());
} catch (Exception ex) {
fail(msg2);
}
}
@Test
public final void testFloat32ByteValue() {
String msg1 = "Float32.byteValue() failed.";
Float32 vz0 = new Float32("", 0.0F);
Float32 vp1 = new Float32("", 1.0F);
Float32 vp2 = new Float32("", 2.0F);
Float32 vm1 = new Float32("", -1.0F);
Float32 vm2 = new Float32("", -2.0F);
Float32 vh1 = new Float32("", 8388606.0F);
Float32 vh2 = new Float32("", 8388607.0F);
Float32 vh3 = new Float32("", 8388608.0F);
Float32 vh4 = new Float32("", 8388609.0F);
assertEquals(msg1, (byte)0x00, vz0.byteValue());
assertEquals(msg1, (byte)0x01, vp1.byteValue());
assertEquals(msg1, (byte)0x02, vp2.byteValue());
assertEquals(msg1, (byte)0xff, vm1.byteValue());
assertEquals(msg1, (byte)0xfe, vm2.byteValue());
assertEquals(msg1, (byte)0xfe, vh1.byteValue());
assertEquals(msg1, (byte)0xff, vh2.byteValue());
assertEquals(msg1, (byte)0x00, vh3.byteValue());
assertEquals(msg1, (byte)0x01, vh4.byteValue());
}
@Test
public final void testFloat32ShortValue() {
String msg1 = "Float32.shortValue() failed.";
Float32 vz0 = new Float32("", 0.0F);
Float32 vp1 = new Float32("", 1.0F);
Float32 vp2 = new Float32("", 2.0F);
Float32 vm1 = new Float32("", -1.0F);
Float32 vm2 = new Float32("", -2.0F);
Float32 vh1 = new Float32("", 8388606.0F);
Float32 vh2 = new Float32("", 8388607.0F);
Float32 vh3 = new Float32("", 8388608.0F);
Float32 vh4 = new Float32("", 8388609.0F);
assertEquals(msg1, (short)0x0000, vz0.shortValue());
assertEquals(msg1, (short)0x0001, vp1.shortValue());
assertEquals(msg1, (short)0x0002, vp2.shortValue());
assertEquals(msg1, (short)0xffff, vm1.shortValue());
assertEquals(msg1, (short)0xfffe, vm2.shortValue());
assertEquals(msg1, (short)0xfffe, vh1.shortValue());
assertEquals(msg1, (short)0xffff, vh2.shortValue());
assertEquals(msg1, (short)0x0000, vh3.shortValue());
assertEquals(msg1, (short)0x0001, vh4.shortValue());
}
@Test
public final void testFloat32IntValue() {
String msg1 = "Float32.intValue() failed.";
Float32 vz0 = new Float32("", 0.0F);
Float32 vp1 = new Float32("", 1.0F);
Float32 vp2 = new Float32("", 2.0F);
Float32 vm1 = new Float32("", -1.0F);
Float32 vm2 = new Float32("", -2.0F);
Float32 vh1 = new Float32("", 8388606.0F);
Float32 vh2 = new Float32("", 8388607.0F);
Float32 vh3 = new Float32("", 8388608.0F);
Float32 vh4 = new Float32("", 8388609.0F);
assertEquals(msg1, 0x00000000, vz0.intValue());
assertEquals(msg1, 0x00000001, vp1.intValue());
assertEquals(msg1, 0x00000002, vp2.intValue());
assertEquals(msg1, 0xffffffff, vm1.intValue());
assertEquals(msg1, 0xfffffffe, vm2.intValue());
assertEquals(msg1, 0x007ffffe, vh1.intValue());
assertEquals(msg1, 0x007fffff, vh2.intValue());
assertEquals(msg1, 0x00800000, vh3.intValue());
assertEquals(msg1, 0x00800001, vh4.intValue());
}
@Test
public final void testFloat32LongValue() {
String msg1 = "Float32.longValue() failed.";
Float32 vz0 = new Float32("", 0.0F);
Float32 vp1 = new Float32("", 1.0F);
Float32 vp2 = new Float32("", 2.0F);
Float32 vm1 = new Float32("", -1.0F);
Float32 vm2 = new Float32("", -2.0F);
Float32 vh1 = new Float32("", 8388606.0F);
Float32 vh2 = new Float32("", 8388607.0F);
Float32 vh3 = new Float32("", 8388608.0F);
Float32 vh4 = new Float32("", 8388609.0F);
assertEquals(msg1, 0x0000000000000000L, vz0.longValue());
assertEquals(msg1, 0x0000000000000001L, vp1.longValue());
assertEquals(msg1, 0x0000000000000002L, vp2.longValue());
assertEquals(msg1, 0xffffffffffffffffL, vm1.longValue());
assertEquals(msg1, 0xfffffffffffffffeL, vm2.longValue());
assertEquals(msg1, 0x00000000007ffffeL, vh1.longValue());
assertEquals(msg1, 0x00000000007fffffL, vh2.longValue());
assertEquals(msg1, 0x0000000000800000L, vh3.longValue());
assertEquals(msg1, 0x0000000000800001L, vh4.longValue());
}
@Test
public final void testFloat32FloatValue() {
String msg1 = "Float32.floatValue() failed.";
Float32 vz0 = new Float32("", 0.0F);
Float32 vp1 = new Float32("", 1.0F);
Float32 vp2 = new Float32("", 2.0F);
Float32 vm1 = new Float32("", -1.0F);
Float32 vm2 = new Float32("", -2.0F);
Float32 vh1 = new Float32("", 8388606.0F);
Float32 vh2 = new Float32("", 8388607.0F);
Float32 vh3 = new Float32("", 8388608.0F);
Float32 vh4 = new Float32("", 8388609.0F);
assertTrue(msg1, 0.0F <= vz0.floatValue());
assertTrue(msg1, 1.0F <= vp1.floatValue());
assertTrue(msg1, 2.0F <= vp2.floatValue());
assertTrue(msg1, -1.0F <= vm1.floatValue());
assertTrue(msg1, -2.0F <= vm2.floatValue());
assertTrue(msg1, 8388606.0F <= vh1.floatValue());
assertTrue(msg1, 8388607.0F <= vh2.floatValue());
assertTrue(msg1, 8388608.0F <= vh3.floatValue());
assertTrue(msg1, 8388609.0F <= vh4.floatValue());
}
@Test
public final void testFloat32DoubleValue() {
String msg1 = "Float32.doubleValue() failed.";
Float32 vz0 = new Float32("", 0.0F);
Float32 vp1 = new Float32("", 1.0F);
Float32 vp2 = new Float32("", 2.0F);
Float32 vm1 = new Float32("", -1.0F);
Float32 vm2 = new Float32("", -2.0F);
Float32 vh1 = new Float32("", 8388606.0F);
Float32 vh2 = new Float32("", 8388607.0F);
Float32 vh3 = new Float32("", 8388608.0F);
Float32 vh4 = new Float32("", 8388609.0F);
assertTrue(msg1, 0.0D <= vz0.doubleValue());
assertTrue(msg1, 1.0D <= vp1.doubleValue());
assertTrue(msg1, 2.0D <= vp2.doubleValue());
assertTrue(msg1, -1.0D <= vm1.doubleValue());
assertTrue(msg1, -2.0D <= vm2.doubleValue());
assertTrue(msg1, 8388606.0D <= vh1.doubleValue());
assertTrue(msg1, 8388607.0D <= vh2.doubleValue());
assertTrue(msg1, 8388608.0D <= vh3.doubleValue());
assertTrue(msg1, 8388609.0D <= vh4.doubleValue());
}
@Test
public final void testFloat32ToString() {
String msg1 = "Float32.toString() failed.";
Float32 vz0 = new Float32("", 0.0F);
Float32 vp1 = new Float32("", 1.0F);
Float32 vp2 = new Float32("", 2.0F);
Float32 vm1 = new Float32("", -1.0F);
Float32 vm2 = new Float32("", -2.0F);
Float32 vh1 = new Float32("", 8388606.0F);
Float32 vh2 = new Float32("", 8388607.0F);
Float32 vh3 = new Float32("", 8388608.0F);
Float32 vh4 = new Float32("", 8388609.0F);
assertEquals(msg1, "0.0", vz0.toString());
assertEquals(msg1, "1.0", vp1.toString());
assertEquals(msg1, "2.0", vp2.toString());
assertEquals(msg1, "-1.0", vm1.toString());
assertEquals(msg1, "-2.0", vm2.toString());
assertEquals(msg1, "8388606.0", vh1.toString());
assertEquals(msg1, "8388607.0", vh2.toString());
assertEquals(msg1, "8388608.0", vh3.toString());
assertEquals(msg1, "8388609.0", vh4.toString());
}
@Test
public final void testFloat64LongLongInt() {
String msg1 = "Float64(long, long, int) failed.";
String msg2 = "Float64(long, long, int) illegal arguments check failed.";
LargeBitList la = new MemoryBitList(64);
Float64 va = new Float64("", la, 2, 3);
assertEquals(msg1, 0, va.getRaw());
assertEquals(msg1, 2, va.getRange().getStart());
assertEquals(msg1, 3, va.length());
}
@Test
public final void testFloat64Float64() {
String msg1 = "Float64(Float64) failed.";
String msg2 = "Float64.clone() failed.";
LargeBitList la = new MemoryBitList(64);
Float64 va = new Float64("", la, 2, 3);
Float64 vb = new Float64(va);
assertEquals(msg1, va.getRaw(), vb.getRaw());
assertEquals(msg1, va.getRange().getStart(), vb.getRange().getStart());
assertEquals(msg1, va.getRange().getEnd(), vb.getRange().getEnd());
vb.setRaw(10);
vb.getRange().setStart(20);
vb.getRange().setEnd(30);
assertNotEquals(msg1, va.getRaw(), vb.getRaw());
assertNotEquals(msg1, va.getRange().getStart(), vb.getRange().getStart());
assertNotEquals(msg1, va.getRange().getEnd(), vb.getRange().getEnd());
try {
Float64 vc = (Float64)va.clone();
assertEquals(msg2, va.getRaw(), vc.getRaw());
assertEquals(msg2, va.getRange().getStart(), vc.getRange().getStart());
assertEquals(msg2, va.getRange().getEnd(), vc.getRange().getEnd());
vc.setRaw(100);
vc.getRange().setStart(4);
vc.getRange().setEnd(10);
assertNotEquals(msg2, va.getRaw(), vc.getRaw());
assertNotEquals(msg2, va.getRange().getStart(), vc.getRange().getStart());
assertNotEquals(msg2, va.getRange().getEnd(), vc.getRange().getEnd());
} catch (Exception ex) {
fail(msg2);
}
}
@Test
public final void testFloat64ByteValue() {
String msg1 = "Float64.byteValue() failed.";
Float64 vz0 = new Float64("", 0.0D);
Float64 vp1 = new Float64("", 1.0D);
Float64 vp2 = new Float64("", 2.0D);
Float64 vm1 = new Float64("", -1.0D);
Float64 vm2 = new Float64("", -2.0D);
Float64 vh1 = new Float64("", 4503599627370494.0D);
Float64 vh2 = new Float64("", 4503599627370495.0D);
Float64 vh3 = new Float64("", 4503599627370496.0D);
Float64 vh4 = new Float64("", 4503599627370497.0D);
assertEquals(msg1, (byte)0x00, vz0.byteValue());
assertEquals(msg1, (byte)0x01, vp1.byteValue());
assertEquals(msg1, (byte)0x02, vp2.byteValue());
assertEquals(msg1, (byte)0xff, vm1.byteValue());
assertEquals(msg1, (byte)0xfe, vm2.byteValue());
assertEquals(msg1, (byte)0xff, vh1.byteValue());
assertEquals(msg1, (byte)0xff, vh2.byteValue());
assertEquals(msg1, (byte)0xff, vh3.byteValue());
assertEquals(msg1, (byte)0xff, vh4.byteValue());
}
@Test
public final void testFloat64ShortValue() {
String msg1 = "Float64.shortValue() failed.";
Float64 vz0 = new Float64("", 0.0D);
Float64 vp1 = new Float64("", 1.0D);
Float64 vp2 = new Float64("", 2.0D);
Float64 vm1 = new Float64("", -1.0D);
Float64 vm2 = new Float64("", -2.0D);
Float64 vh1 = new Float64("", 4503599627370494.0D);
Float64 vh2 = new Float64("", 4503599627370495.0D);
Float64 vh3 = new Float64("", 4503599627370496.0D);
Float64 vh4 = new Float64("", 4503599627370497.0D);
assertEquals(msg1, (short)0x0000, vz0.shortValue());
assertEquals(msg1, (short)0x0001, vp1.shortValue());
assertEquals(msg1, (short)0x0002, vp2.shortValue());
assertEquals(msg1, (short)0xffff, vm1.shortValue());
assertEquals(msg1, (short)0xfffe, vm2.shortValue());
assertEquals(msg1, (short)0xffff, vh1.shortValue());
assertEquals(msg1, (short)0xffff, vh2.shortValue());
assertEquals(msg1, (short)0xffff, vh3.shortValue());
assertEquals(msg1, (short)0xffff, vh4.shortValue());
}
@Test
public final void testFloat64IntValue() {
String msg1 = "Float64.intValue() failed.";
Float64 vz0 = new Float64("", 0.0D);
Float64 vp1 = new Float64("", 1.0D);
Float64 vp2 = new Float64("", 2.0D);
Float64 vm1 = new Float64("", -1.0D);
Float64 vm2 = new Float64("", -2.0D);
Float64 vh1 = new Float64("", 4503599627370494.0D);
Float64 vh2 = new Float64("", 4503599627370495.0D);
Float64 vh3 = new Float64("", 4503599627370496.0D);
Float64 vh4 = new Float64("", 4503599627370497.0D);
assertEquals(msg1, 0x00000000, vz0.intValue());
assertEquals(msg1, 0x00000001, vp1.intValue());
assertEquals(msg1, 0x00000002, vp2.intValue());
assertEquals(msg1, 0xffffffff, vm1.intValue());
assertEquals(msg1, 0xfffffffe, vm2.intValue());
//int に変換するには値が大きすぎるので、
//キャスト結果はすべて Integer.MAX_VALUE になる。
//short, byte については、
//double -> int -> short, byte と変換されるため、
//Integer.MAX_VALUE の下位ビット値である、0xffff, 0xff となる。
//※Java 言語規定「5.1.3 Narrowing Primitive Conversions」を参照
assertEquals(msg1, 0x7fffffff, vh1.intValue());
assertEquals(msg1, 0x7fffffff, vh2.intValue());
assertEquals(msg1, 0x7fffffff, vh3.intValue());
assertEquals(msg1, 0x7fffffff, vh4.intValue());
}
@Test
public final void testFloat64LongValue() {
String msg1 = "Float64.longValue() failed.";
Float64 vz0 = new Float64("", 0.0D);
Float64 vp1 = new Float64("", 1.0D);
Float64 vp2 = new Float64("", 2.0D);
Float64 vm1 = new Float64("", -1.0D);
Float64 vm2 = new Float64("", -2.0D);
Float64 vh1 = new Float64("", 4503599627370494.0D);
Float64 vh2 = new Float64("", 4503599627370495.0D);
Float64 vh3 = new Float64("", 4503599627370496.0D);
Float64 vh4 = new Float64("", 4503599627370497.0D);
assertEquals(msg1, 0x0000000000000000L, vz0.longValue());
assertEquals(msg1, 0x0000000000000001L, vp1.longValue());
assertEquals(msg1, 0x0000000000000002L, vp2.longValue());
assertEquals(msg1, 0xffffffffffffffffL, vm1.longValue());
assertEquals(msg1, 0xfffffffffffffffeL, vm2.longValue());
assertEquals(msg1, 0x000ffffffffffffeL, vh1.longValue());
assertEquals(msg1, 0x000fffffffffffffL, vh2.longValue());
assertEquals(msg1, 0x0010000000000000L, vh3.longValue());
assertEquals(msg1, 0x0010000000000001L, vh4.longValue());
}
@Test
public final void testFloat64FloatValue() {
String msg1 = "Float64.floatValue() failed.";
Float64 vz0 = new Float64("", 0.0D);
Float64 vp1 = new Float64("", 1.0D);
Float64 vp2 = new Float64("", 2.0D);
Float64 vm1 = new Float64("", -1.0D);
Float64 vm2 = new Float64("", -2.0D);
Float64 vh1 = new Float64("", 4503599627370494.0D);
Float64 vh2 = new Float64("", 4503599627370495.0D);
Float64 vh3 = new Float64("", 4503599627370496.0D);
Float64 vh4 = new Float64("", 4503599627370497.0D);
assertTrue(msg1, 0.0F <= vz0.floatValue());
assertTrue(msg1, 1.0F <= vp1.floatValue());
assertTrue(msg1, 2.0F <= vp2.floatValue());
assertTrue(msg1, -1.0F <= vm1.floatValue());
assertTrue(msg1, -2.0F <= vm2.floatValue());
assertTrue(msg1, 4503599627370494.0F <= vh1.floatValue());
assertTrue(msg1, 4503599627370495.0F <= vh2.floatValue());
assertTrue(msg1, 4503599627370496.0F <= vh3.floatValue());
assertTrue(msg1, 4503599627370497.0F <= vh4.floatValue());
}
@Test
public final void testFloat64DoubleValue() {
String msg1 = "Float64.doubleValue() failed.";
Float64 vz0 = new Float64("", 0.0D);
Float64 vp1 = new Float64("", 1.0D);
Float64 vp2 = new Float64("", 2.0D);
Float64 vm1 = new Float64("", -1.0D);
Float64 vm2 = new Float64("", -2.0D);
Float64 vh1 = new Float64("", 4503599627370494.0D);
Float64 vh2 = new Float64("", 4503599627370495.0D);
Float64 vh3 = new Float64("", 4503599627370496.0D);
Float64 vh4 = new Float64("", 4503599627370497.0D);
assertTrue(msg1, 0.0D <= vz0.doubleValue());
assertTrue(msg1, 1.0D <= vp1.doubleValue());
assertTrue(msg1, 2.0D <= vp2.doubleValue());
assertTrue(msg1, -1.0D <= vm1.doubleValue());
assertTrue(msg1, -2.0D <= vm2.doubleValue());
assertTrue(msg1, 4503599627370494.0D <= vh1.doubleValue());
assertTrue(msg1, 4503599627370495.0D <= vh2.doubleValue());
assertTrue(msg1, 4503599627370496.0D <= vh3.doubleValue());
assertTrue(msg1, 4503599627370497.0D <= vh4.doubleValue());
}
@Test
public final void testFloat64ToString() {
String msg1 = "Float64.toString() failed.";
Float64 vz0 = new Float64("", 0.0D);
Float64 vp1 = new Float64("", 1.0D);
Float64 vp2 = new Float64("", 2.0D);
Float64 vm1 = new Float64("", -1.0D);
Float64 vm2 = new Float64("", -2.0D);
Float64 vh1 = new Float64("", 4503599627370494.0D);
Float64 vh2 = new Float64("", 4503599627370495.0D);
Float64 vh3 = new Float64("", 4503599627370496.0D);
Float64 vh4 = new Float64("", 4503599627370497.0D);
assertEquals(msg1, "0.0", vz0.toString());
assertEquals(msg1, "1.0", vp1.toString());
assertEquals(msg1, "2.0", vp2.toString());
assertEquals(msg1, "-1.0", vm1.toString());
assertEquals(msg1, "-2.0", vm2.toString());
assertEquals(msg1, "4.503599627370494E15", vh1.toString());
assertEquals(msg1, "4.503599627370495E15", vh2.toString());
assertEquals(msg1, "4.503599627370496E15", vh3.toString());
assertEquals(msg1, "4.503599627370497E15", vh4.toString());
}
}
| apache-2.0 |
brianm/memcake | src/main/java/org/skife/memcake/GetWithKeyOp.java | 1258 | /*
* 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.skife.memcake;
import org.skife.memcake.connection.Value;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public class GetWithKeyOp {
private final Memcake memcake;
private final byte[] key;
private Duration timeout;
GetWithKeyOp(Memcake memcake, byte[] key, Duration timeout) {
this.memcake = memcake;
this.key = key;
this.timeout = timeout;
}
public GetWithKeyOp timeout(Duration timeout) {
this.timeout = timeout;
return this;
}
public CompletableFuture<Optional<Value>> execute() {
return memcake.call(key, (c) -> c.getk(key, timeout));
}
}
| apache-2.0 |
ingorichtsmeier/ingo-camunda-examples | process-applications/meal-ordering-process/src/main/java/com/camunda/consulting/meal_ordering_process/data/Training.java | 2841 | package com.camunda.consulting.meal_ordering_process.data;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import spinjar.com.fasterxml.jackson.annotation.JsonIgnore;
public class Training implements Serializable {
private static final long serialVersionUID = 1L;
private String trainingID;
private Date startDate;
private Date endDate;
private static DecimalFormat twoDigits = new DecimalFormat("00");
public Training(String trainingID, Date startDate, Date endDate) {
super();
this.trainingID = trainingID;
this.startDate = startDate;
this.endDate = endDate;
}
public Training() {
super();
}
public String getTrainingID() {
return trainingID;
}
public void setTrainingID(String trainingID) {
this.trainingID = trainingID;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@JsonIgnore
public String getEndDateAsIso8601() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(endDate);
return calendar.get(Calendar.YEAR) + "-" + twoDigits.format(calendar.get(Calendar.MONTH) + 1) + "-" + twoDigits.format(calendar.get(Calendar.DAY_OF_MONTH))
+ "T" + twoDigits.format(calendar.get(Calendar.HOUR_OF_DAY)) + ":" + twoDigits.format(calendar.get(Calendar.MINUTE)) + ":"
+ twoDigits.format(calendar.get(Calendar.SECOND));
}
@JsonIgnore
public List<String> getWeekdays() {
List<String> weekdays = new ArrayList<String>();
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
int startday = start.get(Calendar.DAY_OF_YEAR);
int endday = end.get(Calendar.DAY_OF_YEAR);
if (startday == endday) {
weekdays.add(calculateWeekday(start));
return weekdays;
}
for (Calendar date = start; start.before(end); date.add(Calendar.DATE, 1)) {
weekdays.add(calculateWeekday(date));
}
return weekdays;
}
private String calculateWeekday(Calendar date) {
switch (date.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY:
return "Sunday";
case Calendar.MONDAY:
return "Monday";
case Calendar.TUESDAY:
return "Tuesday";
case Calendar.WEDNESDAY:
return "Wednesday";
case Calendar.THURSDAY:
return "Thursday";
case Calendar.FRIDAY:
return "Friday";
case Calendar.SATURDAY:
return "Saturday";
default:
break;
}
return null;
}
}
| apache-2.0 |
lijiangdong/News | app/src/main/java/com/ljd/news/presentation/presenter/Presenter.java | 743 | /*
* Copyright (C) 2016 Li Jiangdong 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.ljd.news.presentation.presenter;
public interface Presenter<T> {
void destroy();
void setView(T t);
}
| apache-2.0 |
hahhaheheh/lexiu | src/main/java/com/thinkgem/jeesite/modules/drh/service/GiftRecordService.java | 1130 | package com.thinkgem.jeesite.modules.drh.service;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.drh.dao.GiftRecordDao;
import com.thinkgem.jeesite.modules.drh.entity.GiftRecord;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by Niexuyang on 2017/11/15.
*/
@Service
public class GiftRecordService extends CrudService<GiftRecordDao,GiftRecord> {
@Override
public GiftRecord get(String id) {
return super.get(id);
}
@Override
public GiftRecord get(GiftRecord entity) {
return super.get(entity);
}
@Override
public List<GiftRecord> findList(GiftRecord entity) {
return super.findList(entity);
}
@Override
public Page<GiftRecord> findPage(Page<GiftRecord> page, GiftRecord entity) {
return super.findPage(page, entity);
}
@Override
public void save(GiftRecord entity) {
super.save(entity);
}
@Override
public void delete(GiftRecord entity) {
super.delete(entity);
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/transform/FailureDetailsMarshaller.java | 2551 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.elasticmapreduce.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.elasticmapreduce.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* FailureDetailsMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class FailureDetailsMarshaller {
private static final MarshallingInfo<String> REASON_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Reason").build();
private static final MarshallingInfo<String> MESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Message").build();
private static final MarshallingInfo<String> LOGFILE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("LogFile").build();
private static final FailureDetailsMarshaller instance = new FailureDetailsMarshaller();
public static FailureDetailsMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(FailureDetails failureDetails, ProtocolMarshaller protocolMarshaller) {
if (failureDetails == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(failureDetails.getReason(), REASON_BINDING);
protocolMarshaller.marshall(failureDetails.getMessage(), MESSAGE_BINDING);
protocolMarshaller.marshall(failureDetails.getLogFile(), LOGFILE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
magnetsystems/message-smack | smack-extensions/src/main/java/org/jivesoftware/smackx/pubsub/Node.java | 24763 | /**
*
* Copyright 2009 Robin Collier.
*
* 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.smackx.pubsub;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.filter.OrFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smackx.delay.DelayInformationManager;
import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
import org.jivesoftware.smackx.pubsub.listener.ItemDeleteListener;
import org.jivesoftware.smackx.pubsub.listener.ItemEventListener;
import org.jivesoftware.smackx.pubsub.listener.NodeConfigListener;
import org.jivesoftware.smackx.pubsub.packet.PubSub;
import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace;
import org.jivesoftware.smackx.pubsub.util.NodeUtils;
import org.jivesoftware.smackx.shim.packet.Header;
import org.jivesoftware.smackx.shim.packet.HeadersExtension;
import org.jivesoftware.smackx.xdata.Form;
import org.jxmpp.jid.Jid;
abstract public class Node
{
protected XMPPConnection con;
protected String id;
protected Jid to;
protected ConcurrentHashMap<ItemEventListener<Item>, PacketListener> itemEventToListenerMap = new ConcurrentHashMap<ItemEventListener<Item>, PacketListener>();
protected ConcurrentHashMap<ItemDeleteListener, PacketListener> itemDeleteToListenerMap = new ConcurrentHashMap<ItemDeleteListener, PacketListener>();
protected ConcurrentHashMap<NodeConfigListener, PacketListener> configEventToListenerMap = new ConcurrentHashMap<NodeConfigListener, PacketListener>();
/**
* Construct a node associated to the supplied connection with the specified
* node id.
*
* @param connection The connection the node is associated with
* @param nodeName The node id
*/
Node(XMPPConnection connection, String nodeName)
{
con = connection;
id = nodeName;
}
/**
* Some XMPP servers may require a specific service to be addressed on the
* server.
*
* For example, OpenFire requires the server to be prefixed by <b>pubsub</b>
*/
void setTo(Jid toAddress)
{
to = toAddress;
}
/**
* Get the NodeId
*
* @return the node id
*/
public String getId()
{
return id;
}
/**
* Returns a configuration form, from which you can create an answer form to be submitted
* via the {@link #sendConfigurationForm(Form)}.
*
* @return the configuration form
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
*/
public ConfigureForm getNodeConfiguration() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
PubSub pubSub = createPubsubPacket(Type.get, new NodeExtension(
PubSubElementType.CONFIGURE_OWNER, getId()), PubSubNamespace.OWNER);
Stanza reply = sendPubsubPacket(pubSub);
return NodeUtils.getFormFromPacket(reply, PubSubElementType.CONFIGURE_OWNER);
}
/**
* Update the configuration with the contents of the new {@link Form}
*
* @param submitForm
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
*/
public void sendConfigurationForm(Form submitForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
PubSub packet = createPubsubPacket(Type.set, new FormNode(FormNodeType.CONFIGURE_OWNER,
getId(), submitForm), PubSubNamespace.OWNER);
con.createPacketCollectorAndSend(packet).nextResultOrThrow();
}
/**
* Discover node information in standard {@link DiscoverInfo} format.
*
* @return The discovery information about the node.
* @throws XMPPErrorException
* @throws NoResponseException if there was no response from the server.
* @throws NotConnectedException
* @throws InterruptedException
*/
public DiscoverInfo discoverInfo() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
DiscoverInfo info = new DiscoverInfo();
info.setTo(to);
info.setNode(getId());
return (DiscoverInfo) con.createPacketCollectorAndSend(info).nextResultOrThrow();
}
/**
* Get the subscriptions currently associated with this node.
*
* @return List of {@link Subscription}
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
*
*/
public List<Subscription> getSubscriptions() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
return getSubscriptions(null, null);
}
/**
* Get the subscriptions currently associated with this node.
* <p>
* {@code additionalExtensions} can be used e.g. to add a "Result Set Management" extension.
* {@code returnedExtensions} will be filled with the packet extensions found in the answer.
* </p>
*
* @param additionalExtensions
* @param returnedExtensions a collection that will be filled with the returned packet
* extensions
* @return List of {@link Subscription}
* @throws NoResponseException
* @throws XMPPErrorException
* @throws NotConnectedException
* @throws InterruptedException
*/
public List<Subscription> getSubscriptions(List<PacketExtension> additionalExtensions, Collection<PacketExtension> returnedExtensions)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
return getSubscriptions(additionalExtensions, returnedExtensions, null);
}
/**
* Get the subscriptions currently associated with this node as owner.
*
* @return List of {@link Subscription}
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
* @see #getSubscriptionsAsOwner(List, Collection)
* @since 4.1
*/
public List<Subscription> getSubscriptionsAsOwner() throws NoResponseException, XMPPErrorException,
NotConnectedException, InterruptedException {
return getSubscriptionsAsOwner(null, null);
}
/**
* Get the subscriptions currently associated with this node as owner.
* <p>
* Unlike {@link #getSubscriptions(List, Collection)}, which only retrieves the subscriptions of the current entity
* ("user"), this method returns a list of <b>all</b> subscriptions. This requires the entity to have the sufficient
* privileges to manage subscriptions.
* </p>
* <p>
* {@code additionalExtensions} can be used e.g. to add a "Result Set Management" extension.
* {@code returnedExtensions} will be filled with the packet extensions found in the answer.
* </p>
*
* @param additionalExtensions
* @param returnedExtensions a collection that will be filled with the returned packet extensions
* @return List of {@link Subscription}
* @throws NoResponseException
* @throws XMPPErrorException
* @throws NotConnectedException
* @throws InterruptedException
* @see <a href="http://www.xmpp.org/extensions/xep-0060.html#owner-subscriptions-retrieve">XEP-60 § 8.8.1 -
* Retrieve Subscriptions List</a>
* @since 4.1
*/
public List<Subscription> getSubscriptionsAsOwner(List<PacketExtension> additionalExtensions,
Collection<PacketExtension> returnedExtensions) throws NoResponseException, XMPPErrorException,
NotConnectedException, InterruptedException {
return getSubscriptions(additionalExtensions, returnedExtensions, PubSubNamespace.OWNER);
}
private List<Subscription> getSubscriptions(List<PacketExtension> additionalExtensions,
Collection<PacketExtension> returnedExtensions, PubSubNamespace pubSubNamespace)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
PubSub pubSub = createPubsubPacket(Type.get, new NodeExtension(PubSubElementType.SUBSCRIPTIONS, getId()), pubSubNamespace);
if (additionalExtensions != null) {
for (PacketExtension pe : additionalExtensions) {
pubSub.addExtension(pe);
}
}
PubSub reply = sendPubsubPacket(pubSub);
if (returnedExtensions != null) {
returnedExtensions.addAll(reply.getExtensions());
}
SubscriptionsExtension subElem = (SubscriptionsExtension) reply.getExtension(PubSubElementType.SUBSCRIPTIONS);
return subElem.getSubscriptions();
}
/**
* Get the affiliations of this node.
*
* @return List of {@link Affiliation}
* @throws NoResponseException
* @throws XMPPErrorException
* @throws NotConnectedException
* @throws InterruptedException
*/
public List<Affiliation> getAffiliations() throws NoResponseException, XMPPErrorException,
NotConnectedException, InterruptedException {
return getAffiliations(null, null);
}
/**
* Get the affiliations of this node.
* <p>
* {@code additionalExtensions} can be used e.g. to add a "Result Set Management" extension.
* {@code returnedExtensions} will be filled with the packet extensions found in the answer.
* </p>
*
* @param additionalExtensions additional {@code PacketExtensions} add to the request
* @param returnedExtensions a collection that will be filled with the returned packet
* extensions
* @return List of {@link Affiliation}
* @throws NoResponseException
* @throws XMPPErrorException
* @throws NotConnectedException
* @throws InterruptedException
*/
public List<Affiliation> getAffiliations(List<PacketExtension> additionalExtensions, Collection<PacketExtension> returnedExtensions)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
PubSub pubSub = createPubsubPacket(Type.get, new NodeExtension(PubSubElementType.AFFILIATIONS, getId()));
if (additionalExtensions != null) {
for (PacketExtension pe : additionalExtensions) {
pubSub.addExtension(pe);
}
}
PubSub reply = sendPubsubPacket(pubSub);
if (returnedExtensions != null) {
returnedExtensions.addAll(reply.getExtensions());
}
AffiliationsExtension affilElem = (AffiliationsExtension) reply.getExtension(PubSubElementType.AFFILIATIONS);
return affilElem.getAffiliations();
}
/**
* The user subscribes to the node using the supplied jid. The
* bare jid portion of this one must match the jid for the connection.
*
* Please note that the {@link Subscription.State} should be checked
* on return since more actions may be required by the caller.
* {@link Subscription.State#pending} - The owner must approve the subscription
* request before messages will be received.
* {@link Subscription.State#unconfigured} - If the {@link Subscription#isConfigRequired()} is true,
* the caller must configure the subscription before messages will be received. If it is false
* the caller can configure it but is not required to do so.
* @param jid The jid to subscribe as.
* @return The subscription
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
*/
public Subscription subscribe(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
PubSub pubSub = createPubsubPacket(Type.set, new SubscribeExtension(jid, getId()));
PubSub reply = sendPubsubPacket(pubSub);
return reply.getExtension(PubSubElementType.SUBSCRIPTION);
}
/**
* The user subscribes to the node using the supplied jid and subscription
* options. The bare jid portion of this one must match the jid for the
* connection.
*
* Please note that the {@link Subscription.State} should be checked
* on return since more actions may be required by the caller.
* {@link Subscription.State#pending} - The owner must approve the subscription
* request before messages will be received.
* {@link Subscription.State#unconfigured} - If the {@link Subscription#isConfigRequired()} is true,
* the caller must configure the subscription before messages will be received. If it is false
* the caller can configure it but is not required to do so.
* @param jid The jid to subscribe as.
* @return The subscription
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
*/
public Subscription subscribe(String jid, SubscribeForm subForm) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
PubSub request = createPubsubPacket(Type.set, new SubscribeExtension(jid, getId()));
request.addExtension(new FormNode(FormNodeType.OPTIONS, subForm));
PubSub reply = PubSubManager.sendPubsubPacket(con, request);
return reply.getExtension(PubSubElementType.SUBSCRIPTION);
}
/**
* Remove the subscription related to the specified JID. This will only
* work if there is only 1 subscription. If there are multiple subscriptions,
* use {@link #unsubscribe(String, String)}.
*
* @param jid The JID used to subscribe to the node
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
*
*/
public void unsubscribe(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
unsubscribe(jid, null);
}
/**
* Remove the specific subscription related to the specified JID.
*
* @param jid The JID used to subscribe to the node
* @param subscriptionId The id of the subscription being removed
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
*/
public void unsubscribe(String jid, String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
sendPubsubPacket(createPubsubPacket(Type.set, new UnsubscribeExtension(jid, getId(), subscriptionId)));
}
/**
* Returns a SubscribeForm for subscriptions, from which you can create an answer form to be submitted
* via the {@link #sendConfigurationForm(Form)}.
*
* @return A subscription options form
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
*/
public SubscribeForm getSubscriptionOptions(String jid) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
return getSubscriptionOptions(jid, null);
}
/**
* Get the options for configuring the specified subscription.
*
* @param jid JID the subscription is registered under
* @param subscriptionId The subscription id
*
* @return The subscription option form
* @throws XMPPErrorException
* @throws NoResponseException
* @throws NotConnectedException
* @throws InterruptedException
*
*/
public SubscribeForm getSubscriptionOptions(String jid, String subscriptionId) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
PubSub packet = sendPubsubPacket(createPubsubPacket(Type.get, new OptionsExtension(jid, getId(), subscriptionId)));
FormNode ext = packet.getExtension(PubSubElementType.OPTIONS);
return new SubscribeForm(ext.getForm());
}
/**
* Register a listener for item publication events. This
* listener will get called whenever an item is published to
* this node.
*
* @param listener The handler for the event
*/
@SuppressWarnings("unchecked")
public void addItemEventListener(@SuppressWarnings("rawtypes") ItemEventListener listener)
{
PacketListener conListener = new ItemEventTranslator(listener);
itemEventToListenerMap.put(listener, conListener);
con.addSyncPacketListener(conListener, new EventContentFilter(EventElementType.items.toString(), "item"));
}
/**
* Unregister a listener for publication events.
*
* @param listener The handler to unregister
*/
public void removeItemEventListener(@SuppressWarnings("rawtypes") ItemEventListener listener)
{
PacketListener conListener = itemEventToListenerMap.remove(listener);
if (conListener != null)
con.removeSyncPacketListener(conListener);
}
/**
* Register a listener for configuration events. This listener
* will get called whenever the node's configuration changes.
*
* @param listener The handler for the event
*/
public void addConfigurationListener(NodeConfigListener listener)
{
PacketListener conListener = new NodeConfigTranslator(listener);
configEventToListenerMap.put(listener, conListener);
con.addSyncPacketListener(conListener, new EventContentFilter(EventElementType.configuration.toString()));
}
/**
* Unregister a listener for configuration events.
*
* @param listener The handler to unregister
*/
public void removeConfigurationListener(NodeConfigListener listener)
{
PacketListener conListener = configEventToListenerMap .remove(listener);
if (conListener != null)
con.removeSyncPacketListener(conListener);
}
/**
* Register an listener for item delete events. This listener
* gets called whenever an item is deleted from the node.
*
* @param listener The handler for the event
*/
public void addItemDeleteListener(ItemDeleteListener listener)
{
PacketListener delListener = new ItemDeleteTranslator(listener);
itemDeleteToListenerMap.put(listener, delListener);
EventContentFilter deleteItem = new EventContentFilter(EventElementType.items.toString(), "retract");
EventContentFilter purge = new EventContentFilter(EventElementType.purge.toString());
con.addSyncPacketListener(delListener, new OrFilter(deleteItem, purge));
}
/**
* Unregister a listener for item delete events.
*
* @param listener The handler to unregister
*/
public void removeItemDeleteListener(ItemDeleteListener listener)
{
PacketListener conListener = itemDeleteToListenerMap .remove(listener);
if (conListener != null)
con.removeSyncPacketListener(conListener);
}
@Override
public String toString()
{
return super.toString() + " " + getClass().getName() + " id: " + id;
}
protected PubSub createPubsubPacket(Type type, PacketExtension ext)
{
return createPubsubPacket(type, ext, null);
}
protected PubSub createPubsubPacket(Type type, PacketExtension ext, PubSubNamespace ns)
{
return PubSub.createPubsubPacket(to, type, ext, ns);
}
protected PubSub sendPubsubPacket(PubSub packet) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException
{
return PubSubManager.sendPubsubPacket(con, packet);
}
private static List<String> getSubscriptionIds(Stanza packet)
{
HeadersExtension headers = (HeadersExtension)packet.getExtension("headers", "http://jabber.org/protocol/shim");
List<String> values = null;
if (headers != null)
{
values = new ArrayList<String>(headers.getHeaders().size());
for (Header header : headers.getHeaders())
{
values.add(header.getValue());
}
}
return values;
}
/**
* This class translates low level item publication events into api level objects for
* user consumption.
*
* @author Robin Collier
*/
public class ItemEventTranslator implements PacketListener
{
@SuppressWarnings("rawtypes")
private ItemEventListener listener;
public ItemEventTranslator(@SuppressWarnings("rawtypes") ItemEventListener eventListener)
{
listener = eventListener;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void processPacket(Stanza packet)
{
EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns());
ItemsExtension itemsElem = (ItemsExtension)event.getEvent();
ItemPublishEvent eventItems = new ItemPublishEvent(itemsElem.getNode(), (List<Item>)itemsElem.getItems(), getSubscriptionIds(packet), DelayInformationManager.getDelayTimestamp(packet));
listener.handlePublishedItems(eventItems);
}
}
/**
* This class translates low level item deletion events into api level objects for
* user consumption.
*
* @author Robin Collier
*/
public class ItemDeleteTranslator implements PacketListener
{
private ItemDeleteListener listener;
public ItemDeleteTranslator(ItemDeleteListener eventListener)
{
listener = eventListener;
}
public void processPacket(Stanza packet)
{
EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns());
List<PacketExtension> extList = event.getExtensions();
if (extList.get(0).getElementName().equals(PubSubElementType.PURGE_EVENT.getElementName()))
{
listener.handlePurge();
}
else
{
ItemsExtension itemsElem = (ItemsExtension)event.getEvent();
@SuppressWarnings("unchecked")
Collection<RetractItem> pubItems = (Collection<RetractItem>) itemsElem.getItems();
List<String> items = new ArrayList<String>(pubItems.size());
for (RetractItem item : pubItems)
{
items.add(item.getId());
}
ItemDeleteEvent eventItems = new ItemDeleteEvent(itemsElem.getNode(), items, getSubscriptionIds(packet));
listener.handleDeletedItems(eventItems);
}
}
}
/**
* This class translates low level node configuration events into api level objects for
* user consumption.
*
* @author Robin Collier
*/
public class NodeConfigTranslator implements PacketListener
{
private NodeConfigListener listener;
public NodeConfigTranslator(NodeConfigListener eventListener)
{
listener = eventListener;
}
public void processPacket(Stanza packet)
{
EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns());
ConfigurationEvent config = (ConfigurationEvent)event.getEvent();
listener.handleNodeConfiguration(config);
}
}
/**
* Filter for {@link PacketListener} to filter out events not specific to the
* event type expected for this node.
*
* @author Robin Collier
*/
class EventContentFilter implements PacketFilter
{
private String firstElement;
private String secondElement;
EventContentFilter(String elementName)
{
firstElement = elementName;
}
EventContentFilter(String firstLevelEelement, String secondLevelElement)
{
firstElement = firstLevelEelement;
secondElement = secondLevelElement;
}
public boolean accept(Stanza packet)
{
if (!(packet instanceof Message))
return false;
EventElement event = (EventElement)packet.getExtension("event", PubSubNamespace.EVENT.getXmlns());
if (event == null)
return false;
NodeExtension embedEvent = event.getEvent();
if (embedEvent == null)
return false;
if (embedEvent.getElementName().equals(firstElement))
{
if (!embedEvent.getNode().equals(getId()))
return false;
if (secondElement == null)
return true;
if (embedEvent instanceof EmbeddedPacketExtension)
{
List<PacketExtension> secondLevelList = ((EmbeddedPacketExtension)embedEvent).getExtensions();
if (secondLevelList.size() > 0 && secondLevelList.get(0).getElementName().equals(secondElement))
return true;
}
}
return false;
}
}
}
| apache-2.0 |
kalyanreddyemani/opencga | opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/StorageManagerFactory.java | 7087 | /*
* Copyright 2015 OpenCB
*
* 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.opencb.opencga.storage.core;
import org.opencb.opencga.storage.core.alignment.AlignmentStorageManager;
import org.opencb.opencga.storage.core.config.StorageConfiguration;
import org.opencb.opencga.storage.core.config.StorageEngineConfiguration;
import org.opencb.opencga.storage.core.variant.VariantStorageManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Creates StorageManagers by reflexion.
* The StorageManager's className is read from <opencga-home>/conf/storage.properties
*/
public class StorageManagerFactory {
private static StorageManagerFactory storageManagerFactory;
private StorageConfiguration storageConfiguration;
private Map<String, AlignmentStorageManager> alignmentStorageManagerMap = new HashMap<>();
private Map<String, VariantStorageManager> variantStorageManagerMap = new HashMap<>();
protected static Logger logger = LoggerFactory.getLogger(StorageConfiguration.class);
public StorageManagerFactory(StorageConfiguration storageConfiguration) {
this.storageConfiguration = storageConfiguration;
}
public static StorageManagerFactory get() {
if (storageManagerFactory == null) {
try {
storageManagerFactory = new StorageManagerFactory(StorageConfiguration.load());
return storageManagerFactory;
} catch (IOException e) {
e.printStackTrace();
logger.error("Unable to get StorageManagerFactory");
}
}
return storageManagerFactory;
}
public AlignmentStorageManager getAlignmentStorageManager()
throws IllegalAccessException, InstantiationException, ClassNotFoundException {
return getAlignmentStorageManager(null);
}
public AlignmentStorageManager getAlignmentStorageManager(String storageEngineName)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
return getStorageManager("ALIGNMENT", storageEngineName, alignmentStorageManagerMap);
}
public VariantStorageManager getVariantStorageManager()
throws IllegalAccessException, InstantiationException, ClassNotFoundException {
return getVariantStorageManager(null);
}
public VariantStorageManager getVariantStorageManager(String storageEngineName)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
return getStorageManager("VARIANT", storageEngineName, variantStorageManagerMap);
}
private <T extends StorageManager> T getStorageManager(String bioformat, String storageEngineName, Map<String, T> storageManagerMap)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
/*
* This new block of code use new StorageConfiguration system, it must replace older one
*/
if(this.storageConfiguration == null) {
throw new NullPointerException();
}
if(!storageManagerMap.containsKey(storageEngineName)) {
String clazz = null;
switch (bioformat.toUpperCase()) {
case "ALIGNMENT":
clazz = this.storageConfiguration.getStorageEngine(storageEngineName).getAlignment().getManager();
break;
case "VARIANT":
clazz = this.storageConfiguration.getStorageEngine(storageEngineName).getVariant().getManager();
break;
}
T storageManager = (T) Class.forName(clazz).newInstance();
storageManager.setConfiguration(this.storageConfiguration, storageEngineName);
storageManagerMap.put(storageEngineName, storageManager);
}
return storageManagerMap.get(storageEngineName);
// // OLD CODE!!!
//
// // Get a valid StorageEngine name
// storageEngineName = parseStorageEngineName(storageEngineName);
// if(storageEngineName == null) {
// return null;
// }
//
//
// // Check if this already has been created
// if(!storageManagerMap.containsKey(storageEngineName)) {
// String key = "OPENCGA.STORAGE." + storageEngineName;
// Properties storageProperties = Config.getStorageProperties();
// String storageManagerClassName = storageProperties.getProperty(key + "." + bioformat + ".MANAGER");
// String propertiesPath = storageProperties.getProperty(key + ".CONF");
//
// // Specific VariantStorageManager is created by reflection using the Class name from the properties file.
// // The conf file is passed to the storage engine
// T storageManager = (T) Class.forName(storageManagerClassName).newInstance();
// storageManager.addConfigUri(URI.create(Config.getOpenCGAHome() + "/").resolve("conf/").resolve(propertiesPath));
//
// storageManagerMap.put(storageEngineName, storageManager);
// }
// return storageManagerMap.get(storageEngineName);
}
public String getDefaultStorageManagerName() {
return storageConfiguration.getDefaultStorageEngineId();
// String[] storageEngineNames = Config.getStorageProperties().getProperty("OPENCGA.STORAGE.ENGINES").split(",");
// return storageEngineNames[0].toUpperCase();
}
public List<String> getDefaultStorageManagerNames() {
return storageConfiguration.getStorageEngines().stream().map(StorageEngineConfiguration::getId).collect(Collectors.<String>toList());
// return Config.getStorageProperties().getProperty("OPENCGA.STORAGE.ENGINES").split(",");
}
// private static String parseStorageEngineName(String storageEngineName) {
// String[] storageEngineNames = Config.getStorageProperties().getProperty("OPENCGA.STORAGE.ENGINES").split(",");
// if(storageEngineName == null || storageEngineName.isEmpty()) {
// return storageEngineNames[0].toUpperCase();
// } else {
// storageEngineName = storageEngineName.toUpperCase();
// for (String engineName : storageEngineNames) {
// if(engineName.toUpperCase().equals(storageEngineName)) {
// return storageEngineName.toUpperCase();
// }
// }
// return null;
// }
// }
}
| apache-2.0 |
adligo/xml_io_generator_tests.adligo.org | src/org/adligo/xml_io_generators_tests/MockMutant.java | 999 | package org.adligo.xml_io_generators_tests;
import java.io.Serializable;
public class MockMutant implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private transient float fid;
private double did;
private transient short sid;
private long lid;
private String name;
private boolean b;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public float getFid() {
return fid;
}
public void setFid(float fid) {
this.fid = fid;
}
public double getDid() {
return did;
}
public void setDid(double did) {
this.did = did;
}
public short getSid() {
return sid;
}
public void setSid(short sid) {
this.sid = sid;
}
public long getLid() {
return lid;
}
public void setLid(long lid) {
this.lid = lid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isB() {
return b;
}
public void setB(boolean b) {
this.b = b;
}
}
| apache-2.0 |
google/bamboo-soy | src/main/java/com/google/bamboo/soy/file/SoyFileViewProviderFactory.java | 1347 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.bamboo.soy.file;
import com.google.bamboo.soy.SoyLanguage;
import com.intellij.lang.Language;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.FileViewProviderFactory;
import com.intellij.psi.PsiManager;
import org.jetbrains.annotations.NotNull;
public class SoyFileViewProviderFactory implements FileViewProviderFactory {
@NotNull
@Override
public FileViewProvider createFileViewProvider(
@NotNull VirtualFile virtualFile,
Language language,
@NotNull PsiManager psiManager,
boolean eventSystemEnabled) {
assert language.isKindOf(SoyLanguage.INSTANCE);
return new SoyFileViewProvider(psiManager, virtualFile, eventSystemEnabled);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/KeyPair.java | 20306 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lightsail.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes an SSH key pair.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/KeyPair" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class KeyPair implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The friendly name of the SSH key pair.
* </p>
*/
private String name;
/**
* <p>
* The Amazon Resource Name (ARN) of the key pair (e.g.,
* <code>arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE</code>).
* </p>
*/
private String arn;
/**
* <p>
* The support code. Include this code in your email to support when you have questions about an instance or another
* resource in Lightsail. This code enables our support team to look up your Lightsail information more easily.
* </p>
*/
private String supportCode;
/**
* <p>
* The timestamp when the key pair was created (e.g., <code>1479816991.349</code>).
* </p>
*/
private java.util.Date createdAt;
/**
* <p>
* The region name and Availability Zone where the key pair was created.
* </p>
*/
private ResourceLocation location;
/**
* <p>
* The resource type (usually <code>KeyPair</code>).
* </p>
*/
private String resourceType;
/**
* <p>
* The tag keys and optional values for the resource. For more information about tags in Lightsail, see the <a
* href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags">Amazon Lightsail Developer
* Guide</a>.
* </p>
*/
private java.util.List<Tag> tags;
/**
* <p>
* The RSA fingerprint of the key pair.
* </p>
*/
private String fingerprint;
/**
* <p>
* The friendly name of the SSH key pair.
* </p>
*
* @param name
* The friendly name of the SSH key pair.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The friendly name of the SSH key pair.
* </p>
*
* @return The friendly name of the SSH key pair.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The friendly name of the SSH key pair.
* </p>
*
* @param name
* The friendly name of the SSH key pair.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KeyPair withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the key pair (e.g.,
* <code>arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE</code>).
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the key pair (e.g.,
* <code>arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE</code>).
*/
public void setArn(String arn) {
this.arn = arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the key pair (e.g.,
* <code>arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE</code>).
* </p>
*
* @return The Amazon Resource Name (ARN) of the key pair (e.g.,
* <code>arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE</code>).
*/
public String getArn() {
return this.arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the key pair (e.g.,
* <code>arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE</code>).
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the key pair (e.g.,
* <code>arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KeyPair withArn(String arn) {
setArn(arn);
return this;
}
/**
* <p>
* The support code. Include this code in your email to support when you have questions about an instance or another
* resource in Lightsail. This code enables our support team to look up your Lightsail information more easily.
* </p>
*
* @param supportCode
* The support code. Include this code in your email to support when you have questions about an instance or
* another resource in Lightsail. This code enables our support team to look up your Lightsail information
* more easily.
*/
public void setSupportCode(String supportCode) {
this.supportCode = supportCode;
}
/**
* <p>
* The support code. Include this code in your email to support when you have questions about an instance or another
* resource in Lightsail. This code enables our support team to look up your Lightsail information more easily.
* </p>
*
* @return The support code. Include this code in your email to support when you have questions about an instance or
* another resource in Lightsail. This code enables our support team to look up your Lightsail information
* more easily.
*/
public String getSupportCode() {
return this.supportCode;
}
/**
* <p>
* The support code. Include this code in your email to support when you have questions about an instance or another
* resource in Lightsail. This code enables our support team to look up your Lightsail information more easily.
* </p>
*
* @param supportCode
* The support code. Include this code in your email to support when you have questions about an instance or
* another resource in Lightsail. This code enables our support team to look up your Lightsail information
* more easily.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KeyPair withSupportCode(String supportCode) {
setSupportCode(supportCode);
return this;
}
/**
* <p>
* The timestamp when the key pair was created (e.g., <code>1479816991.349</code>).
* </p>
*
* @param createdAt
* The timestamp when the key pair was created (e.g., <code>1479816991.349</code>).
*/
public void setCreatedAt(java.util.Date createdAt) {
this.createdAt = createdAt;
}
/**
* <p>
* The timestamp when the key pair was created (e.g., <code>1479816991.349</code>).
* </p>
*
* @return The timestamp when the key pair was created (e.g., <code>1479816991.349</code>).
*/
public java.util.Date getCreatedAt() {
return this.createdAt;
}
/**
* <p>
* The timestamp when the key pair was created (e.g., <code>1479816991.349</code>).
* </p>
*
* @param createdAt
* The timestamp when the key pair was created (e.g., <code>1479816991.349</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KeyPair withCreatedAt(java.util.Date createdAt) {
setCreatedAt(createdAt);
return this;
}
/**
* <p>
* The region name and Availability Zone where the key pair was created.
* </p>
*
* @param location
* The region name and Availability Zone where the key pair was created.
*/
public void setLocation(ResourceLocation location) {
this.location = location;
}
/**
* <p>
* The region name and Availability Zone where the key pair was created.
* </p>
*
* @return The region name and Availability Zone where the key pair was created.
*/
public ResourceLocation getLocation() {
return this.location;
}
/**
* <p>
* The region name and Availability Zone where the key pair was created.
* </p>
*
* @param location
* The region name and Availability Zone where the key pair was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KeyPair withLocation(ResourceLocation location) {
setLocation(location);
return this;
}
/**
* <p>
* The resource type (usually <code>KeyPair</code>).
* </p>
*
* @param resourceType
* The resource type (usually <code>KeyPair</code>).
* @see ResourceType
*/
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
/**
* <p>
* The resource type (usually <code>KeyPair</code>).
* </p>
*
* @return The resource type (usually <code>KeyPair</code>).
* @see ResourceType
*/
public String getResourceType() {
return this.resourceType;
}
/**
* <p>
* The resource type (usually <code>KeyPair</code>).
* </p>
*
* @param resourceType
* The resource type (usually <code>KeyPair</code>).
* @return Returns a reference to this object so that method calls can be chained together.
* @see ResourceType
*/
public KeyPair withResourceType(String resourceType) {
setResourceType(resourceType);
return this;
}
/**
* <p>
* The resource type (usually <code>KeyPair</code>).
* </p>
*
* @param resourceType
* The resource type (usually <code>KeyPair</code>).
* @see ResourceType
*/
public void setResourceType(ResourceType resourceType) {
withResourceType(resourceType);
}
/**
* <p>
* The resource type (usually <code>KeyPair</code>).
* </p>
*
* @param resourceType
* The resource type (usually <code>KeyPair</code>).
* @return Returns a reference to this object so that method calls can be chained together.
* @see ResourceType
*/
public KeyPair withResourceType(ResourceType resourceType) {
this.resourceType = resourceType.toString();
return this;
}
/**
* <p>
* The tag keys and optional values for the resource. For more information about tags in Lightsail, see the <a
* href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags">Amazon Lightsail Developer
* Guide</a>.
* </p>
*
* @return The tag keys and optional values for the resource. For more information about tags in Lightsail, see the
* <a href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags">Amazon Lightsail
* Developer Guide</a>.
*/
public java.util.List<Tag> getTags() {
return tags;
}
/**
* <p>
* The tag keys and optional values for the resource. For more information about tags in Lightsail, see the <a
* href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags">Amazon Lightsail Developer
* Guide</a>.
* </p>
*
* @param tags
* The tag keys and optional values for the resource. For more information about tags in Lightsail, see the
* <a href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags">Amazon Lightsail
* Developer Guide</a>.
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new java.util.ArrayList<Tag>(tags);
}
/**
* <p>
* The tag keys and optional values for the resource. For more information about tags in Lightsail, see the <a
* href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags">Amazon Lightsail Developer
* Guide</a>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* The tag keys and optional values for the resource. For more information about tags in Lightsail, see the
* <a href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags">Amazon Lightsail
* Developer Guide</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KeyPair withTags(Tag... tags) {
if (this.tags == null) {
setTags(new java.util.ArrayList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* The tag keys and optional values for the resource. For more information about tags in Lightsail, see the <a
* href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags">Amazon Lightsail Developer
* Guide</a>.
* </p>
*
* @param tags
* The tag keys and optional values for the resource. For more information about tags in Lightsail, see the
* <a href="https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-tags">Amazon Lightsail
* Developer Guide</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KeyPair withTags(java.util.Collection<Tag> tags) {
setTags(tags);
return this;
}
/**
* <p>
* The RSA fingerprint of the key pair.
* </p>
*
* @param fingerprint
* The RSA fingerprint of the key pair.
*/
public void setFingerprint(String fingerprint) {
this.fingerprint = fingerprint;
}
/**
* <p>
* The RSA fingerprint of the key pair.
* </p>
*
* @return The RSA fingerprint of the key pair.
*/
public String getFingerprint() {
return this.fingerprint;
}
/**
* <p>
* The RSA fingerprint of the key pair.
* </p>
*
* @param fingerprint
* The RSA fingerprint of the key pair.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public KeyPair withFingerprint(String fingerprint) {
setFingerprint(fingerprint);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getArn() != null)
sb.append("Arn: ").append(getArn()).append(",");
if (getSupportCode() != null)
sb.append("SupportCode: ").append(getSupportCode()).append(",");
if (getCreatedAt() != null)
sb.append("CreatedAt: ").append(getCreatedAt()).append(",");
if (getLocation() != null)
sb.append("Location: ").append(getLocation()).append(",");
if (getResourceType() != null)
sb.append("ResourceType: ").append(getResourceType()).append(",");
if (getTags() != null)
sb.append("Tags: ").append(getTags()).append(",");
if (getFingerprint() != null)
sb.append("Fingerprint: ").append(getFingerprint());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof KeyPair == false)
return false;
KeyPair other = (KeyPair) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getArn() == null ^ this.getArn() == null)
return false;
if (other.getArn() != null && other.getArn().equals(this.getArn()) == false)
return false;
if (other.getSupportCode() == null ^ this.getSupportCode() == null)
return false;
if (other.getSupportCode() != null && other.getSupportCode().equals(this.getSupportCode()) == false)
return false;
if (other.getCreatedAt() == null ^ this.getCreatedAt() == null)
return false;
if (other.getCreatedAt() != null && other.getCreatedAt().equals(this.getCreatedAt()) == false)
return false;
if (other.getLocation() == null ^ this.getLocation() == null)
return false;
if (other.getLocation() != null && other.getLocation().equals(this.getLocation()) == false)
return false;
if (other.getResourceType() == null ^ this.getResourceType() == null)
return false;
if (other.getResourceType() != null && other.getResourceType().equals(this.getResourceType()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
if (other.getFingerprint() == null ^ this.getFingerprint() == null)
return false;
if (other.getFingerprint() != null && other.getFingerprint().equals(this.getFingerprint()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode());
hashCode = prime * hashCode + ((getSupportCode() == null) ? 0 : getSupportCode().hashCode());
hashCode = prime * hashCode + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode());
hashCode = prime * hashCode + ((getLocation() == null) ? 0 : getLocation().hashCode());
hashCode = prime * hashCode + ((getResourceType() == null) ? 0 : getResourceType().hashCode());
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
hashCode = prime * hashCode + ((getFingerprint() == null) ? 0 : getFingerprint().hashCode());
return hashCode;
}
@Override
public KeyPair clone() {
try {
return (KeyPair) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.lightsail.model.transform.KeyPairMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
noemus/kotlin-eclipse | kotlin-eclipse-ui-test/src/org/jetbrains/kotlin/ui/tests/scripts/templates/KotlinScriptWithTemplateResolveTest.java | 658 | package org.jetbrains.kotlin.ui.tests.scripts.templates;
import org.junit.Test;
public class KotlinScriptWithTemplateResolveTest extends KotlinScriptWithTemplateResolveTestCase {
@Test
public void testSample() {
doTest("testData/scripts/templates/sample.testDef.kts");
}
@Test
public void testStandard() {
doTest("testData/scripts/templates/standard.kts");
}
@Test
public void testSampleEx() {
doTest("testData/scripts/templates/sampleEx.testDef.kts");
}
@Test
public void testCustomEPResolver() {
doTest("testData/scripts/templates/customEPResolver.kts");
}
}
| apache-2.0 |
davido/buck | src/com/facebook/buck/thrift/ThriftJavaEnhancer.java | 8015 | /*
* Copyright 2014-present Facebook, 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.facebook.buck.thrift;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.jvm.java.CalculateAbi;
import com.facebook.buck.jvm.java.DefaultJavaLibrary;
import com.facebook.buck.jvm.java.JavaLibraryRules;
import com.facebook.buck.jvm.java.Javac;
import com.facebook.buck.jvm.java.JavacOptions;
import com.facebook.buck.jvm.java.JavacOptionsAmender;
import com.facebook.buck.jvm.java.JavacToJarStepFactory;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.ImmutableFlavor;
import com.facebook.buck.model.UnflavoredBuildTarget;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRules;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Suppliers;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Ordering;
import java.nio.file.Path;
import java.util.Optional;
public class ThriftJavaEnhancer implements ThriftLanguageSpecificEnhancer {
private static final Flavor JAVA_FLAVOR = ImmutableFlavor.of("java");
private final ThriftBuckConfig thriftBuckConfig;
private final JavacOptions templateOptions;
public ThriftJavaEnhancer(
ThriftBuckConfig thriftBuckConfig,
JavacOptions templateOptions) {
this.thriftBuckConfig = thriftBuckConfig;
this.templateOptions = templateOptions;
}
@Override
public String getLanguage() {
return "java";
}
@Override
public Flavor getFlavor() {
return JAVA_FLAVOR;
}
@Override
public ImmutableSortedSet<String> getGeneratedSources(
BuildTarget target,
ThriftConstructorArg args,
String thriftName,
ImmutableList<String> services) {
return ImmutableSortedSet.of("");
}
@VisibleForTesting
protected BuildTarget getSourceZipBuildTarget(UnflavoredBuildTarget target, String name) {
return BuildTargets.createFlavoredBuildTarget(
target,
ImmutableFlavor.of(
String.format(
"thrift-java-source-zip-%s",
name.replace('/', '-').replace('.', '-').replace('+', '-').replace(' ', '-'))));
}
private Path getSourceZipOutputPath(
ProjectFilesystem filesystem,
UnflavoredBuildTarget target,
String name) {
BuildTarget flavoredTarget = getSourceZipBuildTarget(target, name);
return BuildTargets.getScratchPath(filesystem, flavoredTarget, "%s" + Javac.SRC_ZIP);
}
@Override
public BuildRule createBuildRule(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
ThriftConstructorArg args,
ImmutableMap<String, ThriftSource> sources,
ImmutableSortedSet<BuildRule> deps) throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
if (CalculateAbi.isAbiTarget(params.getBuildTarget())) {
BuildTarget libraryTarget = CalculateAbi.getLibraryTarget(params.getBuildTarget());
BuildRule libraryRule = resolver.requireRule(libraryTarget);
return CalculateAbi.of(
params.getBuildTarget(),
ruleFinder,
params,
Preconditions.checkNotNull(libraryRule.getSourcePathToOutput()));
}
// Pack all the generated sources into a single source zip that we'll pass to the
// java rule below.
ImmutableSortedSet.Builder<BuildRule> sourceZipsBuilder = ImmutableSortedSet.naturalOrder();
UnflavoredBuildTarget unflavoredBuildTarget =
params.getBuildTarget().getUnflavoredBuildTarget();
for (ImmutableMap.Entry<String, ThriftSource> ent : sources.entrySet()) {
String name = ent.getKey();
BuildTarget compilerTarget = ent.getValue().getCompileTarget();
Path sourceDirectory = ent.getValue().getOutputDir(resolver).resolve("gen-java");
BuildTarget sourceZipTarget = getSourceZipBuildTarget(unflavoredBuildTarget, name);
Path sourceZip =
getSourceZipOutputPath(params.getProjectFilesystem(), unflavoredBuildTarget, name);
sourceZipsBuilder.add(
new SrcZip(
params.copyWithChanges(
sourceZipTarget,
Suppliers.ofInstance(ImmutableSortedSet.of(resolver.getRule(compilerTarget))),
Suppliers.ofInstance(ImmutableSortedSet.of())),
sourceZip,
sourceDirectory));
}
ImmutableSortedSet<BuildRule> sourceZips = sourceZipsBuilder.build();
resolver.addAllToIndex(sourceZips);
// Create to main compile rule.
BuildRuleParams javaParams = params.copyWithChanges(
BuildTargets.createFlavoredBuildTarget(
unflavoredBuildTarget,
getFlavor()),
Suppliers.ofInstance(
ImmutableSortedSet.<BuildRule>naturalOrder()
.addAll(sourceZips)
.addAll(deps)
.addAll(BuildRules.getExportedRules(deps))
.addAll(ruleFinder.filterBuildRuleInputs(templateOptions.getInputs(ruleFinder)))
.build()),
Suppliers.ofInstance(ImmutableSortedSet.of()));
final SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
return new DefaultJavaLibrary(
javaParams,
pathResolver,
ruleFinder,
FluentIterable.from(sourceZips)
.transform(BuildRule::getSourcePathToOutput)
.toSortedSet(Ordering.natural()),
/* resources */ ImmutableSet.of(),
templateOptions.getGeneratedSourceFolderName(),
/* proguardConfig */ Optional.empty(),
/* postprocessClassesCommands */ ImmutableList.of(),
/* exportedDeps */ ImmutableSortedSet.of(),
/* providedDeps */ ImmutableSortedSet.of(),
JavaLibraryRules.getAbiInputs(resolver, javaParams.getDeps()),
templateOptions.trackClassUsage(),
/* additionalClasspathEntries */ ImmutableSet.of(),
new JavacToJarStepFactory(templateOptions, JavacOptionsAmender.IDENTITY),
/* resourcesRoot */ Optional.empty(),
/* manifest file */ Optional.empty(),
/* mavenCoords */ Optional.empty(),
/* tests */ ImmutableSortedSet.of(),
/* classesToRemoveFromJar */ ImmutableSet.of());
}
private ImmutableSet<BuildTarget> getImplicitDeps() {
return ImmutableSet.of(thriftBuckConfig.getJavaDep());
}
@Override
public ImmutableSet<BuildTarget> getImplicitDepsForTargetFromConstructorArg(
BuildTarget target,
ThriftConstructorArg args) {
return getImplicitDeps();
}
@Override
public ImmutableSet<String> getOptions(BuildTarget target, ThriftConstructorArg arg) {
return arg.javaOptions;
}
@Override
public ThriftLibraryDescription.CompilerType getCompilerType() {
return ThriftLibraryDescription.CompilerType.THRIFT;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/ListApplicationsResult.java | 9350 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kinesisanalyticsv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalyticsv2-2018-05-23/ListApplications"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListApplicationsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A list of <code>ApplicationSummary</code> objects.
* </p>
*/
private java.util.List<ApplicationSummary> applicationSummaries;
/**
* <p>
* The pagination token for the next set of results, or <code>null</code> if there are no additional results. Pass
* this token into a subsequent command to retrieve the next set of items For more information about pagination, see
* <a href="https://docs.aws.amazon.com/cli/latest/userguide/pagination.html">Using the Amazon Command Line
* Interface's Pagination Options</a>.
* </p>
*/
private String nextToken;
/**
* <p>
* A list of <code>ApplicationSummary</code> objects.
* </p>
*
* @return A list of <code>ApplicationSummary</code> objects.
*/
public java.util.List<ApplicationSummary> getApplicationSummaries() {
return applicationSummaries;
}
/**
* <p>
* A list of <code>ApplicationSummary</code> objects.
* </p>
*
* @param applicationSummaries
* A list of <code>ApplicationSummary</code> objects.
*/
public void setApplicationSummaries(java.util.Collection<ApplicationSummary> applicationSummaries) {
if (applicationSummaries == null) {
this.applicationSummaries = null;
return;
}
this.applicationSummaries = new java.util.ArrayList<ApplicationSummary>(applicationSummaries);
}
/**
* <p>
* A list of <code>ApplicationSummary</code> objects.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setApplicationSummaries(java.util.Collection)} or {@link #withApplicationSummaries(java.util.Collection)}
* if you want to override the existing values.
* </p>
*
* @param applicationSummaries
* A list of <code>ApplicationSummary</code> objects.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListApplicationsResult withApplicationSummaries(ApplicationSummary... applicationSummaries) {
if (this.applicationSummaries == null) {
setApplicationSummaries(new java.util.ArrayList<ApplicationSummary>(applicationSummaries.length));
}
for (ApplicationSummary ele : applicationSummaries) {
this.applicationSummaries.add(ele);
}
return this;
}
/**
* <p>
* A list of <code>ApplicationSummary</code> objects.
* </p>
*
* @param applicationSummaries
* A list of <code>ApplicationSummary</code> objects.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListApplicationsResult withApplicationSummaries(java.util.Collection<ApplicationSummary> applicationSummaries) {
setApplicationSummaries(applicationSummaries);
return this;
}
/**
* <p>
* The pagination token for the next set of results, or <code>null</code> if there are no additional results. Pass
* this token into a subsequent command to retrieve the next set of items For more information about pagination, see
* <a href="https://docs.aws.amazon.com/cli/latest/userguide/pagination.html">Using the Amazon Command Line
* Interface's Pagination Options</a>.
* </p>
*
* @param nextToken
* The pagination token for the next set of results, or <code>null</code> if there are no additional results.
* Pass this token into a subsequent command to retrieve the next set of items For more information about
* pagination, see <a href="https://docs.aws.amazon.com/cli/latest/userguide/pagination.html">Using the
* Amazon Command Line Interface's Pagination Options</a>.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The pagination token for the next set of results, or <code>null</code> if there are no additional results. Pass
* this token into a subsequent command to retrieve the next set of items For more information about pagination, see
* <a href="https://docs.aws.amazon.com/cli/latest/userguide/pagination.html">Using the Amazon Command Line
* Interface's Pagination Options</a>.
* </p>
*
* @return The pagination token for the next set of results, or <code>null</code> if there are no additional
* results. Pass this token into a subsequent command to retrieve the next set of items For more information
* about pagination, see <a href="https://docs.aws.amazon.com/cli/latest/userguide/pagination.html">Using
* the Amazon Command Line Interface's Pagination Options</a>.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The pagination token for the next set of results, or <code>null</code> if there are no additional results. Pass
* this token into a subsequent command to retrieve the next set of items For more information about pagination, see
* <a href="https://docs.aws.amazon.com/cli/latest/userguide/pagination.html">Using the Amazon Command Line
* Interface's Pagination Options</a>.
* </p>
*
* @param nextToken
* The pagination token for the next set of results, or <code>null</code> if there are no additional results.
* Pass this token into a subsequent command to retrieve the next set of items For more information about
* pagination, see <a href="https://docs.aws.amazon.com/cli/latest/userguide/pagination.html">Using the
* Amazon Command Line Interface's Pagination Options</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListApplicationsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getApplicationSummaries() != null)
sb.append("ApplicationSummaries: ").append(getApplicationSummaries()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListApplicationsResult == false)
return false;
ListApplicationsResult other = (ListApplicationsResult) obj;
if (other.getApplicationSummaries() == null ^ this.getApplicationSummaries() == null)
return false;
if (other.getApplicationSummaries() != null && other.getApplicationSummaries().equals(this.getApplicationSummaries()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getApplicationSummaries() == null) ? 0 : getApplicationSummaries().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ListApplicationsResult clone() {
try {
return (ListApplicationsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
actframework/actframework | src/main/java/act/cli/InvalidCommandLineException.java | 988 | package act.cli;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* 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.
* #L%
*/
import org.osgl.exception.InvalidArgException;
public class InvalidCommandLineException extends InvalidArgException {
public InvalidCommandLineException(String message) {
super(message);
}
public InvalidCommandLineException(String message, Object... args) {
super(message, args);
}
}
| apache-2.0 |
tamsler/raffle-app | app/src/main/java/org/thomasamsler/raffleapp/activities/RaffleDetailActivity.java | 896 | package org.thomasamsler.raffleapp.activities;
import android.app.Activity;
import android.os.Bundle;
import org.thomasamsler.raffleapp.AppConstants;
import org.thomasamsler.raffleapp.R;
import org.thomasamsler.raffleapp.fragments.RaffleDetailFragment;
public class RaffleDetailActivity extends Activity implements AppConstants {
private String mRaffleId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_raffle_detail);
mRaffleId = getIntent().getExtras().getString(RAFFLE_ID_KEY);
if(savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, RaffleDetailFragment.newInstance(mRaffleId))
.commit();
}
setTitle(R.string.activity_raffle_detail_name);
}
}
| apache-2.0 |
huyongli/TigerVideo | TigerVideoPlayer/src/main/java/cn/ittiger/player/util/ViewIndex.java | 303 | package cn.ittiger.player.util;
/**
* @author: ylhu
* @time: 2017/12/12
*/
public final class ViewIndex {
public static final int VIDEO_THUMB_VIEW_INDEX = 1;
public static final int FULLSCREEN_GESTURE_VIEW_INDEX = 2;
public static final int VIDEO_CONTROLLER_VIEW_INDEX = 3;
}
| apache-2.0 |
Sargul/dbeaver | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/auth/DBASessionContext.java | 1456 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* 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.jkiss.dbeaver.model.auth;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.access.DBASession;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
/**
* Session context.
* Holds various auth sessions.
*/
public interface DBASessionContext {
/**
* Find and opens space session
* @param space target space
* @param open if true then new session will be opened if possible
*/
@Nullable
DBASession getSpaceSession(@NotNull DBRProgressMonitor monitor, @NotNull DBAAuthSpace space, boolean open) throws DBException;
DBAAuthToken[] getSavedTokens();
void addSession(@NotNull DBASession session);
boolean removeSession(@NotNull DBASession session);
}
| apache-2.0 |
amzn/exoplayer-amazon-port | library/transformer/src/test/java/com/google/android/exoplayer2/transformer/TransformerTest.java | 23437 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.transformer;
import static com.google.android.exoplayer2.transformer.Transformer.PROGRESS_STATE_AVAILABLE;
import static com.google.android.exoplayer2.transformer.Transformer.PROGRESS_STATE_NO_TRANSFORMATION;
import static com.google.android.exoplayer2.transformer.Transformer.PROGRESS_STATE_UNAVAILABLE;
import static com.google.android.exoplayer2.transformer.Transformer.PROGRESS_STATE_WAITING_FOR_AVAILABILITY;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.testutil.AutoAdvancingFakeClock;
import com.google.android.exoplayer2.testutil.DumpFileAsserts;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.Util;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.shadows.ShadowMediaCodec;
/** Unit test for {@link Transformer}. */
@RunWith(AndroidJUnit4.class)
public final class TransformerTest {
private static final String URI_PREFIX = "asset:///media/";
private static final String FILE_VIDEO_ONLY = "mkv/sample.mkv";
private static final String FILE_AUDIO_ONLY = "amr/sample_nb.amr";
private static final String FILE_AUDIO_VIDEO = "mp4/sample.mp4";
private static final String FILE_WITH_SUBTITLES = "mkv/sample_with_srt.mkv";
private static final String FILE_WITH_SEF_SLOW_MOTION = "mp4/sample_sef_slow_motion.mp4";
private static final String FILE_WITH_ALL_SAMPLE_FORMATS_UNSUPPORTED = "mp4/sample_ac3.mp4";
private static final String FILE_UNKNOWN_DURATION = "mp4/sample_fragmented.mp4";
public static final String DUMP_FILE_OUTPUT_DIRECTORY = "transformerdumps";
public static final String DUMP_FILE_EXTENSION = "dump";
private Context context;
private String outputPath;
private TestMuxer testMuxer;
private AutoAdvancingFakeClock clock;
private ProgressHolder progressHolder;
@Before
public void setUp() throws Exception {
context = ApplicationProvider.getApplicationContext();
outputPath = Util.createTempFile(context, "TransformerTest").getPath();
clock = new AutoAdvancingFakeClock();
progressHolder = new ProgressHolder();
createEncodersAndDecoders();
}
@After
public void tearDown() throws Exception {
Files.delete(Paths.get(outputPath));
removeEncodersAndDecoders();
}
@Test
public void startTransformation_videoOnly_completesSuccessfully() throws Exception {
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_VIDEO_ONLY);
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
DumpFileAsserts.assertOutput(context, testMuxer, getDumpFileName(FILE_VIDEO_ONLY));
}
@Test
public void startTransformation_audioOnly_completesSuccessfully() throws Exception {
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_AUDIO_ONLY);
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
DumpFileAsserts.assertOutput(context, testMuxer, getDumpFileName(FILE_AUDIO_ONLY));
}
@Test
public void startTransformation_audioAndVideo_completesSuccessfully() throws Exception {
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_AUDIO_VIDEO);
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
DumpFileAsserts.assertOutput(context, testMuxer, getDumpFileName(FILE_AUDIO_VIDEO));
}
@Test
public void startTransformation_withSubtitles_completesSuccessfully() throws Exception {
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_WITH_SUBTITLES);
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
DumpFileAsserts.assertOutput(context, testMuxer, getDumpFileName(FILE_WITH_SUBTITLES));
}
@Test
public void startTransformation_successiveTransformations_completesSuccessfully()
throws Exception {
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_VIDEO_ONLY);
// Transform first media item.
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
Files.delete(Paths.get(outputPath));
// Transformer.startTransformation() will create a new SimpleExoPlayer instance. Reset the
// clock's handler so that the clock advances with the new SimpleExoPlayer instance.
clock.resetHandler();
// Transform second media item.
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
DumpFileAsserts.assertOutput(context, testMuxer, getDumpFileName(FILE_VIDEO_ONLY));
}
@Test
public void startTransformation_concurrentTransformations_throwsError() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_VIDEO_ONLY);
transformer.startTransformation(mediaItem, outputPath);
assertThrows(
IllegalStateException.class, () -> transformer.startTransformation(mediaItem, outputPath));
}
@Test
public void startTransformation_removeAudio_completesSuccessfully() throws Exception {
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setRemoveAudio(true)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_AUDIO_VIDEO);
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
DumpFileAsserts.assertOutput(
context, testMuxer, getDumpFileName(FILE_AUDIO_VIDEO + ".noaudio"));
}
@Test
public void startTransformation_removeVideo_completesSuccessfully() throws Exception {
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setRemoveVideo(true)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_AUDIO_VIDEO);
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
DumpFileAsserts.assertOutput(
context, testMuxer, getDumpFileName(FILE_AUDIO_VIDEO + ".novideo"));
}
@Test
public void startTransformation_flattenForSlowMotion_completesSuccessfully() throws Exception {
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setFlattenForSlowMotion(true)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_WITH_SEF_SLOW_MOTION);
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
DumpFileAsserts.assertOutput(context, testMuxer, getDumpFileName(FILE_WITH_SEF_SLOW_MOTION));
}
@Test
public void startTransformation_withPlayerError_completesWithError() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
MediaItem mediaItem = MediaItem.fromUri("asset:///non-existing-path.mp4");
transformer.startTransformation(mediaItem, outputPath);
Exception exception = TransformerTestRunner.runUntilError(transformer);
assertThat(exception).isInstanceOf(ExoPlaybackException.class);
assertThat(exception).hasCauseThat().isInstanceOf(IOException.class);
}
@Test
public void startTransformation_withAllSampleFormatsUnsupported_completesWithError()
throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_WITH_ALL_SAMPLE_FORMATS_UNSUPPORTED);
transformer.startTransformation(mediaItem, outputPath);
Exception exception = TransformerTestRunner.runUntilError(transformer);
assertThat(exception).isInstanceOf(IllegalStateException.class);
}
@Test
public void startTransformation_afterCancellation_completesSuccessfully() throws Exception {
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_VIDEO_ONLY);
transformer.startTransformation(mediaItem, outputPath);
transformer.cancel();
Files.delete(Paths.get(outputPath));
// Transformer.startTransformation() will create a new SimpleExoPlayer instance. Reset the
// clock's handler so that the clock advances with the new SimpleExoPlayer instance.
clock.resetHandler();
// This would throw if the previous transformation had not been cancelled.
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
DumpFileAsserts.assertOutput(context, testMuxer, getDumpFileName(FILE_VIDEO_ONLY));
}
@Test
public void startTransformation_fromSpecifiedThread_completesSuccessfully() throws Exception {
HandlerThread anotherThread = new HandlerThread("AnotherThread");
anotherThread.start();
Looper looper = anotherThread.getLooper();
Transformer transformer =
new Transformer.Builder()
.setContext(context)
.setLooper(looper)
.setClock(clock)
.setMuxerFactory(new TestMuxerFactory())
.build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_AUDIO_ONLY);
AtomicReference<Exception> exception = new AtomicReference<>();
CountDownLatch countDownLatch = new CountDownLatch(1);
new Handler(looper)
.post(
() -> {
try {
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
} catch (Exception e) {
exception.set(e);
} finally {
countDownLatch.countDown();
}
});
countDownLatch.await();
assertThat(exception.get()).isNull();
DumpFileAsserts.assertOutput(context, testMuxer, getDumpFileName(FILE_AUDIO_ONLY));
}
@Test
public void startTransformation_fromWrongThread_throwsError() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_AUDIO_ONLY);
HandlerThread anotherThread = new HandlerThread("AnotherThread");
AtomicReference<IllegalStateException> illegalStateException = new AtomicReference<>();
CountDownLatch countDownLatch = new CountDownLatch(1);
anotherThread.start();
new Handler(anotherThread.getLooper())
.post(
() -> {
try {
transformer.startTransformation(mediaItem, outputPath);
} catch (IOException e) {
// Do nothing.
} catch (IllegalStateException e) {
illegalStateException.set(e);
} finally {
countDownLatch.countDown();
}
});
countDownLatch.await();
assertThat(illegalStateException.get()).isNotNull();
}
@Test
public void getProgress_knownDuration_returnsConsistentStates() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_VIDEO_ONLY);
AtomicInteger previousProgressState =
new AtomicInteger(PROGRESS_STATE_WAITING_FOR_AVAILABILITY);
AtomicBoolean foundInconsistentState = new AtomicBoolean();
Handler progressHandler =
new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
@Transformer.ProgressState int progressState = transformer.getProgress(progressHolder);
if (progressState == PROGRESS_STATE_UNAVAILABLE) {
foundInconsistentState.set(true);
return;
}
switch (previousProgressState.get()) {
case PROGRESS_STATE_WAITING_FOR_AVAILABILITY:
break;
case PROGRESS_STATE_AVAILABLE:
if (progressState == PROGRESS_STATE_WAITING_FOR_AVAILABILITY) {
foundInconsistentState.set(true);
return;
}
break;
case PROGRESS_STATE_NO_TRANSFORMATION:
if (progressState != PROGRESS_STATE_NO_TRANSFORMATION) {
foundInconsistentState.set(true);
return;
}
break;
default:
throw new IllegalStateException();
}
previousProgressState.set(progressState);
sendEmptyMessage(0);
}
};
transformer.startTransformation(mediaItem, outputPath);
progressHandler.sendEmptyMessage(0);
TransformerTestRunner.runUntilCompleted(transformer);
assertThat(foundInconsistentState.get()).isFalse();
}
@Test
public void getProgress_knownDuration_givesIncreasingPercentages() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_VIDEO_ONLY);
List<Integer> progresses = new ArrayList<>();
Handler progressHandler =
new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
@Transformer.ProgressState int progressState = transformer.getProgress(progressHolder);
if (progressState == PROGRESS_STATE_NO_TRANSFORMATION) {
return;
}
if (progressState != PROGRESS_STATE_WAITING_FOR_AVAILABILITY
&& (progresses.isEmpty()
|| Iterables.getLast(progresses) != progressHolder.progress)) {
progresses.add(progressHolder.progress);
}
sendEmptyMessage(0);
}
};
transformer.startTransformation(mediaItem, outputPath);
progressHandler.sendEmptyMessage(0);
TransformerTestRunner.runUntilCompleted(transformer);
assertThat(progresses).isInOrder();
if (!progresses.isEmpty()) {
// The progress list could be empty if the transformation ends before any progress can be
// retrieved.
assertThat(progresses.get(0)).isAtLeast(0);
assertThat(Iterables.getLast(progresses)).isLessThan(100);
}
}
@Test
public void getProgress_noCurrentTransformation_returnsNoTransformation() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_VIDEO_ONLY);
@Transformer.ProgressState int stateBeforeTransform = transformer.getProgress(progressHolder);
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
@Transformer.ProgressState int stateAfterTransform = transformer.getProgress(progressHolder);
assertThat(stateBeforeTransform).isEqualTo(Transformer.PROGRESS_STATE_NO_TRANSFORMATION);
assertThat(stateAfterTransform).isEqualTo(Transformer.PROGRESS_STATE_NO_TRANSFORMATION);
}
@Test
public void getProgress_unknownDuration_returnsConsistentStates() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_UNKNOWN_DURATION);
AtomicInteger previousProgressState =
new AtomicInteger(PROGRESS_STATE_WAITING_FOR_AVAILABILITY);
AtomicBoolean foundInconsistentState = new AtomicBoolean();
Handler progressHandler =
new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
@Transformer.ProgressState int progressState = transformer.getProgress(progressHolder);
switch (previousProgressState.get()) {
case PROGRESS_STATE_WAITING_FOR_AVAILABILITY:
break;
case PROGRESS_STATE_UNAVAILABLE:
case PROGRESS_STATE_AVAILABLE: // See [Internal: b/176145097].
if (progressState == PROGRESS_STATE_WAITING_FOR_AVAILABILITY) {
foundInconsistentState.set(true);
return;
}
break;
case PROGRESS_STATE_NO_TRANSFORMATION:
if (progressState != PROGRESS_STATE_NO_TRANSFORMATION) {
foundInconsistentState.set(true);
return;
}
break;
default:
throw new IllegalStateException();
}
previousProgressState.set(progressState);
sendEmptyMessage(0);
}
};
transformer.startTransformation(mediaItem, outputPath);
progressHandler.sendEmptyMessage(0);
TransformerTestRunner.runUntilCompleted(transformer);
assertThat(foundInconsistentState.get()).isFalse();
}
@Test
public void getProgress_fromWrongThread_throwsError() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
HandlerThread anotherThread = new HandlerThread("AnotherThread");
AtomicReference<IllegalStateException> illegalStateException = new AtomicReference<>();
CountDownLatch countDownLatch = new CountDownLatch(1);
anotherThread.start();
new Handler(anotherThread.getLooper())
.post(
() -> {
try {
transformer.getProgress(progressHolder);
} catch (IllegalStateException e) {
illegalStateException.set(e);
} finally {
countDownLatch.countDown();
}
});
countDownLatch.await();
assertThat(illegalStateException.get()).isNotNull();
}
@Test
public void cancel_afterCompletion_doesNotThrow() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
MediaItem mediaItem = MediaItem.fromUri(URI_PREFIX + FILE_VIDEO_ONLY);
transformer.startTransformation(mediaItem, outputPath);
TransformerTestRunner.runUntilCompleted(transformer);
transformer.cancel();
}
@Test
public void cancel_fromWrongThread_throwsError() throws Exception {
Transformer transformer = new Transformer.Builder().setContext(context).setClock(clock).build();
HandlerThread anotherThread = new HandlerThread("AnotherThread");
AtomicReference<IllegalStateException> illegalStateException = new AtomicReference<>();
CountDownLatch countDownLatch = new CountDownLatch(1);
anotherThread.start();
new Handler(anotherThread.getLooper())
.post(
() -> {
try {
transformer.cancel();
} catch (IllegalStateException e) {
illegalStateException.set(e);
} finally {
countDownLatch.countDown();
}
});
countDownLatch.await();
assertThat(illegalStateException.get()).isNotNull();
}
private static void createEncodersAndDecoders() {
ShadowMediaCodec.CodecConfig codecConfig =
new ShadowMediaCodec.CodecConfig(
/* inputBufferSize= */ 10_000,
/* outputBufferSize= */ 10_000,
/* codec= */ (in, out) -> out.put(in));
ShadowMediaCodec.addDecoder(MimeTypes.AUDIO_AAC, codecConfig);
ShadowMediaCodec.addDecoder(MimeTypes.AUDIO_AMR_NB, codecConfig);
ShadowMediaCodec.addEncoder(MimeTypes.AUDIO_AAC, codecConfig);
}
private static void removeEncodersAndDecoders() {
ShadowMediaCodec.clearCodecs();
}
private static String getDumpFileName(String originalFileName) {
return DUMP_FILE_OUTPUT_DIRECTORY + '/' + originalFileName + '.' + DUMP_FILE_EXTENSION;
}
private final class TestMuxerFactory implements Muxer.Factory {
@Override
public Muxer create(String path, String outputMimeType) throws IOException {
testMuxer = new TestMuxer(path, outputMimeType);
return testMuxer;
}
@Override
public Muxer create(ParcelFileDescriptor parcelFileDescriptor, String outputMimeType)
throws IOException {
testMuxer = new TestMuxer("FD:" + parcelFileDescriptor.getFd(), outputMimeType);
return testMuxer;
}
@Override
public boolean supportsOutputMimeType(String mimeType) {
return true;
}
}
}
| apache-2.0 |
motorina0/flowable-engine | modules/flowable-bpmn-converter/src/test/java/org/flowable/editor/language/xml/DataStoreConverterTest.java | 1601 | package org.flowable.editor.language.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.DataStore;
import org.flowable.bpmn.model.DataStoreReference;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.Pool;
import org.junit.Test;
public class DataStoreConverterTest extends AbstractConverterTest {
@Test
public void connvertXMLToModel() throws Exception {
BpmnModel bpmnModel = readXMLFile();
validateModel(bpmnModel);
}
@Test
public void convertModelToXML() throws Exception {
BpmnModel bpmnModel = readXMLFile();
BpmnModel parsedModel = exportAndReadXMLFile(bpmnModel);
validateModel(parsedModel);
}
protected String getResource() {
return "datastore.bpmn";
}
private void validateModel(BpmnModel model) {
assertEquals(1, model.getDataStores().size());
DataStore dataStore = model.getDataStore("DataStore_1");
assertNotNull(dataStore);
assertEquals("DataStore_1", dataStore.getId());
assertEquals("test", dataStore.getDataState());
assertEquals("Test Database", dataStore.getName());
assertEquals("test", dataStore.getItemSubjectRef());
FlowElement refElement = model.getFlowElement("DataStoreReference_1");
assertNotNull(refElement);
assertTrue(refElement instanceof DataStoreReference);
assertEquals(1, model.getPools().size());
Pool pool = model.getPools().get(0);
assertEquals("pool1", pool.getId());
}
}
| apache-2.0 |
pierpal/IBDMUT | SRC/PedMatchProcessor.java | 19314 | /*
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 IBDMUT;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
*
* @author Pier Palamara
*/
class PedMatchProcessor implements Callable<TreeMap<String, Results>> {
private final String pedFile;
private final boolean useExcludeMask;
private final String maskFile;
private final String excludeFile;
private final String matchFile;
private final boolean usePosteriors;
private final double offsetCM;
private final ArrayList<Integer> maxVarCountList;
private final double minLen;
private String posteriorsFile;
private final double posteriorFrom;
private final double posteriorTo;
private final boolean storePosterior;
private final boolean printMutMatchOut;
private final boolean saveBin;
private final String saveBinSuffix;
private final boolean loadBin;
private final boolean writeMutMatchOut;
private final String loadBinSuffix;
private final ArrayList<String> maskFiles;
private static TreeSet<String> onlyIncludeSNPs;
private static boolean useOnlyIncludeSNPs = false;
private static boolean cumulativeMaAFRegression = true;
public static void setCumulativeMaAFRegression(boolean value) throws IOException {
cumulativeMaAFRegression = value;
}
// private final Dataset data;
public static void setOnlyIncludeSNPs(String file) throws IOException {
Tools.printVerboseProgressLevel1("Reading SNP inclusion file " + file);
BufferedReader br = null;
onlyIncludeSNPs = new TreeSet<String>();
useOnlyIncludeSNPs = true;
try {
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException ex) {
Tools.exit("Could not open SNP excusion file " + file);
}
String line = br.readLine();
while (line != null) {
String[] strSplit = line.trim().split("\\s+");
String ID = strSplit[0];
onlyIncludeSNPs.add(ID);
line = br.readLine();
}
Tools.printVerboseProgressLevel1("Read " + onlyIncludeSNPs.size() + " SNPs");
}
public PedMatchProcessor(String pedFile, boolean useMask, boolean useExcludeMask, String maskFile, String excludeFile, String matchFile,
double offsetCM, ArrayList<Integer> maxVarCountList, double minLen, boolean usePosteriors, String posteriorsFile, double posteriorFrom,
double posteriorTo, boolean storePosterior, boolean printMutMatchOut,
boolean saveBin, String saveBinSuffix, boolean loadBin, String loadBinSuffix,
boolean writeMutMatchOut, ArrayList<String> maskFiles) {
this.pedFile = pedFile;
this.useExcludeMask = useExcludeMask;
this.maskFile = maskFile;
this.excludeFile = excludeFile;
this.matchFile = matchFile;
this.offsetCM = offsetCM;
this.maxVarCountList = maxVarCountList;
this.minLen = minLen;
this.usePosteriors = usePosteriors;
this.posteriorsFile = posteriorsFile;
this.posteriorFrom = posteriorFrom;
this.posteriorTo = posteriorTo;
this.storePosterior = storePosterior;
this.printMutMatchOut = printMutMatchOut;
this.saveBin = saveBin;
this.saveBinSuffix = saveBinSuffix;
this.loadBin = loadBin;
this.loadBinSuffix = loadBinSuffix;
this.writeMutMatchOut = writeMutMatchOut;
this.maskFiles = maskFiles;
}
public TreeMap<String, Results> call() throws FileNotFoundException, IOException {
Dataset data = new DataLoader(loadBinSuffix, saveBinSuffix, pedFile, saveBin, loadBin, usePosteriors, posteriorFrom, posteriorTo, storePosterior).call();
TreeMap<String, Results> resultsList = new TreeMap<String, Results>();
for (String maskFile : maskFiles) {
boolean useTrinucleotideContext = (TrinucleotideContext.context != null);
boolean didAlreadyWarnMatchFileHasNoSNPs = false;
for (Integer count : maxVarCountList) {
resultsList.put(maskFile + "\t" + count, new Results(maskFile, count));
}
FileOutputStream MUToutput = null;
Writer MUTwriter = null;
boolean useMask = maskFile.compareToIgnoreCase("") != 0;
if (useMask) {
data.setIncludeMask(new Mask(maskFile, data.getChr()));
}
if (useExcludeMask) {
data.setExcludeMask(new Mask(excludeFile, data.getChr()));
}
Tools.printVerboseProgressLevel1("Reading file " + matchFile);
if (this.writeMutMatchOut) {
File f = new File(maskFile);
String mask = f.getName();
MUToutput = new FileOutputStream(matchFile + "." + mask + ".mut.gz");
MUTwriter = new OutputStreamWriter(new GZIPOutputStream(MUToutput), "UTF-8");
}
BufferedReader br = null;
try {
InputStream fileStream = new FileInputStream(matchFile);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, "UTF-8");
br = new BufferedReader(decoder);
} catch (FileNotFoundException ex) {
Tools.exit("Could not open match file " + matchFile);
} catch (IOException ex) {
Logger.getLogger(PedMatchProcessor.class
.getName()).log(Level.SEVERE, null, ex);
System.exit(
1);
}
// PROCESS MATCH
try {
String line = br.readLine();
while (line != null) {
ArrayList<Double> freqOfMismatchingSNPsOnSegment = new ArrayList<Double>();
ArrayList<String> IDsOfMismatchingSNPsOnSegment = new ArrayList<String>();
String[] strSplit = line.split("\\s+");
String FamID1 = strSplit[0];
String IndID1 = strSplit[1];
String FamID2 = strSplit[2];
String IndID2 = strSplit[3];
String chromosome = strSplit[4];
int fromPos = Integer.parseInt(strSplit[5]);
int toPos = Integer.parseInt(strSplit[6]);
String fromSNP = strSplit[7];
String toSNP = strSplit[8];
double length = Double.parseDouble(strSplit[10]);
String unit = strSplit[11];
if (unit.compareToIgnoreCase("Mb") == 0) {
Tools.warning("Warning: parsed match which is not in cM unit.");
}
if (length < minLen || length - 2 * offsetCM <= 0) {
line = br.readLine();
continue;
}
int mapFrom, mapTo;
try {
mapFrom = data.getIDtoPos().get(fromSNP);
mapTo = data.getIDtoPos().get(toSNP);
} catch (Exception ex) {
if (!didAlreadyWarnMatchFileHasNoSNPs) {
Tools.warning("Warning: Could not find SNPs indicated in match file. Will always find them using physical start/end of segments.");
didAlreadyWarnMatchFileHasNoSNPs = true;
}
fromSNP = (data.getPhysToID().ceilingEntry(fromPos) != null) ? data.getPhysToID().ceilingEntry(fromPos).getValue() : data.getPhysToID().floorEntry(fromPos).getValue();
mapFrom = data.getIDtoPos().get(fromSNP);
toSNP = (data.getPhysToID().floorEntry(toPos) != null) ? data.getPhysToID().floorEntry(toPos).getValue() : data.getPhysToID().ceilingEntry(toPos).getValue();
mapTo = data.getIDtoPos().get(toSNP);
}
Individual ID1 = data.getIndividuals().get(FamID1 + "\t" + IndID1);
Individual ID2 = data.getIndividuals().get(FamID2 + "\t" + IndID2);
TreeMap<Integer, Integer> diffList = new TreeMap<Integer, Integer>();
for (Integer maxVarCount : maxVarCountList) {
diffList.put(maxVarCount, 0);
}
BitSet bitSeq1 = ID1.getBitSeq();
BitSet mask1 = ID1.getMask();
BitSet bitSeq2 = ID2.getBitSeq();
BitSet mask2 = ID2.getMask();
double fromGen = data.getGenPosArray().get(mapFrom);
double toGen = data.getGenPosArray().get(mapTo);
int firstPos = -1;
int inMaskSize = 0;
for (int ind = mapFrom; ind <= mapTo; ind++) {
double distanceFromLeftEdge = data.getGenPosArray().get(ind) - fromGen;
double distanceFromRightEdge = toGen - data.getGenPosArray().get(ind);
if (distanceFromLeftEdge < offsetCM || distanceFromRightEdge < offsetCM) {
continue;
}
if (firstPos == -1) {
firstPos = data.getPhysPos().get(ind);
}
int SNPpos = data.getPhysPos().get(ind);
if ((useExcludeMask && data.getExcludeMask().contains(SNPpos)) || (useMask && !data.getIncludeMask().contains(SNPpos))) {
data.setNotInMask(data.getNotInMask() + 1);
continue;
}
if (useOnlyIncludeSNPs && !onlyIncludeSNPs.contains(data.getPhysToID().get(SNPpos))) {
data.setNotInMask(data.getNotInMask() + 1);
continue;
}
data.setInMask(data.getInMask() + 1);
if (!mask1.get(ind) || !mask2.get(ind)) {
//HANDLE MISSING
} else {
if (bitSeq1.get(ind) != bitSeq2.get(ind)) {
if (data.isHaveFreq() && (printMutMatchOut || writeMutMatchOut)) {
// if they are the same
}
for (int cntInd = 0; cntInd < maxVarCountList.size(); cntInd++) {
int maxVarCount = maxVarCountList.get(cntInd);
Results results = resultsList.get(maskFile + "\t" + maxVarCount);
boolean condition = (!cumulativeMaAFRegression)
? (cntInd != 0)
&& (data.getIDToVarCounts().get(data.getPhysToID().get(SNPpos)) < maxVarCount
&& data.getIDToVarCounts().get(data.getPhysToID().get(SNPpos)) >= maxVarCountList.get(cntInd - 1))
: (data.getIDToVarCounts().get(data.getPhysToID().get(SNPpos)) <= maxVarCount);
if (condition) {
int diff = diffList.get(maxVarCount);
diff++;
if (useTrinucleotideContext) {
Pair<String, String> trinucleotides = TrinucleotideContext.getTrinucleotides(data.getPhysToID().get(SNPpos));
if (trinucleotides != null) {
results.increaseTrinucleotideCounts(trinucleotides.getKey(), trinucleotides.getValue());
}
}
diffList.put(maxVarCount, diff);
double lenRounded = Math.floor(length * 2) / 2.0;
if (data.getVariants().get(ind).isTransition()) {
results.setTransitions(results.getTransitions() + 1);
double val = (results.getTransitionPerCM().containsKey(lenRounded)) ? results.getTransitionPerCM().get(lenRounded) + 1 : 1;
results.getTransitionPerCM().put(lenRounded, val);
} else {
results.setTransversions(results.getTransversions() + 1);
double val = (results.getTransversionPerCM().containsKey(lenRounded)) ? results.getTransversionPerCM().get(lenRounded) + 1 : 1;
results.getTransversionPerCM().put(lenRounded, val);
}
if (data.isHaveFreq()) {
double frq = data.getIDToFreq().get(data.getPhysToID().get(SNPpos));
int frqCounts = 1;
if (results.getFreqCounts().containsKey(frq)) {
frqCounts += results.getFreqCounts().get(frq);
}
results.getFreqCounts().put(frq, frqCounts);
}
}
}
} else {
// if they are different
double frq = data.getIDToFreq().get(data.getPhysToID().get(SNPpos));
IDsOfMismatchingSNPsOnSegment.add(data.getPhysToID().get(SNPpos));
freqOfMismatchingSNPsOnSegment.add(frq);
}
}
}
int exactFromPhys = data.genCoordToPhys(data.getIdToGen().get(fromSNP) + offsetCM);
int exactToPhys = data.genCoordToPhys(data.getIdToGen().get(toSNP) - offsetCM);
inMaskSize = (exactToPhys <= exactFromPhys) ? 0 : (exactToPhys - exactFromPhys);
if (useMask && inMaskSize > 0) {
inMaskSize = data.getIncludeMask().getMaskOverlapWithRegion(exactFromPhys, exactToPhys);
}
if (inMaskSize > 0) {
for (Integer maxVarCount : maxVarCountList) {
int diff = diffList.get(maxVarCount);
Results results = resultsList.get(maskFile + "\t" + maxVarCount);
results.addTotInMask(inMaskSize);
results.setTotalSegmentCount(results.getTotalSegmentCount() + 1);
results.setTotalSegmentLength(results.getTotalSegmentLength() + length);
// TODO here is where it's added. May fix'
results.addHetCount(length, diff, inMaskSize);
StringBuilder additionalInfoString = null;
if (printMutMatchOut || writeMutMatchOut) {
additionalInfoString = new StringBuilder();
for (String k : IDsOfMismatchingSNPsOnSegment) {
additionalInfoString.append(k);
additionalInfoString.append(" ");
}
}
if (printMutMatchOut) {
System.out.println(line + "\t" + diff + "\t" + inMaskSize + "\t" + additionalInfoString.toString());
}
if (writeMutMatchOut) {
MUTwriter.write(line + "\t" + diff + "\t" + inMaskSize + "\t" + maxVarCount + "\t" + additionalInfoString.toString() + "\n");
}
double histBin = (double) Math.round(length * data.getRoundTo()) / data.getRoundTo();
double counts = diff;
data.setTotDiff(data.getTotDiff() + diff);
if (results.getCountsHistogram().containsKey(histBin)) {
counts += results.getCountsHistogram().get(histBin);
}
results.getCountsHistogram().put(histBin, counts);
double inMaskThisSegment = inMaskSize;
data.setTotInMask(data.getTotInMask() + inMaskSize);
if (results.getInMaskHistogram().containsKey(histBin)) {
inMaskThisSegment += results.getInMaskHistogram().get(histBin);
}
results.getInMaskHistogram().put(histBin, inMaskThisSegment);
}
}
line = br.readLine();
}
} catch (IOException ex) {
Tools.exit("Could not read match file " + matchFile);
}
if (this.writeMutMatchOut) {
MUTwriter.flush();
MUTwriter.close();
}
if (useMask) {
Tools.printVerboseProgressLevel2("Finished analyzing file " + pedFile + ". In mask:\t" + data.getInMask() + "\tnot in mask:\t" + data.getNotInMask() + "\tratio:\t" + ((double) data.getInMask()) / data.getNotInMask());
}
}
return resultsList;
}
}
| apache-2.0 |
ctc-g/sinavi-jfw | validation/jfw-validation-core/src/main/java/jp/co/ctc_g/jse/core/validation/constraints/FixedEqualsTo.java | 4791 | /*
* Copyright (c) 2013 ITOCHU Techno-Solutions Corporation.
*
* 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 jp.co.ctc_g.jse.core.validation.constraints;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import jp.co.ctc_g.jse.core.validation.constraints.feature.fixedequalsto.FixedEqualsToValidator;
import jp.co.ctc_g.jse.core.validation.constraints.feature.fixedequalsto.FixedEqualsToValidatorForBigDecimal;
import jp.co.ctc_g.jse.core.validation.constraints.feature.fixedequalsto.FixedEqualsToValidatorForBigInteger;
import jp.co.ctc_g.jse.core.validation.constraints.feature.fixedequalsto.FixedEqualsToValidatorForDate;
import jp.co.ctc_g.jse.core.validation.constraints.feature.fixedequalsto.FixedEqualsToValidatorForDouble;
import jp.co.ctc_g.jse.core.validation.constraints.feature.fixedequalsto.FixedEqualsToValidatorForFloat;
import jp.co.ctc_g.jse.core.validation.constraints.feature.fixedequalsto.FixedEqualsToValidatorForInteger;
import jp.co.ctc_g.jse.core.validation.constraints.feature.fixedequalsto.FixedEqualsToValidatorForLong;
/**
* <p>
* このバリデータ注釈は、プロパティと指定された値との等価性を検証します。
* </p>
* <h4>概要</h4>
* <p>
* このバリデータが等価性を検証する際には、{@link Object#equals(Object)} メソッドを利用します。
* </p>
* <p>サポートしているタイプ:</p>
* <ul>
* <li>{@link java.lang.CharSequence}</li>
* <li>{@link java.util.Date}</li>
* <li>{@link java.math.BigDecimal}</li>
* <li>{@link java.math.BigInteger}</li>
* <li>{@link java.lang.Double}</li>
* <li>{@link java.lang.Float}</li>
* <li>{@link java.lang.Integer}</li>
* <li>{@link java.lang.Long}</li>
* </ul>
* <h4>利用方法</h4>
* <p>
* 使用例は下記の通りです。
* </p>
* <pre class="brush:java">
* public class Domain {
*
* @FixedEqualsTo("12345")
* private String value;
*
* //@FixedEqualsTo("12345") 読み込み専用メソッドにも付与することができます。
* public String getValue() { return value; }
* public String setValue(String value) { this.value = value; }
* </pre>
* @author ITOCHU Techno-Solutions Corporation.
*/
@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {
FixedEqualsToValidator.class, FixedEqualsToValidatorForDate.class, FixedEqualsToValidatorForBigDecimal.class,
FixedEqualsToValidatorForBigInteger.class, FixedEqualsToValidatorForDouble.class, FixedEqualsToValidatorForFloat.class,
FixedEqualsToValidatorForInteger.class, FixedEqualsToValidatorForLong.class
})
public @interface FixedEqualsTo {
/**
* エラーメッセージのキーを指定します。
*/
String message() default "{jp.co.ctc_g.jse.core.validation.constraints.FixedEqualsTo.message}";
/**
* 検証グループを指定します。
*/
Class<?>[] groups() default {};
/**
* ペイロードを指定します。
* デフォルトの検証プロセスでは利用されません。
*/
Class<? extends Payload>[] payload() default {};
/**
* 比較対象の値を文字列で指定します。
*/
String value();
/**
* 日付の書式を指定します。
* {@link java.text.SimpleDateFormat}の日付/時刻パターンで指定します。
* この属性値はプロパティの型が{@link java.util.Date}のときにのみ有効になります。
*/
String datePattern() default "yyyy/MM/dd";
/**
* {@link FixedEqualsTo}の配列を指定します。
* この制約を複数指定したい場合に利用します。
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Documented
@interface List {
FixedEqualsTo[] value();
}
} | apache-2.0 |
Sewmi/test-results-manager | src/main/java/org/wso2/qa/testlink/extension/web/ErrorHandlerServlet.java | 3159 | package org.wso2.qa.testlink.extension.web;
import org.apache.log4j.Logger;
import org.wso2.qa.testlink.extension.model.TestResultsManagerException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* The error handler servlet, which logs the exception properly and sends out the error message.
*/
public class ErrorHandlerServlet extends HttpServlet {
private static final Logger LOGGER = Logger.getLogger(ErrorHandlerServlet.class);
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null){
servletName = "Unknown";
}
String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null){
requestUri = "Unknown";
}
String responsePayload = null;
String errorMessage = String.format("Error occurred while serving the request.\n\tStatus Code : '%d'\n\tServlet Name : '%s'" +
"\n\tRequest URI : '%s'", statusCode, servletName, requestUri);
// If the immediate cause is a TestResultsManagerException, the log message and the response payload should be
// based on whether the error is a runtime error or not.
// Runtime errors are not logged in this class since they should be logged where they originated and
// the response payload should contain any 'Exception' related info.
if(throwable instanceof TestResultsManagerException){
TestResultsManagerException testResultsManagerException = (TestResultsManagerException) throwable;
if(!testResultsManagerException.isRuntimeError()){
responsePayload = String.format("{\"reason\":\"%s\", \"exceptionClass\":\"%s\"}",
throwable.getMessage(), throwable.getCause().getClass().getName());
LOGGER.error(errorMessage, throwable);
}else{
responsePayload = String.format("{\"reason\":\"%s\"}", testResultsManagerException.getMessage());
}
}else{
responsePayload = String.format("{\"reason\":\"%s\", \"exceptionClass\":\"%s\"}",
throwable.getMessage(), throwable.getClass().getName());
LOGGER.error(errorMessage, throwable);
}
// Set response content type
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println(responsePayload);
}
}
| apache-2.0 |
geecodemonkeys/jscompiler | src/main/java/jscompiler/ast/ASTPostfixExpression.java | 827 | package jscompiler.ast;
import jscompiler.ast.visitor.ASTVisitor;
import jscompiler.token.TokenType;
public class ASTPostfixExpression extends ASTExpression {
private TokenType opType;
private ASTExpression expression;
public ASTPostfixExpression(TokenType opType, ASTExpression expr) {
this.setOpType(opType);
this.expression = expr;
}
public TokenType getOpType() {
return opType;
}
public void setOpType(TokenType opType) {
this.opType = opType;
}
public ASTExpression getExpression() {
return expression;
}
public void setExpression(ASTExpression expression) {
this.expression = expression;
}
@Override
public void accept(ASTVisitor visitor) {
if (!visitor.visit(this)) {
return;
}
if (expression != null) {
expression.accept(visitor);
}
visitor.endVisit(this);
}
}
| apache-2.0 |
priimak/cloudkeeper | cloudkeeper-core/cloudkeeper-marshaling/src/main/java/com/svbio/cloudkeeper/marshaling/MarshalingTreeUnmarshalSource.java | 6905 | package com.svbio.cloudkeeper.marshaling;
import cloudkeeper.types.ByteSequence;
import com.svbio.cloudkeeper.marshaling.MarshalingTreeNode.ByteSequenceNode;
import com.svbio.cloudkeeper.marshaling.MarshalingTreeNode.MarshaledObjectNode;
import com.svbio.cloudkeeper.marshaling.MarshalingTreeNode.MarshaledReplacementObjectNode;
import com.svbio.cloudkeeper.marshaling.MarshalingTreeNode.ObjectNode;
import com.svbio.cloudkeeper.marshaling.MarshalingTreeNode.RawObjectNode;
import com.svbio.cloudkeeper.model.api.Marshaler;
import com.svbio.cloudkeeper.model.api.MarshalingException;
import com.svbio.cloudkeeper.model.immutable.element.Key;
import com.svbio.cloudkeeper.model.immutable.element.NoKey;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Objects;
/**
* This class exposes a marshaling tree as unmarshal source.
*
* <p>Instance of this class are shallow immutable.
*/
public abstract class MarshalingTreeUnmarshalSource implements UnmarshalSource {
private MarshalingTreeUnmarshalSource() { }
/**
* Creates a new unmarshal source from the given marshaling tree.
*
* @param tree marshaling tree
* @return the new unmarshal source
*/
public static MarshalingTreeUnmarshalSource create(ObjectNode tree) {
Objects.requireNonNull(tree);
@Nullable MarshalingTreeUnmarshalSource unmarshalSource = tree.accept(CreateInstanceVisitor.INSTANCE, null);
assert unmarshalSource != null;
return unmarshalSource;
}
/**
* Unmarshals an object from the given source.
*
* <p>This method is equivalent to creating an unmarshal source using {@link #create(ObjectNode)} and then calling
* {@link DelegatingUnmarshalContext#unmarshal(UnmarshalSource, ClassLoader)}.
*
* @param tree marshaling tree
* @param classLoader class loader to be returned by
* {@link com.svbio.cloudkeeper.model.api.UnmarshalContext#getClassLoader()}
* @return the object
* @throws MarshalingException if a deserialization error occurs
* @throws IOException if an I/O error occurs
*/
public static Object unmarshal(ObjectNode tree, ClassLoader classLoader) throws IOException {
Objects.requireNonNull(tree);
Objects.requireNonNull(classLoader);
UnmarshalSource unmarshalSource = create(tree);
return DelegatingUnmarshalContext.unmarshal(unmarshalSource, classLoader);
}
@Nullable
@Override
public Object getObject() {
return null;
}
@Nullable
abstract MarshalingTreeNode getChild(Key key);
@Nullable
@Override
public final ByteSequence getByteSequence(Key key) throws MarshalingException {
@Nullable MarshalingTreeNode child = getChild(key);
if (child instanceof ByteSequenceNode) {
return ((ByteSequenceNode) child).getByteSequence();
} else if (child != null) {
throw new MarshalingException(String.format(
"Expected byte-sequence node for key '%s', but got object node.", key
));
} else {
return null;
}
}
@Nullable
@Override
public final UnmarshalSource resolve(Key key) throws MarshalingException {
@Nullable MarshalingTreeNode child = getChild(key);
if (child instanceof ObjectNode) {
@Nullable UnmarshalSource childUnmarshalSource = child.accept(CreateInstanceVisitor.INSTANCE, null);
assert childUnmarshalSource != null;
return childUnmarshalSource;
} else if (child != null) {
throw new MarshalingException(String.format(
"Expected object node for key '%s', but got byte-sequence node.", key
));
} else {
return null;
}
}
private static final class ObjectNodeUnmarshalSource extends MarshalingTreeUnmarshalSource {
private final RawObjectNode node;
private ObjectNodeUnmarshalSource(RawObjectNode node) {
this.node = node;
}
private static UnsupportedOperationException fail() {
return new UnsupportedOperationException(
"Impossible operation for unmarshal source that represents raw-object node."
);
}
@Override
public Marshaler<?> getMarshaler() {
throw fail();
}
@Nullable
@Override
public Object getObject() {
return node.getObject();
}
@Override
MarshalingTreeNode getChild(Key key) {
throw fail();
}
}
private static final class MarshaledObjectUnmarshalSource extends MarshalingTreeUnmarshalSource {
private final MarshaledObjectNode node;
private MarshaledObjectUnmarshalSource(MarshaledObjectNode node) {
this.node = node;
}
@Override
public Marshaler<?> getMarshaler() {
return node.getMarshaler();
}
@Nullable
@Override
MarshalingTreeNode getChild(Key key) {
return node.getChildren().get(key);
}
}
private static final class MarshaledReplacementObjectUnmarshalSource extends MarshalingTreeUnmarshalSource {
private final MarshaledReplacementObjectNode node;
private MarshaledReplacementObjectUnmarshalSource(MarshaledReplacementObjectNode node) {
this.node = node;
}
@Override
public Marshaler<?> getMarshaler() {
return node.getMarshaler();
}
@Nullable
@Override
MarshalingTreeNode getChild(Key key) {
return key instanceof NoKey
? node.getChild()
: null;
}
}
private enum CreateInstanceVisitor implements MarshalingTreeNodeVisitor<MarshalingTreeUnmarshalSource, Void> {
INSTANCE;
@Override
public ObjectNodeUnmarshalSource visitRawObjectNode(RawObjectNode node, @Nullable Void ignored) {
return new ObjectNodeUnmarshalSource(node);
}
@Override
public MarshaledObjectUnmarshalSource visitMarshaledObjectNode(MarshaledObjectNode node,
@Nullable Void ignored) {
return new MarshaledObjectUnmarshalSource(node);
}
@Nullable
@Override
public MarshalingTreeUnmarshalSource visitMarshaledReplacementNode(MarshaledReplacementObjectNode node,
@Nullable Void ignored) {
return new MarshaledReplacementObjectUnmarshalSource(node);
}
@Nullable
@Override
public MarshalingTreeUnmarshalSource visitByteSequenceNode(ByteSequenceNode node, @Nullable Void ignored) {
// Cannot happen.
throw new IllegalStateException("Cannot create UnmarshalSource for byte-sequence node.");
}
}
}
| apache-2.0 |
Radlermo/Monikajava_pft | Sandbox/src/main/java/pl/stqa/pft/sandbox/Primes.java | 1984 | package pl.stqa.pft.sandbox;
/* test czy liczba jest liczba pierwsza*/
public class Primes {
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
/* liczba pierwsza to taka która dzieli się przez jeden i przez samą siebie.
int i=2 - licznik zaczyna się od 2
i<n; wskazujemy miejsce gdzie licznik powinien się zatrzymać
i= i+1 lub i+=1 lub i++ - zmienna licznika na każdej iteracji cyklu*/
/* ciało cyklu czyli działania które powinny się odbywać w każdej iteracji*/
if (n % i == 0) { /* jeżeli reszta z dzielenia n/i =0 to oznacza liczba n nie jest pierwsza*/
return false;
}
}
return true;
}
/* bardziej optymalny test niż powyżej */
public static boolean isPrimeFast(int n) {
for (int i = 2; i < n/2; i++) {
if (n % i == 0) { /* jeżeli reszta z dzielenia n/i =0 to oznacza liczba n nie jest pierwsza*/
return false;
}
}
return true;
}
/* jeszcze szybsza funkcja */
public static boolean isPrimeFast2(int n) {
int m = (int) Math.sqrt(n);
for (int i = 2; i < m; i++) {
if (n % i == 0) { /* jeżeli reszta z dzielenia n/i =0 to oznacza liczba n nie jest pierwsza*/
return false;
}
}
return true;
}
public static boolean isPrimeWhile(int n) {
int i = 2;
while (i < n) {
if (n % i == 0) { /* jeżeli reszta z dzielenia n/i =0 to oznacza liczba n nie jest pierwsza*/
return false;
}
i++; /* cykl */
}
return true;
}
public static boolean isPrimeWhile2(int n) {
int i = 2;
while (i < n && n % i != 0) {
i++; /* kolejne liczby cyklu */
}
return i == n;
}
public static boolean isPrime(long n) {
for (long i = 2; i < n; i++) {
if (n % i == 0) { /* jeżeli reszta z dzielenia n/i =0 to oznacza liczba n nie jest pierwsza*/
return false;
}
}
return true;
}
}
| apache-2.0 |
levymoreira/griffon | subprojects/griffon-core/src/main/java/griffon/core/package-info.java | 699 | /*
* Copyright 2008-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.
*/
/**
* Core application classes.
*
* @since 2.0.0
*/
package griffon.core;
| apache-2.0 |
rgoldberg/guava | guava/src/com/google/common/collect/MoreCollectors.java | 5156 | /*
* Copyright (C) 2016 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Collector;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Collectors not present in {@code java.util.stream.Collectors} that are not otherwise associated
* with a {@code com.google.common} type.
*
* @author Louis Wasserman
* @since 21.0
*/
@Beta
@GwtCompatible
public final class MoreCollectors {
/*
* TODO(lowasser): figure out if we can convert this to a concurrent AtomicReference-based
* collector without breaking j2cl?
*/
private static final Collector<Object, ?, Optional<Object>> TO_OPTIONAL =
Collector.of(
ToOptionalState::new,
ToOptionalState::add,
ToOptionalState::combine,
ToOptionalState::getOptional,
Collector.Characteristics.UNORDERED);
/**
* A collector that converts a stream of zero or one elements to an {@code Optional}. The returned
* collector throws an {@code IllegalArgumentException} if the stream consists of two or more
* elements, and a {@code NullPointerException} if the stream consists of exactly one element,
* which is null.
*/
@SuppressWarnings("unchecked")
public static <T> Collector<T, ?, Optional<T>> toOptional() {
return (Collector) TO_OPTIONAL;
}
private static final Object NULL_PLACEHOLDER = new Object();
private static final Collector<Object, ?, Object> ONLY_ELEMENT =
Collector.of(
ToOptionalState::new,
(state, o) -> state.add((o == null) ? NULL_PLACEHOLDER : o),
ToOptionalState::combine,
state -> {
Object result = state.getElement();
return (result == NULL_PLACEHOLDER) ? null : result;
},
Collector.Characteristics.UNORDERED);
/**
* A collector that takes a stream containing exactly one element and returns that element. The
* returned collector throws an {@code IllegalArgumentException} if the stream consists of two or
* more elements, and a {@code NoSuchElementException} if the stream is empty.
*/
@SuppressWarnings("unchecked")
public static <T> Collector<T, ?, T> onlyElement() {
return (Collector) ONLY_ELEMENT;
}
/**
* This atrocity is here to let us report several of the elements in the stream if there were more
* than one, not just two.
*/
private static final class ToOptionalState {
static final int MAX_EXTRAS = 4;
@Nullable Object element;
@Nullable List<Object> extras;
ToOptionalState() {
element = null;
extras = null;
}
IllegalArgumentException multiples(boolean overflow) {
StringBuilder sb =
new StringBuilder().append("expected one element but was: <").append(element);
for (Object o : extras) {
sb.append(", ").append(o);
}
if (overflow) {
sb.append(", ...");
}
sb.append('>');
throw new IllegalArgumentException(sb.toString());
}
void add(Object o) {
checkNotNull(o);
if (element == null) {
this.element = o;
} else if (extras == null) {
extras = new ArrayList<>(MAX_EXTRAS);
extras.add(o);
} else if (extras.size() < MAX_EXTRAS) {
extras.add(o);
} else {
throw multiples(true);
}
}
ToOptionalState combine(ToOptionalState other) {
if (element == null) {
return other;
} else if (other.element == null) {
return this;
} else {
if (extras == null) {
extras = new ArrayList<>();
}
extras.add(other.element);
if (other.extras != null) {
this.extras.addAll(other.extras);
}
if (extras.size() > MAX_EXTRAS) {
extras.subList(MAX_EXTRAS, extras.size()).clear();
throw multiples(true);
}
return this;
}
}
Optional<Object> getOptional() {
if (extras == null) {
return Optional.ofNullable(element);
} else {
throw multiples(false);
}
}
Object getElement() {
if (element == null) {
throw new NoSuchElementException();
} else if (extras == null) {
return element;
} else {
throw multiples(false);
}
}
}
private MoreCollectors() {}
}
| apache-2.0 |
Kevin-Stark/SlidingMenu | slidingmenu/src/main/java/com/kevin/slidingmenu/MenuInterface.java | 1136 | package com.kevin.slidingmenu;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.View;
public interface MenuInterface {
public abstract void scrollBehindTo(int x, int y,
CustomViewBehind cvb, float scrollScale);
public abstract int getMenuLeft(CustomViewBehind cvb, View content);
public abstract int getAbsLeftBound(CustomViewBehind cvb, View content);
public abstract int getAbsRightBound(CustomViewBehind cvb, View content);
public abstract boolean marginTouchAllowed(View content, int x, int threshold);
public abstract boolean menuOpenTouchAllowed(View content, int currPage, int x);
public abstract boolean menuTouchInQuickReturn(View content, int currPage, int x);
public abstract boolean menuClosedSlideAllowed(int x);
public abstract boolean menuOpenSlideAllowed(int x);
public abstract void drawShadow(Canvas canvas, Drawable shadow, int width);
public abstract void drawFade(Canvas canvas, int alpha,
CustomViewBehind cvb, View content);
public abstract void drawSelector(View content, Canvas canvas, float percentOpen);
}
| apache-2.0 |
teachus/teachus | teachus-frontend/src/main/java/dk/teachus/frontend/components/list/TeachUsSortableDataProvider.java | 2780 | package dk.teachus.frontend.components.list;
import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.lang.Objects;
import org.apache.wicket.util.lang.PropertyResolver;
public abstract class TeachUsSortableDataProvider<O> extends SortableDataProvider<O> {
private static final long serialVersionUID = 1L;
private class DelegatedComparator implements Comparator<O> {
private final SortParam sortParam;
public DelegatedComparator(SortParam sortParam) {
this.sortParam = sortParam;
}
@SuppressWarnings("unchecked")
public int compare(O o1, O o2) {
int compare = 0;
if (o1 != null && o2 != null) {
Comparator foundComparator = null;
for (String sortProperty : comparators.keySet()) {
if (Objects.equal(sortParam.getProperty(), sortProperty)) {
foundComparator = comparators.get(sortProperty);
break;
}
}
if (foundComparator != null) {
Object property1 = PropertyResolver.getValue(sortParam.getProperty(), o1);
Object property2 = PropertyResolver.getValue(sortParam.getProperty(), o2);
compare = foundComparator.compare(property1, property2);
if (sortParam.isAscending() == false) {
compare *= -1;
}
}
} else if (o1 != null) {
compare = -1;
} else if (o2 != null) {
compare = 1;
}
return compare;
}
}
private IModel<List<O>> listModel;
private Map<String, Comparator<?>> comparators;
public TeachUsSortableDataProvider(IModel<List<O>> listModel) {
this.listModel = listModel;
this.comparators = new HashMap<String, Comparator<?>>();
}
public Iterator<O> iterator(int first, int count) {
List<O> sortedList = getSortedList();
int toIndex = first + count;
if (toIndex > sortedList.size())
{
toIndex = sortedList.size();
}
return sortedList.subList(first, toIndex).listIterator();
}
public IModel<O> model(O object) {
return new Model((Serializable) object);
}
public int size() {
return getSortedList().size();
}
protected List<O> getList() {
return listModel.getObject();
}
protected List<O> getSortedList() {
SortParam sortParam = getSort();
List<O> list = getList();
Collections.sort(list, new DelegatedComparator(sortParam));
return list;
}
protected void addComparator(String sortProperty, Comparator<?> comparator) {
comparators.put(sortProperty, comparator);
}
}
| apache-2.0 |
octaware/super-volley | super-volley-library/src/main/java/com/android/supervolley/Utils.java | 20131 | package com.android.supervolley;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.NoSuchElementException;
import okhttp3.ResponseBody;
import okio.Buffer;
final class Utils {
static final Type[] EMPTY_TYPE_ARRAY = new Type[0];
private Utils() {
// No instances.
}
static Class<?> getRawType(Type type) {
if (type == null) throw new NullPointerException("type == null");
if (type instanceof Class<?>) {
// Type is a normal class.
return (Class<?>) type;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
// I'm not exactly sure why getRawType() returns Type instead of Class. Neal isn't either but
// suspects some pathological case related to nested classes exists.
Type rawType = parameterizedType.getRawType();
if (!(rawType instanceof Class)) throw new IllegalArgumentException();
return (Class<?>) rawType;
}
if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
}
if (type instanceof TypeVariable) {
// We could use the variable's bounds, but that won't work if there are multiple. Having a raw
// type that's more general than necessary is okay.
return Object.class;
}
if (type instanceof WildcardType) {
return getRawType(((WildcardType) type).getUpperBounds()[0]);
}
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <" + type + "> is of type " + type.getClass().getName());
}
/**
* Returns true if {@code a} and {@code b} are equal.
*/
static boolean equals(Type a, Type b) {
if (a == b) {
return true; // Also handles (a == null && b == null).
} else if (a instanceof Class) {
return a.equals(b); // Class already specifies equals().
} else if (a instanceof ParameterizedType) {
if (!(b instanceof ParameterizedType)) return false;
ParameterizedType pa = (ParameterizedType) a;
ParameterizedType pb = (ParameterizedType) b;
return equal(pa.getOwnerType(), pb.getOwnerType())
&& pa.getRawType().equals(pb.getRawType())
&& Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());
} else if (a instanceof GenericArrayType) {
if (!(b instanceof GenericArrayType)) return false;
GenericArrayType ga = (GenericArrayType) a;
GenericArrayType gb = (GenericArrayType) b;
return equals(ga.getGenericComponentType(), gb.getGenericComponentType());
} else if (a instanceof WildcardType) {
if (!(b instanceof WildcardType)) return false;
WildcardType wa = (WildcardType) a;
WildcardType wb = (WildcardType) b;
return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
&& Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
} else if (a instanceof TypeVariable) {
if (!(b instanceof TypeVariable)) return false;
TypeVariable<?> va = (TypeVariable<?>) a;
TypeVariable<?> vb = (TypeVariable<?>) b;
return va.getGenericDeclaration() == vb.getGenericDeclaration()
&& va.getName().equals(vb.getName());
} else {
return false; // This isn't a type we support!
}
}
/**
* Returns the generic supertype for {@code supertype}. For example, given a class {@code
* IntegerSet}, the result for when supertype is {@code Set.class} is {@code Set<Integer>} and the
* result when the supertype is {@code Collection.class} is {@code Collection<Integer>}.
*/
static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) {
if (toResolve == rawType) return context;
// We skip searching through interfaces if unknown is an interface.
if (toResolve.isInterface()) {
Class<?>[] interfaces = rawType.getInterfaces();
for (int i = 0, length = interfaces.length; i < length; i++) {
if (interfaces[i] == toResolve) {
return rawType.getGenericInterfaces()[i];
} else if (toResolve.isAssignableFrom(interfaces[i])) {
return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve);
}
}
}
// Check our supertypes.
if (!rawType.isInterface()) {
while (rawType != Object.class) {
Class<?> rawSupertype = rawType.getSuperclass();
if (rawSupertype == toResolve) {
return rawType.getGenericSuperclass();
} else if (toResolve.isAssignableFrom(rawSupertype)) {
return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve);
}
rawType = rawSupertype;
}
}
// We can't resolve this further.
return toResolve;
}
private static int indexOf(Object[] array, Object toFind) {
for (int i = 0; i < array.length; i++) {
if (toFind.equals(array[i])) return i;
}
throw new NoSuchElementException();
}
private static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
static int hashCodeOrZero(Object o) {
return o != null ? o.hashCode() : 0;
}
static String typeToString(Type type) {
return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
}
/**
* Returns the generic form of {@code supertype}. For example, if this is {@code
* ArrayList<String>}, this returns {@code Iterable<String>} given the input {@code
* Iterable.class}.
*
* @param supertype a superclass of, or interface implemented by, this.
*/
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) {
if (!supertype.isAssignableFrom(contextRawType)) throw new IllegalArgumentException();
return resolve(context, contextRawType,
getGenericSupertype(context, contextRawType, supertype));
}
static Type resolve(Type context, Class<?> contextRawType, Type toResolve) {
// This implementation is made a little more complicated in an attempt to avoid object-creation.
while (true) {
if (toResolve instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) toResolve;
toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
if (toResolve == typeVariable) {
return toResolve;
}
} else if (toResolve instanceof Class && ((Class<?>) toResolve).isArray()) {
Class<?> original = (Class<?>) toResolve;
Type componentType = original.getComponentType();
Type newComponentType = resolve(context, contextRawType, componentType);
return componentType == newComponentType ? original : new GenericArrayTypeImpl(
newComponentType);
} else if (toResolve instanceof GenericArrayType) {
GenericArrayType original = (GenericArrayType) toResolve;
Type componentType = original.getGenericComponentType();
Type newComponentType = resolve(context, contextRawType, componentType);
return componentType == newComponentType ? original : new GenericArrayTypeImpl(
newComponentType);
} else if (toResolve instanceof ParameterizedType) {
ParameterizedType original = (ParameterizedType) toResolve;
Type ownerType = original.getOwnerType();
Type newOwnerType = resolve(context, contextRawType, ownerType);
boolean changed = newOwnerType != ownerType;
Type[] args = original.getActualTypeArguments();
for (int t = 0, length = args.length; t < length; t++) {
Type resolvedTypeArgument = resolve(context, contextRawType, args[t]);
if (resolvedTypeArgument != args[t]) {
if (!changed) {
args = args.clone();
changed = true;
}
args[t] = resolvedTypeArgument;
}
}
return changed
? new ParameterizedTypeImpl(newOwnerType, original.getRawType(), args)
: original;
} else if (toResolve instanceof WildcardType) {
WildcardType original = (WildcardType) toResolve;
Type[] originalLowerBound = original.getLowerBounds();
Type[] originalUpperBound = original.getUpperBounds();
if (originalLowerBound.length == 1) {
Type lowerBound = resolve(context, contextRawType, originalLowerBound[0]);
if (lowerBound != originalLowerBound[0]) {
return new WildcardTypeImpl(new Type[]{Object.class}, new Type[]{lowerBound});
}
} else if (originalUpperBound.length == 1) {
Type upperBound = resolve(context, contextRawType, originalUpperBound[0]);
if (upperBound != originalUpperBound[0]) {
return new WildcardTypeImpl(new Type[]{upperBound}, EMPTY_TYPE_ARRAY);
}
}
return original;
} else {
return toResolve;
}
}
}
private static Type resolveTypeVariable(
Type context, Class<?> contextRawType, TypeVariable<?> unknown) {
Class<?> declaredByRaw = declaringClassOf(unknown);
// We can't reduce this further.
if (declaredByRaw == null) return unknown;
Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw);
if (declaredBy instanceof ParameterizedType) {
int index = indexOf(declaredByRaw.getTypeParameters(), unknown);
return ((ParameterizedType) declaredBy).getActualTypeArguments()[index];
}
return unknown;
}
/**
* Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared by
* a class.
*/
private static Class<?> declaringClassOf(TypeVariable<?> typeVariable) {
GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
return genericDeclaration instanceof Class ? (Class<?>) genericDeclaration : null;
}
static void checkNotPrimitive(Type type) {
if (type instanceof Class<?> && ((Class<?>) type).isPrimitive()) {
throw new IllegalArgumentException();
}
}
static <T> T checkNotNull(T object, String message) {
if (object == null) {
throw new NullPointerException(message);
}
return object;
}
/**
* Returns true if {@code annotations} contains an instance of {@code cls}.
*/
static boolean isAnnotationPresent(Annotation[] annotations,
Class<? extends Annotation> cls) {
for (Annotation annotation : annotations) {
if (cls.isInstance(annotation)) {
return true;
}
}
return false;
}
static ResponseBody buffer(final ResponseBody body) throws IOException {
Buffer buffer = new Buffer();
body.source().readAll(buffer);
return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
}
static <T> void validateServiceInterface(Class<T> service) {
if (!service.isInterface()) {
throw new IllegalArgumentException("API declarations must be interfaces.");
}
// Prevent API interfaces from extending other interfaces. This not only avoids a bug in
// Android (http://b.android.com/58753) but it forces composition of API declarations which is
// the recommended pattern.
if (service.getInterfaces().length > 0) {
throw new IllegalArgumentException("API interfaces must not extend other interfaces.");
}
}
static Type getParameterUpperBound(int index, ParameterizedType type) {
Type[] types = type.getActualTypeArguments();
if (index < 0 || index >= types.length) {
throw new IllegalArgumentException(
"Index " + index + " not in range [0," + types.length + ") for " + type);
}
Type paramType = types[index];
if (paramType instanceof WildcardType) {
return ((WildcardType) paramType).getUpperBounds()[0];
}
return paramType;
}
static boolean hasUnresolvableType(Type type) {
if (type instanceof Class<?>) {
return false;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
if (hasUnresolvableType(typeArgument)) {
return true;
}
}
return false;
}
if (type instanceof GenericArrayType) {
return hasUnresolvableType(((GenericArrayType) type).getGenericComponentType());
}
if (type instanceof TypeVariable) {
return true;
}
if (type instanceof WildcardType) {
return true;
}
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <" + type + "> is of type " + className);
}
static Type getCallResponseType(Type returnType) {
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalArgumentException(
"Call return type must be parameterized as Call<Foo> or Call<? extends Foo>");
}
return getParameterUpperBound(0, (ParameterizedType) returnType);
}
private static final class ParameterizedTypeImpl implements ParameterizedType {
private final Type ownerType;
private final Type rawType;
private final Type[] typeArguments;
ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) {
// Require an owner type if the raw type needs it.
if (rawType instanceof Class<?>
&& (ownerType == null) != (((Class<?>) rawType).getEnclosingClass() == null)) {
throw new IllegalArgumentException();
}
this.ownerType = ownerType;
this.rawType = rawType;
this.typeArguments = typeArguments.clone();
for (Type typeArgument : this.typeArguments) {
if (typeArgument == null) throw new NullPointerException();
checkNotPrimitive(typeArgument);
}
}
@Override
public Type[] getActualTypeArguments() {
return typeArguments.clone();
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type getOwnerType() {
return ownerType;
}
@Override
public boolean equals(Object other) {
return other instanceof ParameterizedType && Utils.equals(this, (ParameterizedType) other);
}
@Override
public int hashCode() {
return Arrays.hashCode(typeArguments) ^ rawType.hashCode() ^ hashCodeOrZero(ownerType);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(30 * (typeArguments.length + 1));
result.append(typeToString(rawType));
if (typeArguments.length == 0) return result.toString();
result.append("<").append(typeToString(typeArguments[0]));
for (int i = 1; i < typeArguments.length; i++) {
result.append(", ").append(typeToString(typeArguments[i]));
}
return result.append(">").toString();
}
}
private static final class GenericArrayTypeImpl implements GenericArrayType {
private final Type componentType;
GenericArrayTypeImpl(Type componentType) {
this.componentType = componentType;
}
@Override
public Type getGenericComponentType() {
return componentType;
}
@Override
public boolean equals(Object o) {
return o instanceof GenericArrayType
&& Utils.equals(this, (GenericArrayType) o);
}
@Override
public int hashCode() {
return componentType.hashCode();
}
@Override
public String toString() {
return typeToString(componentType) + "[]";
}
}
/**
* The WildcardType interface supports multiple upper bounds and multiple
* lower bounds. We only support what the Java 6 language needs - at most one
* bound. If a lower bound is set, the upper bound must be Object.class.
*/
private static final class WildcardTypeImpl implements WildcardType {
private final Type upperBound;
private final Type lowerBound;
WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) {
if (lowerBounds.length > 1) throw new IllegalArgumentException();
if (upperBounds.length != 1) throw new IllegalArgumentException();
if (lowerBounds.length == 1) {
if (lowerBounds[0] == null) throw new NullPointerException();
checkNotPrimitive(lowerBounds[0]);
if (upperBounds[0] != Object.class) throw new IllegalArgumentException();
this.lowerBound = lowerBounds[0];
this.upperBound = Object.class;
} else {
if (upperBounds[0] == null) throw new NullPointerException();
checkNotPrimitive(upperBounds[0]);
this.lowerBound = null;
this.upperBound = upperBounds[0];
}
}
@Override
public Type[] getUpperBounds() {
return new Type[]{upperBound};
}
@Override
public Type[] getLowerBounds() {
return lowerBound != null ? new Type[]{lowerBound} : EMPTY_TYPE_ARRAY;
}
@Override
public boolean equals(Object other) {
return other instanceof WildcardType && Utils.equals(this, (WildcardType) other);
}
@Override
public int hashCode() {
// This equals Arrays.hashCode(getLowerBounds()) ^ Arrays.hashCode(getUpperBounds()).
return (lowerBound != null ? 31 + lowerBound.hashCode() : 1) ^ (31 + upperBound.hashCode());
}
@Override
public String toString() {
if (lowerBound != null) return "? super " + typeToString(lowerBound);
if (upperBound == Object.class) return "?";
return "? extends " + typeToString(upperBound);
}
}
}
| apache-2.0 |
k21/buck | src/com/facebook/buck/cxx/toolchain/GnuArchiver.java | 2733 | /*
* Copyright 2015-present Facebook, 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.facebook.buck.cxx.toolchain;
import com.facebook.buck.cxx.toolchain.objectfile.ObjectFileScrubbers;
import com.facebook.buck.io.FileScrubber;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.RuleKeyObjectSink;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.Tool;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
public class GnuArchiver implements Archiver {
private final Tool tool;
public GnuArchiver(Tool tool) {
this.tool = tool;
}
@Override
public ImmutableList<FileScrubber> getScrubbers() {
return ImmutableList.of(
ObjectFileScrubbers.createDateUidGidScrubber(ObjectFileScrubbers.PaddingStyle.LEFT));
}
@Override
public boolean supportsThinArchives() {
return true;
}
@Override
public ImmutableList<String> getArchiveOptions(boolean isThinArchive) {
String options = isThinArchive ? "qcT" : "qc";
return ImmutableList.of(options);
}
@Override
public ImmutableList<String> outputArgs(String outputPath) {
return ImmutableList.of(outputPath);
}
@Override
public boolean isRanLibStepRequired() {
return true;
}
@Override
public ImmutableCollection<BuildRule> getDeps(SourcePathRuleFinder ruleFinder) {
return tool.getDeps(ruleFinder);
}
@Override
public ImmutableCollection<SourcePath> getInputs() {
return tool.getInputs();
}
@Override
public ImmutableList<String> getCommandPrefix(SourcePathResolver resolver) {
return tool.getCommandPrefix(resolver);
}
@Override
public ImmutableMap<String, String> getEnvironment(SourcePathResolver resolver) {
return tool.getEnvironment(resolver);
}
@Override
public void appendToRuleKey(RuleKeyObjectSink sink) {
sink.setReflectively("tool", tool).setReflectively("type", getClass().getSimpleName());
}
@Override
public boolean isArgfileRequired() {
return false;
}
}
| apache-2.0 |
pashkobohdan/GraphicsDrawer | src/library/graphic/settings/WriteFunctionsSettings.java | 4264 | package library.graphic.settings;
import javafx.scene.paint.Color;
import library.function.LagrangePolynomialFunction;
import library.function.PolynomialFunction;
import library.function.RunnableDoubleFunction;
import library.function.StringFunction;
import library.function.settings.FunctionSettings;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
/**
* Created by Bohdan Pashko on 04.04.2016.
*/
@XmlRootElement
public class WriteFunctionsSettings {
private WriteFunction functionF;
private WriteFunction functionG;
public WriteFunctionsSettings() {
}
public static WriteFunctionsSettings getByFunctions(RunnableDoubleFunction functionF, RunnableDoubleFunction functionG) {
WriteFunctionsSettings result = new WriteFunctionsSettings();
if (functionF != null) {
result.setFunctionF(new WriteFunction(functionF.getFunctionSettings().getGraphicColor().toString(), functionF.getType(), functionF.toString()));
}
if (functionG != null) {
result.setFunctionG(new WriteFunction(functionG.getFunctionSettings().getGraphicColor().toString(), functionG.getType(), functionG.toString()));
}
return result;
}
public RunnableDoubleFunction getRunnableFunctionF() {
return getFunction(functionF);
}
public RunnableDoubleFunction getRunnableFunctionG() {
return getFunction(functionG);
}
private RunnableDoubleFunction getFunction(WriteFunction writeFunction) {
RunnableDoubleFunction result;
if (writeFunction == null) {
return null;
}
switch (writeFunction.getTypeOfFunction()) {
case 0:
result = new StringFunction().parseByString(writeFunction.getFunctionString());
result.setFunctionSettings(new FunctionSettings(Color.web(writeFunction.getFunctionColor())));
break;
case 1:
result = new PolynomialFunction().parseByString(writeFunction.getFunctionString());
result.setFunctionSettings(new FunctionSettings(Color.web(writeFunction.getFunctionColor())));
break;
case 2:
result = new LagrangePolynomialFunction().parseByString(writeFunction.getFunctionString());
result.setFunctionSettings(new FunctionSettings(Color.web(writeFunction.getFunctionColor())));
break;
default:
result = null;
}
return result;
}
public static boolean write(String fileName, WriteFunctionsSettings writeFunctionsSettings) {
try {
File selectedFile = new File(fileName);
JAXBContext jaxbContext = JAXBContext.newInstance(WriteFunctionsSettings.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(writeFunctionsSettings, selectedFile);
System.out.println("Write successful !");
} catch (JAXBException e) {
e.printStackTrace();
}
return false;
}
public static WriteFunctionsSettings read(String fileName) {
if (!new File(fileName).exists()) {
return null;
}
try {
JAXBContext jaxbContext = JAXBContext.newInstance(WriteFunctionsSettings.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
WriteFunctionsSettings customer = (WriteFunctionsSettings) jaxbUnmarshaller.unmarshal(new File(fileName));
return customer;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public WriteFunction getFunctionF() {
return functionF;
}
public void setFunctionF(WriteFunction functionF) {
this.functionF = functionF;
}
public WriteFunction getFunctionG() {
return functionG;
}
public void setFunctionG(WriteFunction functionG) {
this.functionG = functionG;
}
}
| apache-2.0 |
trasa/aws-sdk-java | aws-java-sdk-storagegateway/src/main/java/com/amazonaws/services/storagegateway/model/transform/ListTagsForResourceRequestMarshaller.java | 3695 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.storagegateway.model.transform;
import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.storagegateway.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* ListTagsForResourceRequest Marshaller
*/
public class ListTagsForResourceRequestMarshaller
implements
Marshaller<Request<ListTagsForResourceRequest>, ListTagsForResourceRequest> {
public Request<ListTagsForResourceRequest> marshall(
ListTagsForResourceRequest listTagsForResourceRequest) {
if (listTagsForResourceRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<ListTagsForResourceRequest> request = new DefaultRequest<ListTagsForResourceRequest>(
listTagsForResourceRequest, "AWSStorageGateway");
request.addHeader("X-Amz-Target",
"StorageGateway_20130630.ListTagsForResource");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
StringWriter stringWriter = new StringWriter();
JSONWriter jsonWriter = new JSONWriter(stringWriter);
jsonWriter.object();
if (listTagsForResourceRequest.getResourceARN() != null) {
jsonWriter.key("ResourceARN").value(
listTagsForResourceRequest.getResourceARN());
}
if (listTagsForResourceRequest.getMarker() != null) {
jsonWriter.key("Marker").value(
listTagsForResourceRequest.getMarker());
}
if (listTagsForResourceRequest.getLimit() != null) {
jsonWriter.key("Limit").value(
listTagsForResourceRequest.getLimit());
}
jsonWriter.endObject();
String snippet = stringWriter.toString();
byte[] content = snippet.getBytes(UTF8);
request.setContent(new StringInputStream(snippet));
request.addHeader("Content-Length",
Integer.toString(content.length));
request.addHeader("Content-Type", "application/x-amz-json-1.1");
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
| apache-2.0 |
mtaylor/DataBroker | webportal-root/src/main/java/com/arjuna/databroker/webportal/tree/DataServiceTreeNode.java | 1139 | /*
* Copyright (c) 2013-2014, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved.
*/
package com.arjuna.databroker.webportal.tree;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
public class DataServiceTreeNode extends AbstractTreeNode
{
private static final long serialVersionUID = -5713567605573809197L;
private static final String TYPE = "Data Service";
public DataServiceTreeNode()
{
}
public DataServiceTreeNode(Model model, Resource resource)
{
super(model, resource);
}
public String getType()
{
return TYPE;
}
public AbstractTreeNode processSubNodeStatement(Model model, Statement statement)
{
Property producesDataSetProperty = model.getProperty("http://rdfs.arjuna.com/datasource#", "producesDataSet");
if (producesDataSetProperty.equals(statement.getPredicate()))
return new DataSetTreeNode(model, statement.getResource());
else
return null;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-autoscaling/src/main/java/com/amazonaws/services/autoscaling/model/transform/InstanceReusePolicyStaxUnmarshaller.java | 2462 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.autoscaling.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.autoscaling.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* InstanceReusePolicy StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InstanceReusePolicyStaxUnmarshaller implements Unmarshaller<InstanceReusePolicy, StaxUnmarshallerContext> {
public InstanceReusePolicy unmarshall(StaxUnmarshallerContext context) throws Exception {
InstanceReusePolicy instanceReusePolicy = new InstanceReusePolicy();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return instanceReusePolicy;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("ReuseOnScaleIn", targetDepth)) {
instanceReusePolicy.setReuseOnScaleIn(BooleanStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return instanceReusePolicy;
}
}
}
}
private static InstanceReusePolicyStaxUnmarshaller instance;
public static InstanceReusePolicyStaxUnmarshaller getInstance() {
if (instance == null)
instance = new InstanceReusePolicyStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
spring-projects/spring-framework | spring-messaging/src/test/java/org/springframework/messaging/core/CachingDestinationResolverTests.java | 2384 | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.core;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Unit tests for {@link CachingDestinationResolverProxy}.
*
* @author Agim Emruli
* @author Juergen Hoeller
*/
public class CachingDestinationResolverTests {
@Test
public void cachedDestination() {
@SuppressWarnings("unchecked")
DestinationResolver<String> resolver = mock(DestinationResolver.class);
CachingDestinationResolverProxy<String> resolverProxy = new CachingDestinationResolverProxy<>(resolver);
given(resolver.resolveDestination("abcd")).willReturn("dcba");
given(resolver.resolveDestination("1234")).willReturn("4321");
assertThat(resolverProxy.resolveDestination("abcd")).isEqualTo("dcba");
assertThat(resolverProxy.resolveDestination("1234")).isEqualTo("4321");
assertThat(resolverProxy.resolveDestination("1234")).isEqualTo("4321");
assertThat(resolverProxy.resolveDestination("abcd")).isEqualTo("dcba");
verify(resolver, times(1)).resolveDestination("abcd");
verify(resolver, times(1)).resolveDestination("1234");
}
@Test
public void noTargetSet() {
CachingDestinationResolverProxy<String> resolverProxy = new CachingDestinationResolverProxy<>();
assertThatIllegalArgumentException().isThrownBy(
resolverProxy::afterPropertiesSet);
}
@Test
public void nullTargetThroughConstructor() {
assertThatIllegalArgumentException().isThrownBy(() ->
new CachingDestinationResolverProxy<String>(null));
}
}
| apache-2.0 |
xuhaoyang/Weibo | app/src/main/java/com/xhy/weibo/receiver/NetWorkReceiver.java | 407 | package com.xhy.weibo.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.xhy.weibo.utils.HttpNetUtil;
/**
* Created by xuhaoyang on 16/7/20.
*/
public class NetWorkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
HttpNetUtil.setConnected(context);
}
}
| apache-2.0 |
wapalxj/GraduationDesign | GraduationDesign/eIM/src/main/java/csdn/shimiso/eim/manager/UserManager.java | 2128 | package csdn.shimiso.eim.manager;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.packet.VCard;
import android.content.Context;
public class UserManager {
private static UserManager userManager = null;
private UserManager() {
}
public static UserManager getInstance(Context context) {
if (userManager == null) {
userManager = new UserManager();
}
return userManager;
}
/**
*
* 获取用户的vcard信息 .
*
* @return
* @author shimiso
* @update 2013-4-16 下午1:32:03
*/
public VCard getUserVCard(String jid) {
XMPPConnection xmppConn = XmppConnectionManager.getInstance()
.getConnection();
VCard vcard = new VCard();
try {
vcard.load(xmppConn, jid);
} catch (XMPPException e) {
e.printStackTrace();
}
return vcard;
}
/**
*
* 保存用户的vcard信息. 注:修改vcard时,头像会丢失,此处为asmack.jar的bug,目前还无法修复
*
* @param vCard
* @return
* @author shimiso
* @update 2013-4-16 下午2:39:37
*/
public VCard saveUserVCard(VCard vCard) {
XMPPConnection xmppConn = XmppConnectionManager.getInstance()
.getConnection();
try {
vCard.save(xmppConn);
return getUserVCard(vCard.getJabberId());
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
/**
*
* 获取用户头像信息 .
*
* @param connection
* @param jid
* @return
* @author shimiso
* @update 2013-4-16 下午1:31:52
*/
public InputStream getUserImage(String jid) {
XMPPConnection connection = XmppConnectionManager.getInstance()
.getConnection();
InputStream ic = null;
try {
System.out.println("获取用户头像信息: " + jid);
VCard vcard = new VCard();
vcard.load(connection, jid);
if (vcard == null || vcard.getAvatar() == null) {
return null;
}
ByteArrayInputStream bais = new ByteArrayInputStream(
vcard.getAvatar());
return bais;
} catch (Exception e) {
e.printStackTrace();
}
return ic;
}
}
| apache-2.0 |
eggeral/javafx-examples | src/main/java/baylandtag/ag_dummy_person_table/Main.java | 1592 | package baylandtag.ag_dummy_person_table;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
// 1. Example of data table
// 2. Example of tab pane
// 3. MainUi and Controller MainUi has 2 tabs one for login one for baylandtag
// 4. Bind the disabled property of baylandtag tab to database connected property
// 5. Baylandtag UI
// 6. Abgeordneter Table
// 7. Baylandtag Controller
private Database database = new Database();
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Utils.loadDatabaseProperties(database);
LoginUi loginUi = new LoginUi();
LoginController loginController = new LoginController(loginUi);
loginController.initialize();
loginController.setDatabase(database);
BaylandtagUi baylandtagUi = new BaylandtagUi();
BaylandtagController baylandtagController = new BaylandtagController(baylandtagUi);
baylandtagController.initialize();
baylandtagController.setDatabase(database);
MainUi mainUi = new MainUi();
MainController mainController = new MainController(mainUi);
mainController.initialize(); // does nothing but we stay with the pattern for demo purpose.
mainController.setDatabase(database);
mainController.setLoginTabContent(loginUi.create());
mainController.setBaylandtagTabContent(baylandtagUi.create());
Parent root = mainUi.create();
Scene mainScene = new Scene(root);
primaryStage.setScene(mainScene);
primaryStage.show();
}
}
| apache-2.0 |
yeastrc/proxl-web-app | proxl_web_app/src/main/java/org/yeastrc/xlink/www/webservices_data_pages_main_get_data_webservices/protein_and_coverage_pages/Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager.java | 4499 | package org.yeastrc.xlink.www.webservices_data_pages_main_get_data_webservices.protein_and_coverage_pages;
import java.util.List;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.yeastrc.xlink.www.cached_data_in_file.CachedDataInFileMgmt;
import org.yeastrc.xlink.www.cached_data_in_file.CachedDataInFileMgmtRegistration;
import org.yeastrc.xlink.www.cached_data_in_file.CachedDataInFileMgmtRegistrationIF;
import org.yeastrc.xlink.www.cached_data_in_file.CachedDataInFileMgmt.IdParamType;
import org.yeastrc.xlink.www.cached_data_in_file.CachedDataInFileMgmt.ReplaceExistingValue;
/**
*
* Manage Cached results for Protein_AllProteins_MultipleSearches_PageData_Webservice
*
* Cache bytes to Disk File using CachedDataInFileMgmt
*
* Interfaces with the CachedDataInFileMgmt for saving and retrieving the result JSON for caching
*
* Added to CachedDataInFileMgmtRegistration to register it
*
* Singleton
*/
public class Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager implements CachedDataInFileMgmtRegistrationIF {
private static final Logger log = LoggerFactory.getLogger( Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager.class );
private static final String PREFIX_FOR_CACHING = "ProteinsAll_MultipleSearches_PageMainDisplayService_";
static final int VERSION_FOR_CACHING_FROM_MAIN_CLASS = Protein_AllProteins_MultipleSearches_PageData_Webservice.VERSION_FOR_CACHING;
private static final Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager instance = new Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager();
// private constructor
private Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager() {}
/**
* @return Singleton instance
*/
public static Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager getSingletonInstance() {
return instance;
}
public static class Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager_Result {
private byte[] webserviceResponseJSONAsBytes;
public byte[] getWebserviceResponseJSONAsBytes() {
return webserviceResponseJSONAsBytes;
}
public void setWebserviceResponseJSONAsBytes(byte[] webserviceResponseJSONAsBytes) {
this.webserviceResponseJSONAsBytes = webserviceResponseJSONAsBytes;
}
}
/**
* @param projectSearchIds
* @param requestQueryString
* @return
* @throws Exception
*/
public Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager_Result retrieveDataFromCache(
List<Integer> projectSearchIds,
byte[] requestIdentifierBytes ) throws Exception {
if ( ! CachedDataInFileMgmt.getSingletonInstance().isCachedDataFilesDirConfigured() ) {
return null; // EARLY EXIT
}
Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager_Result result = new Protein_AllProteins_MultipleSearches_PageData_Webservice_CachedResultManager_Result();
result.webserviceResponseJSONAsBytes =
CachedDataInFileMgmt.getSingletonInstance().retrieveCachedDataFileContents(
PREFIX_FOR_CACHING /* namePrefix */,
VERSION_FOR_CACHING_FROM_MAIN_CLASS /* version */,
requestIdentifierBytes,
projectSearchIds /* ids */,
IdParamType.PROJECT_SEARCH_ID );
return result;
}
/**
* @param projectSearchIds
* @param webserviceResponseJSONAsBytes
* @param requestQueryString
* @throws Exception
*/
public void saveDataToCache(
List<Integer> projectSearchIds,
byte[] webserviceResponseJSONAsBytes,
byte[] requestIdentifierBytes ) throws Exception {
if ( ! CachedDataInFileMgmt.getSingletonInstance().isCachedDataFilesDirConfigured() ) {
return; // EARLY EXIT
}
CachedDataInFileMgmt.getSingletonInstance().saveCachedDataFileContents(
webserviceResponseJSONAsBytes,
ReplaceExistingValue.NO,
PREFIX_FOR_CACHING /* namePrefix */,
VERSION_FOR_CACHING_FROM_MAIN_CLASS /* version */,
requestIdentifierBytes,
projectSearchIds /* ids */,
IdParamType.PROJECT_SEARCH_ID );
}
/*
* Called from CachedDataInFileMgmtRegistration
*
* Register all prefixes and version used with CachedDataInFileMgmt
*/
@Override
public void register() throws Exception {
// Register for Both
{
CachedDataInFileMgmtRegistration.getSingletonInstance()
.register( PREFIX_FOR_CACHING, VERSION_FOR_CACHING_FROM_MAIN_CLASS );
}
}
}
| apache-2.0 |
cdancy/artifactory-rest | src/test/java/com/cdancy/artifactory/rest/BaseArtifactoryMockTest.java | 3448 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cdancy.artifactory.rest;
import com.cdancy.artifactory.rest.config.ArtifactoryAuthenticationModule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.jclouds.util.Strings2.toStringAndClose;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import java.util.UUID;
import javax.ws.rs.core.HttpHeaders;
import org.jclouds.Constants;
import org.jclouds.ContextBuilder;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
/**
* Base class for all Artifactory mock tests.
*/
public class BaseArtifactoryMockTest {
protected String provider;
public BaseArtifactoryMockTest() {
provider = "artifactory";
}
public ArtifactoryApi api(URL url) {
final ArtifactoryAuthentication creds = ArtifactoryAuthentication
.builder()
.credentials("hello:world")
.build();
final ArtifactoryAuthenticationModule credsModule = new ArtifactoryAuthenticationModule(creds);
return ContextBuilder.newBuilder(provider)
.endpoint(url.toString())
.overrides(setupProperties())
.modules(Lists.newArrayList(credsModule))
.buildApi(ArtifactoryApi.class);
}
protected Properties setupProperties() {
Properties properties = new Properties();
properties.setProperty(Constants.PROPERTY_MAX_RETRIES, "0");
return properties;
}
public static MockWebServer mockArtifactoryJavaWebServer() throws IOException {
MockWebServer server = new MockWebServer();
server.start();
return server;
}
public String randomString() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
public String payloadFromResource(String resource) {
try {
return new String(toStringAndClose(getClass().getResourceAsStream(resource)).getBytes(Charsets.UTF_8));
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
protected RecordedRequest assertSent(MockWebServer server, String method, String path, String mediaType) throws InterruptedException {
RecordedRequest request = server.takeRequest();
assertThat(request.getMethod()).isEqualTo(method);
assertThat(request.getPath()).isEqualTo(path);
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(mediaType);
return request;
}
}
| apache-2.0 |
atlasapi/atlas-deer | atlas-core/src/main/java/org/atlasapi/criteria/attribute/IntegerAttribute.java | 1233 | package org.atlasapi.criteria.attribute;
import org.atlasapi.criteria.AttributeQuery;
import org.atlasapi.criteria.IntegerAttributeQuery;
import org.atlasapi.criteria.operator.ComparableOperator;
import org.atlasapi.criteria.operator.Operator;
import org.atlasapi.entity.Identified;
public class IntegerAttribute extends Attribute<Integer> {
private IntegerAttribute(
String name,
Class<? extends Identified> target,
boolean isCollection
) {
super(name, target, isCollection);
}
public static IntegerAttribute list(
String name,
Class<? extends Identified> target
) {
return new IntegerAttribute(name, target, true);
}
@Override
public String toString() {
return "Integer valued attribute: " + name;
}
@Override
public AttributeQuery<Integer> createQuery(Operator op, Iterable<Integer> values) {
if (!(op instanceof ComparableOperator)) {
throw new IllegalArgumentException();
}
return new IntegerAttributeQuery(this, (ComparableOperator) op, values);
}
@Override
public Class<Integer> requiresOperandOfType() {
return Integer.class;
}
}
| apache-2.0 |
StanislavEsin/estanislav | chess_board/src/main/java/ru/job4j/board/Cell.java | 1239 | package ru.job4j.board;
/**
* Cell - ячейка шахматной доски.
*
* @author Stanislav (376825@mail.ru)
* @version $Id$
* @since 1.0
*/
public class Cell {
/**
*/
private int positionX;
/**
*/
private int positionY;
/**
* @see
* @param positionX - int.
* @param positionY - int.
*/
public Cell(int positionX, int positionY) {
this.positionX = positionX;
this.positionY = positionY;
}
/**
* getPositionX.
* @return int.
*/
public int getPositionX() {
return positionX;
}
/**
* getPositionY.
* @return int.
*/
public int getPositionY() {
return positionY;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Cell cell = (Cell) o;
if (positionX != cell.positionX) {
return false;
}
return positionY == cell.positionY;
}
@Override
public int hashCode() {
int result = positionX;
result = 31 * result + positionY;
return result;
}
} | apache-2.0 |
mhurne/aws-sdk-java | aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53domains/model/transform/TransferDomainRequestMarshaller.java | 6594 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.route53domains.model.transform;
import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.route53domains.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* TransferDomainRequest Marshaller
*/
public class TransferDomainRequestMarshaller implements
Marshaller<Request<TransferDomainRequest>, TransferDomainRequest> {
public Request<TransferDomainRequest> marshall(
TransferDomainRequest transferDomainRequest) {
if (transferDomainRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<TransferDomainRequest> request = new DefaultRequest<TransferDomainRequest>(
transferDomainRequest, "AmazonRoute53Domains");
request.addHeader("X-Amz-Target",
"Route53Domains_v20140515.TransferDomain");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
final StructuredJsonGenerator jsonGenerator = SdkJsonProtocolFactory
.createWriter(false, "1.1");
jsonGenerator.writeStartObject();
if (transferDomainRequest.getDomainName() != null) {
jsonGenerator.writeFieldName("DomainName").writeValue(
transferDomainRequest.getDomainName());
}
if (transferDomainRequest.getIdnLangCode() != null) {
jsonGenerator.writeFieldName("IdnLangCode").writeValue(
transferDomainRequest.getIdnLangCode());
}
if (transferDomainRequest.getDurationInYears() != null) {
jsonGenerator.writeFieldName("DurationInYears").writeValue(
transferDomainRequest.getDurationInYears());
}
com.amazonaws.internal.SdkInternalList<Nameserver> nameserversList = (com.amazonaws.internal.SdkInternalList<Nameserver>) transferDomainRequest
.getNameservers();
if (!nameserversList.isEmpty()
|| !nameserversList.isAutoConstruct()) {
jsonGenerator.writeFieldName("Nameservers");
jsonGenerator.writeStartArray();
for (Nameserver nameserversListValue : nameserversList) {
if (nameserversListValue != null) {
NameserverJsonMarshaller.getInstance().marshall(
nameserversListValue, jsonGenerator);
}
}
jsonGenerator.writeEndArray();
}
if (transferDomainRequest.getAuthCode() != null) {
jsonGenerator.writeFieldName("AuthCode").writeValue(
transferDomainRequest.getAuthCode());
}
if (transferDomainRequest.getAutoRenew() != null) {
jsonGenerator.writeFieldName("AutoRenew").writeValue(
transferDomainRequest.getAutoRenew());
}
if (transferDomainRequest.getAdminContact() != null) {
jsonGenerator.writeFieldName("AdminContact");
ContactDetailJsonMarshaller.getInstance().marshall(
transferDomainRequest.getAdminContact(), jsonGenerator);
}
if (transferDomainRequest.getRegistrantContact() != null) {
jsonGenerator.writeFieldName("RegistrantContact");
ContactDetailJsonMarshaller.getInstance().marshall(
transferDomainRequest.getRegistrantContact(),
jsonGenerator);
}
if (transferDomainRequest.getTechContact() != null) {
jsonGenerator.writeFieldName("TechContact");
ContactDetailJsonMarshaller.getInstance().marshall(
transferDomainRequest.getTechContact(), jsonGenerator);
}
if (transferDomainRequest.getPrivacyProtectAdminContact() != null) {
jsonGenerator.writeFieldName("PrivacyProtectAdminContact")
.writeValue(
transferDomainRequest
.getPrivacyProtectAdminContact());
}
if (transferDomainRequest.getPrivacyProtectRegistrantContact() != null) {
jsonGenerator.writeFieldName("PrivacyProtectRegistrantContact")
.writeValue(
transferDomainRequest
.getPrivacyProtectRegistrantContact());
}
if (transferDomainRequest.getPrivacyProtectTechContact() != null) {
jsonGenerator.writeFieldName("PrivacyProtectTechContact")
.writeValue(
transferDomainRequest
.getPrivacyProtectTechContact());
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length",
Integer.toString(content.length));
request.addHeader("Content-Type", jsonGenerator.getContentType());
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
| apache-2.0 |
consulo/consulo-android | android/android/src/org/jetbrains/android/dom/drawable/ListItemBase.java | 1356 | package org.jetbrains.android.dom.drawable;
import com.intellij.util.xml.Convert;
import org.jetbrains.android.dom.AndroidAttributeValue;
import org.jetbrains.android.dom.AndroidResourceType;
import org.jetbrains.android.dom.converters.ResourceReferenceConverter;
import org.jetbrains.android.dom.resources.ResourceValue;
import java.util.List;
/**
* @author Eugene.Kudelevsky
*/
public interface ListItemBase extends DrawableDomElement {
@Convert(ResourceReferenceConverter.class)
@AndroidResourceType("drawable")
AndroidAttributeValue<ResourceValue> getDrawable();
// See android.graphics.drawable.Drawable.createFromXmlInner
List<DrawableSelector> getSelectors();
List<AnimatedStateListTransition> getAnimatedSelectors();
List<LevelList> getLevelLists();
List<LayerList> getLayerLists();
List<LayerList> getTransitions();
List<Ripple> getRipples(); // API 21
List<ColorDrawable> getColors();
List<Shape> getShapes();
// Being considered:
//List<Vector> getVectors();
List<InsetOrClipOrScale> getScales();
List<InsetOrClipOrScale> getClips();
List<InsetOrClipOrScale> getRotates();
List<InsetOrClipOrScale> getAnimatedRotates();
List<AnimationList> getAnimationLists();
List<InsetOrClipOrScale> getInsets();
List<BitmapOrNinePatchElement> getBitmaps();
List<BitmapOrNinePatchElement> getNinePatches();
}
| apache-2.0 |
Sage-Bionetworks/Synapse-Repository-Services | services/repository-managers/src/test/java/org/sagebionetworks/repo/manager/file/scanner/WikiAttachmentFileScannerIntegrationTest.java | 4020 | package org.sagebionetworks.repo.manager.file.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.sagebionetworks.repo.manager.UserManager;
import org.sagebionetworks.repo.manager.file.FileHandleAssociationManager;
import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL;
import org.sagebionetworks.repo.model.dbo.file.FileHandleDao;
import org.sagebionetworks.repo.model.IdRange;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.file.FileHandleAssociateType;
import org.sagebionetworks.repo.model.v2.dao.V2WikiPageDao;
import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class WikiAttachmentFileScannerIntegrationTest {
@Autowired
private FileHandleDao fileHandleDao;
@Autowired
private UserManager userManager;
@Autowired
private V2WikiPageDao wikiDao;
@Autowired
private FileHandleAssociationScannerTestUtils utils;
@Autowired
private FileHandleAssociationManager manager;
private FileHandleAssociateType associationType = FileHandleAssociateType.WikiAttachment;
private UserInfo user;
@BeforeEach
public void before() {
wikiDao.truncateAll();
fileHandleDao.truncateTable();
user = userManager.getUserInfo(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId());
}
@AfterEach
public void after() {
wikiDao.truncateAll();
fileHandleDao.truncateTable();
}
@Test
public void testScanner() {
List<V2WikiPage> wikiPages = new ArrayList<>();
wikiPages.add(createWikiMarkdown("123", 1));
wikiPages.add(createWikiMarkdown("456", 0));
wikiPages.add(createWikiMarkdown("789", 2));
List<ScannedFileHandleAssociation> expected = new ArrayList<>();
for (V2WikiPage wiki : wikiPages) {
for (String fileHandleId : wiki.getAttachmentFileHandleIds()) {
expected.add(new ScannedFileHandleAssociation(Long.valueOf(wiki.getId()), Long.valueOf(fileHandleId)));
}
}
IdRange range = manager.getIdRange(associationType);
// Call under test
List<ScannedFileHandleAssociation> result = StreamSupport.stream(
manager.scanRange(associationType, range).spliterator(), false
).collect(Collectors.toList());
assertEquals(expected, result);
}
private V2WikiPage createWikiMarkdown(String ownerId, int attachmentNum) {
V2WikiPage wikiPage = new V2WikiPage();
wikiPage.setCreatedBy(user.getId().toString());
wikiPage.setModifiedBy(user.getId().toString());
wikiPage.setMarkdownFileHandleId(utils.generateFileHandle(user));
List<String> attachments = IntStream.range(0, attachmentNum).boxed().map(i-> utils.generateFileHandle(user)).collect(Collectors.toList());
wikiPage.setAttachmentFileHandleIds(attachments);
wikiPage = wikiDao.create(wikiPage, Collections.emptyMap(), ownerId, ObjectType.ENTITY, attachments);
// Shortcut: the create method above take in input both a map between a file name and its id and the list of attachement ids (why???). Then serialize this to a list in form of a string. When reading a
// wiki page it reads from that list instead of the list of attachment, since we pass an empty map the list is going to be empty. What we are interested in, is just the list of attachments.
wikiPage.setAttachmentFileHandleIds(attachments);
return wikiPage;
}
}
| apache-2.0 |
lollipopjin/incubator-rocketmq | rocketmq-tools/src/main/java/com/alibaba/rocketmq/tools/command/message/QueryMsgByIdSubCommand.java | 10425 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.rocketmq.tools.command.message;
import com.alibaba.rocketmq.client.exception.MQBrokerException;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.UtilAll;
import com.alibaba.rocketmq.common.message.MessageClientExt;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.alibaba.rocketmq.common.protocol.body.ConsumeMessageDirectlyResult;
import com.alibaba.rocketmq.remoting.RPCHook;
import com.alibaba.rocketmq.remoting.common.RemotingHelper;
import com.alibaba.rocketmq.remoting.exception.RemotingException;
import com.alibaba.rocketmq.tools.admin.DefaultMQAdminExt;
import com.alibaba.rocketmq.tools.admin.api.MessageTrack;
import com.alibaba.rocketmq.tools.command.SubCommand;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.lang3.StringUtils;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
/**
* @author shijia.wxr
*/
public class QueryMsgByIdSubCommand implements SubCommand {
@Override
public String commandName() {
return "queryMsgById";
}
@Override
public String commandDesc() {
return "Query Message by Id";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("i", "msgId", true, "Message Id");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("g", "consumerGroup", true, "consumer group name");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("d", "clientId", true, "The consumer's client id");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("s", "sendMessage", true, "resend message");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("u", "unitName", true, "unit name");
opt.setRequired(false);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
DefaultMQProducer defaultMQProducer = new DefaultMQProducer("ReSendMsgById");
defaultMQProducer.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
defaultMQAdminExt.start();
if (commandLine.hasOption('s')) {
if (commandLine.hasOption('u')) {
String unitName = commandLine.getOptionValue('u').trim();
defaultMQProducer.setUnitName(unitName);
}
defaultMQProducer.start();
}
final String msgIds = commandLine.getOptionValue('i').trim();
final String[] msgIdArr = StringUtils.split(msgIds, ",");
if (commandLine.hasOption('g') && commandLine.hasOption('d')) {
final String consumerGroup = commandLine.getOptionValue('g').trim();
final String clientId = commandLine.getOptionValue('d').trim();
for (String msgId : msgIdArr) {
if (StringUtils.isNotBlank(msgId)) {
pushMsg(defaultMQAdminExt, consumerGroup, clientId, msgId.trim());
}
}
} else if (commandLine.hasOption('s')) {
boolean resend = Boolean.parseBoolean(commandLine.getOptionValue('s', "false").trim());
if (resend) {
for (String msgId : msgIdArr) {
if (StringUtils.isNotBlank(msgId)) {
sendMsg(defaultMQAdminExt, defaultMQProducer, msgId.trim());
}
}
}
} else {
for (String msgId : msgIdArr) {
if (StringUtils.isNotBlank(msgId)) {
queryById(defaultMQAdminExt, msgId.trim());
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
defaultMQProducer.shutdown();
defaultMQAdminExt.shutdown();
}
}
private void pushMsg(final DefaultMQAdminExt defaultMQAdminExt, final String consumerGroup, final String clientId, final String msgId) {
try {
ConsumeMessageDirectlyResult result =
defaultMQAdminExt.consumeMessageDirectly(consumerGroup, clientId, msgId);
System.out.printf("%s", result);
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendMsg(final DefaultMQAdminExt defaultMQAdminExt, final DefaultMQProducer defaultMQProducer, final String msgId) throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
try {
MessageExt msg = defaultMQAdminExt.viewMessage(msgId);
if (msg != null) {
// resend msg by id
System.out.printf("prepare resend msg. originalMsgId=" + msgId);
SendResult result = defaultMQProducer.send(msg);
System.out.printf("%s", result);
} else {
System.out.printf("no message. msgId=" + msgId);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void queryById(final DefaultMQAdminExt admin, final String msgId) throws MQClientException,
RemotingException, MQBrokerException, InterruptedException, IOException {
MessageExt msg = admin.viewMessage(msgId);
printMsg(admin, msg);
}
public static void printMsg(final DefaultMQAdminExt admin, final MessageExt msg) throws IOException {
if (msg == null) {
System.out.printf("%nMessage not found!");
return;
}
String bodyTmpFilePath = createBodyFile(msg);
String msgId = msg.getMsgId();
if (msg instanceof MessageClientExt) {
msgId = ((MessageClientExt) msg).getOffsetMsgId();
}
System.out.printf("%-20s %s%n",
"OffsetID:",
msgId
);
System.out.printf("%-20s %s%n",
"OffsetID:",
msgId
);
System.out.printf("%-20s %s%n",
"Topic:",
msg.getTopic()
);
System.out.printf("%-20s %s%n",
"Tags:",
"[" + msg.getTags() + "]"
);
System.out.printf("%-20s %s%n",
"Keys:",
"[" + msg.getKeys() + "]"
);
System.out.printf("%-20s %d%n",
"Queue ID:",
msg.getQueueId()
);
System.out.printf("%-20s %d%n",
"Queue Offset:",
msg.getQueueOffset()
);
System.out.printf("%-20s %d%n",
"CommitLog Offset:",
msg.getCommitLogOffset()
);
System.out.printf("%-20s %d%n",
"Reconsume Times:",
msg.getReconsumeTimes()
);
System.out.printf("%-20s %s%n",
"Born Timestamp:",
UtilAll.timeMillisToHumanString2(msg.getBornTimestamp())
);
System.out.printf("%-20s %s%n",
"Store Timestamp:",
UtilAll.timeMillisToHumanString2(msg.getStoreTimestamp())
);
System.out.printf("%-20s %s%n",
"Born Host:",
RemotingHelper.parseSocketAddressAddr(msg.getBornHost())
);
System.out.printf("%-20s %s%n",
"Store Host:",
RemotingHelper.parseSocketAddressAddr(msg.getStoreHost())
);
System.out.printf("%-20s %d%n",
"System Flag:",
msg.getSysFlag()
);
System.out.printf("%-20s %s%n",
"Properties:",
msg.getProperties() != null ? msg.getProperties().toString() : ""
);
System.out.printf("%-20s %s%n",
"Message Body Path:",
bodyTmpFilePath
);
try {
List<MessageTrack> mtdList = admin.messageTrackDetail(msg);
if (mtdList.isEmpty()) {
System.out.printf("%n%nWARN: No Consumer");
} else {
System.out.printf("%n%n");
for (MessageTrack mt : mtdList) {
System.out.printf("%s", mt);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String createBodyFile(MessageExt msg) throws IOException {
DataOutputStream dos = null;
try {
String bodyTmpFilePath = "/tmp/rocketmq/msgbodys";
File file = new File(bodyTmpFilePath);
if (!file.exists()) {
file.mkdirs();
}
bodyTmpFilePath = bodyTmpFilePath + "/" + msg.getMsgId();
dos = new DataOutputStream(new FileOutputStream(bodyTmpFilePath));
dos.write(msg.getBody());
return bodyTmpFilePath;
} finally {
if (dos != null)
dos.close();
}
}
}
| apache-2.0 |
zhukic/Sectioned-RecyclerView | sample/src/main/java/zhukic/sample/Movie.java | 888 | package zhukic.sample;
public class Movie {
private String title;
private int year;
private String genre;
public Movie(String title, int year, String genre) {
this.title = title;
this.year = year;
this.genre = genre;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
@Override
public String toString() {
return "Movie{" +
"title='" + title + '\'' +
", year=" + year +
", genre='" + genre + '\'' +
'}';
}
}
| apache-2.0 |
vincentbrison/android-easy-multidex | app/src/main/java/vincentbrison/com/testdexlimit/MainActivity.java | 1130 | package vincentbrison.com.testdexlimit;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| apache-2.0 |
freepander/wechart_weigou | src/freepander/model/PageModel.java | 2384 | package freepander.model;
import java.util.ArrayList;
import java.util.List;
/**
* 分页模型
*
* @author freepander
*
*/
public class PageModel {
/**
* 每页显示的数量
*/
private int countOfOnePage;
/**
* 当前页
*/
private int pageNum;
/**
* 总记录数
*/
private Long count;
/**
* 总页数
*/
private Long countPage;
/**
* 数据记录 List
*/
private List<Object> objects;
/**
* 页数的list
*/
private List<Integer> pageNumList = new ArrayList<Integer>();
/**
* 页面跳转到额url
*/
private String url;
// get和set方法
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Long getCount() {
return count;
}
public int getCountOfOnePage() {
return countOfOnePage;
}
public Long getCountPage() {
return countPage;
}
public List<Object> getObjects() {
return objects;
}
public int getPageNum() {
return pageNum;
}
public PageModel setCount(Long count) {
this.countPage = count / this.getCountOfOnePage();
if (count % this.getCountOfOnePage() > 0) {
this.countPage++;
}
if (this.countPage == 0) {
this.countPage = (long) 1;
}
this.count = count;
this.generatePageList();
return this;
}
public PageModel setCountOfOnePage(int countOfOnePage) {
this.countOfOnePage = countOfOnePage;
return this;
}
public PageModel setCountPage(Long countPage) {
this.countPage = countPage;
return this;
}
public PageModel setObjects(List<Object> objects) {
this.objects = objects;
return this;
}
public PageModel setPageNum(int pageNum) {
this.pageNum = pageNum;
return this;
}
public List<Integer> getPageNumList() {
return pageNumList;
}
public void setPageNumList(List<Integer> pageNumList) {
this.pageNumList = pageNumList;
}
public void generatePageList() {
if (this.countPage <= 9) {
for (int i = 1; i <= this.countPage; i++) {
this.pageNumList.add(i);
}
} else {
if (this.pageNum <= 9) {
for (int i = 1; i <= 9; i++) {
this.pageNumList.add(i);
}
} else if (this.pageNum >= this.countPage - 8) {
for (int i = (int) (this.countPage - 8); i <= this.countPage; i++) {
this.pageNumList.add(i);
}
} else {
for (int i = (int) (this.countPage - 4); i <= this.countPage + 4; i++) {
this.pageNumList.add(i);
}
}
}
}
}
| apache-2.0 |
j-coll/opencga | opencga-core/src/main/java/org/opencb/opencga/core/models/common/CustomStatusParams.java | 2007 | /*
* Copyright 2015-2020 OpenCB
*
* 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.opencb.opencga.core.models.common;
import org.opencb.opencga.core.common.TimeUtils;
public class CustomStatusParams {
private String name;
private String description;
public CustomStatusParams() {
}
public CustomStatusParams(String name, String description) {
this.name = name;
this.description = description;
}
public static CustomStatusParams of(CustomStatus status) {
if (status != null) {
return new CustomStatusParams(status.getName(), status.getDescription());
} else {
return null;
}
}
public CustomStatus toCustomStatus() {
return new CustomStatus(name, description, TimeUtils.getTime());
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("CustomStatusParams{");
sb.append("name='").append(name).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append('}');
return sb.toString();
}
public String getName() {
return name;
}
public CustomStatusParams setName(String name) {
this.name = name;
return this;
}
public String getDescription() {
return description;
}
public CustomStatusParams setDescription(String description) {
this.description = description;
return this;
}
}
| apache-2.0 |