repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
kenchen1101/jstorm | jstorm-core/src/main/java/com/alibaba/jstorm/task/group/MkLocalFirst.java | 4548 | /**
* 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.jstorm.task.group;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.utils.DisruptorQueue;
import com.alibaba.jstorm.daemon.worker.WorkerData;
import com.alibaba.jstorm.utils.IntervalCheck;
import com.alibaba.jstorm.utils.JStormUtils;
import com.alibaba.jstorm.utils.RandomRange;
/**
*
*
* @author zhongyan.feng
* @version
*/
public class MkLocalFirst extends Shuffer {
private static final Logger LOG = LoggerFactory.getLogger(MkLocalFirst.class);
private List<Integer> allOutTasks = new ArrayList<Integer>();
private List<Integer> localOutTasks = new ArrayList<Integer>();
private List<Integer> remoteOutTasks = new ArrayList<Integer>();
private RandomRange randomrange;
private RandomRange remoteRandomRange;
private boolean isLocalWorkerAvail;
private WorkerData workerData;
private IntervalCheck intervalCheck;
public MkLocalFirst(List<Integer> workerTasks, List<Integer> allOutTasks, WorkerData workerData) {
super(workerData);
intervalCheck = new IntervalCheck();
intervalCheck.setInterval(10);
this.allOutTasks.addAll(allOutTasks);
this.workerData = workerData;
List<Integer> localWorkerOutTasks = new ArrayList<Integer>();
for (Integer outTask : allOutTasks) {
if (workerTasks.contains(outTask)) {
localWorkerOutTasks.add(outTask);
}
}
remoteOutTasks.addAll(allOutTasks);
if (localWorkerOutTasks.size() != 0) {
isLocalWorkerAvail = true;
localOutTasks.addAll(localWorkerOutTasks);
} else {
isLocalWorkerAvail = false;
}
randomrange = new RandomRange(localOutTasks.size());
remoteRandomRange = new RandomRange(remoteOutTasks.size());
LOG.info("Local out tasks:" + localOutTasks + ", Remote out tasks:" + remoteOutTasks);
}
@Override
protected int getActiveTask(RandomRange randomrange, List<Integer> outTasks) {
int index = randomrange.nextInt();
int size = outTasks.size();
int i = 0;
for (i = 0; i < size; i++) {
Integer taskId = outTasks.get(index);
boolean taskStatus = workerData.isOutboundTaskActive(taskId);
DisruptorQueue exeQueue = (workerData.getInnerTaskTransfer().get(taskId));
float queueLoadRatio = exeQueue != null ? exeQueue.pctFull() : 0;
if (taskStatus && queueLoadRatio < 1.0)
break;
else
index = randomrange.nextInt();
}
return (i < size ? index : -1);
}
private List<Integer> intraGroup(List<Object> values) {
if (localOutTasks.size() == 0)
return null;
int index = getActiveTask(randomrange, localOutTasks);
if (index == -1) {
return null;
}
return JStormUtils.mk_list(localOutTasks.get(index));
}
private List<Integer> interGroup(List<Object> values) {
int index = getActiveTask(remoteRandomRange, remoteOutTasks);
if (index == -1) {
index = randomrange.nextInt();
}
return JStormUtils.mk_list(remoteOutTasks.get(index));
}
public List<Integer> grouper(List<Object> values) {
List<Integer> ret;
ret = intraGroup(values);
if (ret == null)
ret = interGroup(values);
return ret;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| apache-2.0 |
shahankhatch/aurora | src/jmh/java/org/apache/aurora/benchmark/BenchmarkSettings.java | 3319 | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aurora.benchmark;
import java.util.Set;
import org.apache.aurora.scheduler.storage.entities.IHostAttributes;
import org.apache.aurora.scheduler.storage.entities.IScheduledTask;
import static java.util.Objects.requireNonNull;
/**
* Benchmark test settings.
*/
final class BenchmarkSettings {
private final Set<IHostAttributes> hostAttributes;
private final double clusterUtilization;
private final boolean allVictimsEligibleForPreemption;
private final Set<IScheduledTask> tasks;
private BenchmarkSettings(
double clusterUtilization,
boolean allVictimsEligibleForPreemption,
Set<IHostAttributes> hostAttributes,
Set<IScheduledTask> tasks) {
this.clusterUtilization = clusterUtilization;
this.allVictimsEligibleForPreemption = allVictimsEligibleForPreemption;
this.hostAttributes = requireNonNull(hostAttributes);
this.tasks = requireNonNull(tasks);
}
/**
* Gets the cluster utilization factor specifying what percentage of hosts in the cluster
* already have tasks assigned to them.
*
* @return Cluster utilization (default: 0.9).
*/
double getClusterUtilization() {
return clusterUtilization;
}
/**
* Flag indicating whether all existing assigned tasks are available for preemption.
*
* @return Victim preemption eligibility (default: false).
*/
boolean areAllVictimsEligibleForPreemption() {
return allVictimsEligibleForPreemption;
}
/**
* Gets a set of cluster host attributes.
*
* @return Set of {@link IHostAttributes}.
*/
Set<IHostAttributes> getHostAttributes() {
return hostAttributes;
}
/**
* Gets a benchmark task.
*
* @return Task to run a benchmark for.
*/
Set<IScheduledTask> getTasks() {
return tasks;
}
static class Builder {
private double clusterUtilization = 0.9;
private boolean allVictimsEligibleForPreemption;
private Set<IHostAttributes> hostAttributes;
private Set<IScheduledTask> tasks;
Builder setClusterUtilization(double newClusterUtilization) {
clusterUtilization = newClusterUtilization;
return this;
}
Builder setVictimPreemptionEligibilty(boolean newPreemptionEligibility) {
allVictimsEligibleForPreemption = newPreemptionEligibility;
return this;
}
Builder setHostAttributes(Set<IHostAttributes> newHostAttributes) {
hostAttributes = newHostAttributes;
return this;
}
Builder setTasks(Set<IScheduledTask> newTasks) {
tasks = newTasks;
return this;
}
BenchmarkSettings build() {
return new BenchmarkSettings(
clusterUtilization,
allVictimsEligibleForPreemption,
hostAttributes,
tasks);
}
}
}
| apache-2.0 |
McLeodMoores/starling | projects/analytics/src/test/java/com/opengamma/analytics/financial/timeseries/analysis/DoubleTimeSeriesStatisticsCalculatorTest.java | 1847 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.timeseries.analysis;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.Test;
import com.opengamma.analytics.math.function.Function;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.statistics.descriptive.MeanCalculator;
import com.opengamma.timeseries.DoubleTimeSeries;
import com.opengamma.timeseries.precise.instant.ImmutableInstantDoubleTimeSeries;
import com.opengamma.util.test.TestGroup;
/**
* Test.
*/
@Test(groups = TestGroup.UNIT)
public class DoubleTimeSeriesStatisticsCalculatorTest {
private static final Function1D<double[], Double> MEAN = new MeanCalculator();
private static final Function<DoubleTimeSeries<?>, Double> CALC = new DoubleTimeSeriesStatisticsCalculator(MEAN);
private static final double X = 1.23;
private static final DoubleTimeSeries<?> TS = ImmutableInstantDoubleTimeSeries.of(new long[] {1, 2, 3, 4, 5}, new double[] {X, X, X, X, X});
@Test(expectedExceptions = IllegalArgumentException.class)
public void testConstructor() {
new DoubleTimeSeriesStatisticsCalculator(null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullTS() {
CALC.evaluate((DoubleTimeSeries<?>) null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testEmptyTS() {
CALC.evaluate(ImmutableInstantDoubleTimeSeries.EMPTY_SERIES);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullTSInArray() {
CALC.evaluate(TS, null, TS);
}
@Test
public void test() {
assertEquals(CALC.evaluate(TS), MEAN.evaluate(TS.valuesArrayFast()), 1e-15);
}
}
| apache-2.0 |
twitter/heron | heron/spi/src/java/org/apache/heron/spi/packing/PackingException.java | 1223 | /**
* 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.heron.spi.packing;
/**
* Thrown to indicate that an error occurred while creating a packing plan
*/
public class PackingException extends RuntimeException {
private static final long serialVersionUID = -7361943148478221250L;
public PackingException(String message) {
super(message);
}
public PackingException(String message, Throwable cause) {
super(message, cause);
}
}
| apache-2.0 |
tsdl2013/Android-Next | http/src/main/java/com/mcxiaoke/next/http/ProgressInterceptor.java | 685 | package com.mcxiaoke.next.http;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Response;
import java.io.IOException;
/**
* User: mcxiaoke
* Date: 15/7/2
* Time: 15:17
*/
class ProgressInterceptor implements Interceptor {
private ProgressListener listener;
public ProgressInterceptor(final ProgressListener listener) {
this.listener = listener;
}
@Override
public Response intercept(final Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response.newBuilder()
.body(new ProgressResponseBody(response.body(), listener))
.build();
}
}
| apache-2.0 |
robin13/elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/pipeline/CumulativeSumPipelineAggregator.java | 3315 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.search.aggregations.pipeline;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregation.ReduceContext;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramFactory;
import org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.search.aggregations.pipeline.BucketHelpers.resolveBucketValue;
public class CumulativeSumPipelineAggregator extends PipelineAggregator {
private final DocValueFormat formatter;
CumulativeSumPipelineAggregator(String name, String[] bucketsPaths, DocValueFormat formatter,
Map<String, Object> metadata) {
super(name, bucketsPaths, metadata);
this.formatter = formatter;
}
@Override
public InternalAggregation reduce(InternalAggregation aggregation, ReduceContext reduceContext) {
InternalMultiBucketAggregation<? extends InternalMultiBucketAggregation, ? extends InternalMultiBucketAggregation.InternalBucket>
histo = (InternalMultiBucketAggregation<? extends InternalMultiBucketAggregation, ? extends
InternalMultiBucketAggregation.InternalBucket>) aggregation;
List<? extends InternalMultiBucketAggregation.InternalBucket> buckets = histo.getBuckets();
HistogramFactory factory = (HistogramFactory) histo;
List<Bucket> newBuckets = new ArrayList<>(buckets.size());
double sum = 0;
for (InternalMultiBucketAggregation.InternalBucket bucket : buckets) {
Double thisBucketValue = resolveBucketValue(histo, bucket, bucketsPaths()[0], GapPolicy.INSERT_ZEROS);
// Only increment the sum if it's a finite value, otherwise "increment by zero" is correct
if (thisBucketValue != null && thisBucketValue.isInfinite() == false && thisBucketValue.isNaN() == false) {
sum += thisBucketValue;
}
List<InternalAggregation> aggs = StreamSupport.stream(bucket.getAggregations().spliterator(), false)
.map((p) -> (InternalAggregation) p)
.collect(Collectors.toList());
aggs.add(new InternalSimpleValue(name(), sum, formatter, metadata()));
Bucket newBucket = factory.createBucket(factory.getKey(bucket), bucket.getDocCount(), InternalAggregations.from(aggs));
newBuckets.add(newBucket);
}
return factory.createAggregation(newBuckets);
}
}
| apache-2.0 |
ysung-pivotal/incubator-geode | gemfire-core/src/test/java/com/gemstone/gemfire/cache30/DistributedAckOverflowRegionCCECompressionDUnitTest.java | 2122 | /*=========================================================================
* Copyright (c) 2010-2014 Pivotal Software, Inc. All Rights Reserved.
* This product is protected by U.S. and international copyright
* and intellectual property laws. Pivotal products are covered by
* one or more patents listed at http://www.pivotal.io/patents.
*=========================================================================
*/
package com.gemstone.gemfire.cache30;
import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.compression.Compressor;
import com.gemstone.gemfire.compression.SnappyCompressor;
/**
* Tests Distributed Ack Overflow Region with ConcurrencyChecksEnabled and compression.
*
* @author Kirk Lund
* @since 8.0
*/
public class DistributedAckOverflowRegionCCECompressionDUnitTest extends
DistributedAckOverflowRegionCCEDUnitTest {
public DistributedAckOverflowRegionCCECompressionDUnitTest(String name) {
super(name);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected RegionAttributes getRegionAttributes() {
Compressor compressor = null;
try {
compressor = SnappyCompressor.getDefaultInstance();
} catch (Throwable t) {
// Not a supported OS
return super.getRegionAttributes();
}
RegionAttributes attrs = super.getRegionAttributes();
AttributesFactory factory = new AttributesFactory(attrs);
factory.setCompressor(compressor);
return factory.create();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected RegionAttributes getRegionAttributes(String type) {
Compressor compressor = null;
try {
compressor = SnappyCompressor.getDefaultInstance();
} catch (Throwable t) {
// Not a supported OS
return super.getRegionAttributes(type);
}
RegionAttributes ra = super.getRegionAttributes(type);
AttributesFactory factory = new AttributesFactory(ra);
if(!ra.getDataPolicy().isEmpty()) {
factory.setCompressor(compressor);
}
return factory.create();
}
}
| apache-2.0 |
Peter32/android-validation-komensky | library/src/main/java/eu/inmite/android/lib/validations/form/validators/RegExpValidator.java | 949 | package eu.inmite.android.lib.validations.form.validators;
import eu.inmite.android.lib.validations.form.annotations.RegExp;
import eu.inmite.android.lib.validations.form.annotations.ValidatorFor;
import java.lang.annotation.Annotation;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Tomas Vondracek
*/
@ValidatorFor(RegExp.class)
public class RegExpValidator extends BaseValidator<CharSequence> {
private Pattern mCompiledPattern;
@Override
public boolean validate(Annotation annotation, CharSequence input) {
final String regexp = ((RegExp) annotation).value();
if (mCompiledPattern == null || ! mCompiledPattern.pattern().equals(regexp)) {
mCompiledPattern = Pattern.compile(regexp);
}
return validate(input, mCompiledPattern);
}
private boolean validate(final CharSequence input, final Pattern pattern) {
final Matcher matcher = pattern.matcher(input);
return matcher.matches();
}
}
| apache-2.0 |
gspandy/jprotobuf | v3/src/test/java/com/baidu/bjf/remoting/protobuf/bytestest/ByteTypeClass3.java | 1208 | /*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.bjf.remoting.protobuf.bytestest;
import com.baidu.bjf.remoting.protobuf.annotation.Protobuf;
/**
* Test single private byte array field with getter and setter method
*
* @author xiemalin
* @since 1.0.9
*/
public class ByteTypeClass3 {
@Protobuf
private byte[] bytes;
/**
* get the bytes
* @return the bytes
*/
public byte[] getBytes() {
return bytes;
}
/**
* set bytes value to bytes
* @param bytes the bytes to set
*/
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
}
| apache-2.0 |
isopov/spring-boot | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/amqp/DirectRabbitListenerContainerFactoryConfigurer.java | 1649 | /*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.amqp;
import org.springframework.amqp.rabbit.config.DirectRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.boot.context.properties.PropertyMapper;
/**
* Configure {@link DirectRabbitListenerContainerFactoryConfigurer} with sensible
* defaults.
*
* @author Gary Russell
* @author Stephane Nicoll
* @since 2.0
*/
public final class DirectRabbitListenerContainerFactoryConfigurer extends
AbstractRabbitListenerContainerFactoryConfigurer<DirectRabbitListenerContainerFactory> {
@Override
public void configure(DirectRabbitListenerContainerFactory factory,
ConnectionFactory connectionFactory) {
PropertyMapper map = PropertyMapper.get();
RabbitProperties.DirectContainer config = getRabbitProperties().getListener()
.getDirect();
configure(factory, connectionFactory, config);
map.from(config::getConsumersPerQueue).whenNonNull()
.to(factory::setConsumersPerQueue);
}
}
| apache-2.0 |
sunlibin/incubator-eagle | eagle-security/eagle-security-userprofile/common/src/main/java/org/apache/eagle/security/userprofile/UserPartitioner.java | 1181 | /*
* 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.eagle.security.userprofile;
import kafka.utils.VerifiableProperties;
import kafka.utils.Utils;
public class UserPartitioner implements kafka.producer.Partitioner{
public UserPartitioner(VerifiableProperties prop){
}
@Override
public int partition(Object arg0, int arg1) {
String user = (String)arg0;
return Utils.abs(user.hashCode()) % arg1;
}
} | apache-2.0 |
GabrielBrascher/cloudstack | engine/schema/src/main/java/com/cloud/vm/dao/UserVmDetailsDaoImpl.java | 1297 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.vm.dao;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase;
import com.cloud.vm.UserVmDetailVO;
@Component
public class UserVmDetailsDaoImpl extends ResourceDetailsDaoBase<UserVmDetailVO> implements UserVmDetailsDao {
@Override
public void addDetail(long resourceId, String key, String value, boolean display) {
super.addDetail(new UserVmDetailVO(resourceId, key, value, display));
}
}
| apache-2.0 |
nchinth/nd4j | nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/arithmetic/CopyOp.java | 3566 | /*
*
* * Copyright 2015 Skymind,Inc.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*
*/
package org.nd4j.linalg.api.ops.impl.transforms.arithmetic;
import org.nd4j.linalg.api.complex.IComplexNumber;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.BaseTransformOp;
import org.nd4j.linalg.api.ops.Op;
import org.nd4j.linalg.factory.Nd4j;
/**
* Copy operation
*
* @author Adam Gibson
*/
public class CopyOp extends BaseTransformOp {
public CopyOp() {
}
public CopyOp(INDArray x, INDArray y, INDArray z, int n) {
super(x, y, z, n);
}
public CopyOp(INDArray x, INDArray z) {
super(x, z);
}
public CopyOp(INDArray x, INDArray z, int n) {
super(x, z, n);
}
public CopyOp(INDArray x) {
super(x);
}
public CopyOp(INDArray x, INDArray xDup, INDArray z) {
super(x, xDup, z, x.length());
}
@Override
public String name() {
return "copy";
}
@Override
public IComplexNumber op(IComplexNumber origin, double other) {
return Nd4j.createComplexNumber(other, 0);
}
@Override
public IComplexNumber op(IComplexNumber origin, float other) {
return Nd4j.createComplexNumber(other, 0);
}
@Override
public IComplexNumber op(IComplexNumber origin, IComplexNumber other) {
return origin;
}
@Override
public float op(float origin, float other) {
return origin;
}
@Override
public double op(double origin, double other) {
return origin;
}
@Override
public double op(double origin) {
return origin;
}
@Override
public float op(float origin) {
return origin;
}
@Override
public IComplexNumber op(IComplexNumber origin) {
return origin;
}
@Override
public Op opForDimension(int index, int dimension) {
INDArray xAlongDimension = x.vectorAlongDimension(index, dimension);
if (y() != null)
return new CopyOp(xAlongDimension, y.vectorAlongDimension(index, dimension), z.vectorAlongDimension(index, dimension), xAlongDimension.length());
else
return new CopyOp(xAlongDimension, z.vectorAlongDimension(index, dimension), xAlongDimension.length());
}
@Override
public Op opForDimension(int index, int... dimension) {
INDArray xAlongDimension = x.tensorAlongDimension(index, dimension);
if (y() != null)
return new CopyOp(xAlongDimension, y.tensorAlongDimension(index, dimension), z.tensorAlongDimension(index, dimension), xAlongDimension.length());
else
return new CopyOp(xAlongDimension, z.tensorAlongDimension(index, dimension), xAlongDimension.length());
}
@Override
public void init(INDArray x, INDArray y, INDArray z, int n) {
super.init(x, y, z, n);
if (y == null)
throw new IllegalArgumentException("No components to add");
}
}
| apache-2.0 |
nikhilvibhav/camel | dsl/camel-xml-jaxb-dsl/src/test/java/org/apache/camel/dsl/xml/jaxb/support/MockRestConsumerFactory.java | 1540 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.dsl.xml.jaxb.support;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestConsumerFactory;
public final class MockRestConsumerFactory implements RestConsumerFactory {
@Override
public Consumer createConsumer(
CamelContext camelContext,
Processor processor,
String verb,
String basePath,
String uriTemplate,
String consumes,
String produces,
RestConfiguration configuration,
Map<String, Object> parameters) {
return null;
}
}
| apache-2.0 |
dewmini/carbon-apimgt | gateway-modules/apim-ballerina-native-component/src/test/java/org/wso2/carbon/apimgt/ballerina/util/SaveFileTestCase.java | 2071 | /*
* Copyright (c) 2017, 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.ballerina.util;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
/**
* Test class for saving a file
*/
public class SaveFileTestCase {
private static File tempFile = null;
@BeforeClass
public void setup() throws IOException {
//create a temp file to save the content.
tempFile = File.createTempFile("testTextFile", ".txt");
tempFile.deleteOnExit();
}
@Test(description = "Save file test case")
public void saveFile() {
String path = tempFile.getAbsolutePath();
String content = "Content for save file test case.";
//the below call should be successful since the path is valid (it should return true)
boolean saveFileStatus = Util.saveFile(path, content);
Assert.assertTrue(saveFileStatus);
path = "ThisIsAnInvalidPath" + File.separator + "InvalidFile.txt";
//the below call should fail since the path is invalid (it should return false)
saveFileStatus = Util.saveFile(path, content);
Assert.assertFalse(saveFileStatus);
path = "";
//the below call should fail since the path is empty (it should return false)
saveFileStatus = Util.saveFile(path, content);
Assert.assertFalse(saveFileStatus);
}
}
| apache-2.0 |
shvoidlee/hapi-fhir | hapi-fhir-base/src/main/java/ca/uhn/fhir/util/IModelVisitor2.java | 1876 | package ca.uhn.fhir.util;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* 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 java.util.List;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseExtension;
import org.hl7.fhir.instance.model.api.IBaseResource;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
/**
* @see FhirTerser#visit(IBaseResource, IModelVisitor2)
*/
public interface IModelVisitor2 {
/**
* @param theElement The element being visited
* @param theContainingElementPath The elements in the path leading up to the actual element being accepted. The first element in this path will be the outer resource being visited, and the last element will be the saem object as the object passed as <code>theElement</code>
*/
boolean acceptElement(IBase theElement, List<IBase> theContainingElementPath, List<BaseRuntimeChildDefinition> theChildDefinitionPath, List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath);
/**
*/
boolean acceptUndeclaredExtension(IBaseExtension<?, ?> theNextExt, List<IBase> theContainingElementPath, List<BaseRuntimeChildDefinition> theChildDefinitionPath, List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath);
}
| apache-2.0 |
yew1eb/flink | flink-streaming-java/src/test/java/org/apache/flink/streaming/graph/StreamingJobGraphGeneratorNodeHashTest.java | 18425 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.graph;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.JobVertex;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.streaming.api.graph.StreamNode;
import org.apache.flink.util.TestLogger;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Tests the {@link StreamNode} hash assignment during translation from {@link StreamGraph} to
* {@link JobGraph} instances.
*/
@SuppressWarnings("serial")
public class StreamingJobGraphGeneratorNodeHashTest extends TestLogger {
// ------------------------------------------------------------------------
// Deterministic hash assignment
// ------------------------------------------------------------------------
/**
* Creates the same flow twice and checks that all IDs are the same.
*
* <pre>
* [ (src) -> (map) -> (filter) -> (reduce) -> (map) -> (sink) ]
* //
* [ (src) -> (filter) ] -------------------------------//
* /
* [ (src) -> (filter) ] ------------------------------/
* </pre>
*/
@Test
public void testNodeHashIsDeterministic() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
DataStream<String> src0 = env
.addSource(new NoOpSourceFunction(), "src0")
.map(new NoOpMapFunction())
.filter(new NoOpFilterFunction())
.keyBy(new NoOpKeySelector())
.reduce(new NoOpReduceFunction()).name("reduce");
DataStream<String> src1 = env
.addSource(new NoOpSourceFunction(), "src1")
.filter(new NoOpFilterFunction());
DataStream<String> src2 = env
.addSource(new NoOpSourceFunction(), "src2")
.filter(new NoOpFilterFunction());
src0.map(new NoOpMapFunction())
.union(src1, src2)
.addSink(new NoOpSinkFunction()).name("sink");
JobGraph jobGraph = env.getStreamGraph().getJobGraph();
final Map<JobVertexID, String> ids = rememberIds(jobGraph);
// Do it again and verify
env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
src0 = env
.addSource(new NoOpSourceFunction(), "src0")
.map(new NoOpMapFunction())
.filter(new NoOpFilterFunction())
.keyBy(new NoOpKeySelector())
.reduce(new NoOpReduceFunction()).name("reduce");
src1 = env
.addSource(new NoOpSourceFunction(), "src1")
.filter(new NoOpFilterFunction());
src2 = env
.addSource(new NoOpSourceFunction(), "src2")
.filter(new NoOpFilterFunction());
src0.map(new NoOpMapFunction())
.union(src1, src2)
.addSink(new NoOpSinkFunction()).name("sink");
jobGraph = env.getStreamGraph().getJobGraph();
verifyIdsEqual(jobGraph, ids);
}
/**
* Tests that there are no collisions with two identical sources.
*
* <pre>
* [ (src0) ] --\
* +--> [ (sink) ]
* [ (src1) ] --/
* </pre>
*/
@Test
public void testNodeHashIdenticalSources() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.disableOperatorChaining();
DataStream<String> src0 = env.addSource(new NoOpSourceFunction());
DataStream<String> src1 = env.addSource(new NoOpSourceFunction());
src0.union(src1).addSink(new NoOpSinkFunction());
JobGraph jobGraph = env.getStreamGraph().getJobGraph();
List<JobVertex> vertices = jobGraph.getVerticesSortedTopologicallyFromSources();
assertTrue(vertices.get(0).isInputVertex());
assertTrue(vertices.get(1).isInputVertex());
assertNotNull(vertices.get(0).getID());
assertNotNull(vertices.get(1).getID());
assertNotEquals(vertices.get(0).getID(), vertices.get(1).getID());
}
/**
* Tests that (un)chaining affects the node hash (for sources).
*
* <pre>
* A (chained): [ (src0) -> (map) -> (filter) -> (sink) ]
* B (unchained): [ (src0) ] -> [ (map) -> (filter) -> (sink) ]
* </pre>
*
* <p>The hashes for the single vertex in A and the source vertex in B need to be different.
*/
@Test
public void testNodeHashAfterSourceUnchaining() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.addSource(new NoOpSourceFunction())
.map(new NoOpMapFunction())
.filter(new NoOpFilterFunction())
.addSink(new NoOpSinkFunction());
JobGraph jobGraph = env.getStreamGraph().getJobGraph();
JobVertexID sourceId = jobGraph.getVerticesSortedTopologicallyFromSources()
.get(0).getID();
env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.addSource(new NoOpSourceFunction())
.map(new NoOpMapFunction())
.startNewChain()
.filter(new NoOpFilterFunction())
.addSink(new NoOpSinkFunction());
jobGraph = env.getStreamGraph().getJobGraph();
JobVertexID unchainedSourceId = jobGraph.getVerticesSortedTopologicallyFromSources()
.get(0).getID();
assertNotEquals(sourceId, unchainedSourceId);
}
/**
* Tests that (un)chaining affects the node hash (for intermediate nodes).
*
* <pre>
* A (chained): [ (src0) -> (map) -> (filter) -> (sink) ]
* B (unchained): [ (src0) ] -> [ (map) -> (filter) -> (sink) ]
* </pre>
*
* <p>The hashes for the single vertex in A and the source vertex in B need to be different.
*/
@Test
public void testNodeHashAfterIntermediateUnchaining() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.addSource(new NoOpSourceFunction())
.map(new NoOpMapFunction()).name("map")
.startNewChain()
.filter(new NoOpFilterFunction())
.addSink(new NoOpSinkFunction());
JobGraph jobGraph = env.getStreamGraph().getJobGraph();
JobVertex chainedMap = jobGraph.getVerticesSortedTopologicallyFromSources().get(1);
assertTrue(chainedMap.getName().startsWith("map"));
JobVertexID chainedMapId = chainedMap.getID();
env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.addSource(new NoOpSourceFunction())
.map(new NoOpMapFunction()).name("map")
.startNewChain()
.filter(new NoOpFilterFunction())
.startNewChain()
.addSink(new NoOpSinkFunction());
jobGraph = env.getStreamGraph().getJobGraph();
JobVertex unchainedMap = jobGraph.getVerticesSortedTopologicallyFromSources().get(1);
assertEquals("map", unchainedMap.getName());
JobVertexID unchainedMapId = unchainedMap.getID();
assertNotEquals(chainedMapId, unchainedMapId);
}
/**
* Tests that there are no collisions with two identical intermediate nodes connected to the
* same predecessor.
*
* <pre>
* /-> [ (map) ] -> [ (sink) ]
* [ (src) ] -+
* \-> [ (map) ] -> [ (sink) ]
* </pre>
*/
@Test
public void testNodeHashIdenticalNodes() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.disableOperatorChaining();
DataStream<String> src = env.addSource(new NoOpSourceFunction());
src.map(new NoOpMapFunction()).addSink(new NoOpSinkFunction());
src.map(new NoOpMapFunction()).addSink(new NoOpSinkFunction());
JobGraph jobGraph = env.getStreamGraph().getJobGraph();
Set<JobVertexID> vertexIds = new HashSet<>();
for (JobVertex vertex : jobGraph.getVertices()) {
assertTrue(vertexIds.add(vertex.getID()));
}
}
/**
* Tests that a changed operator name does not affect the hash.
*/
@Test
public void testChangedOperatorName() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.addSource(new NoOpSourceFunction(), "A").map(new NoOpMapFunction());
JobGraph jobGraph = env.getStreamGraph().getJobGraph();
JobVertexID expected = jobGraph.getVerticesAsArray()[0].getID();
env = StreamExecutionEnvironment.createLocalEnvironment();
env.addSource(new NoOpSourceFunction(), "B").map(new NoOpMapFunction());
jobGraph = env.getStreamGraph().getJobGraph();
JobVertexID actual = jobGraph.getVerticesAsArray()[0].getID();
assertEquals(expected, actual);
}
// ------------------------------------------------------------------------
// Manual hash assignment
// ------------------------------------------------------------------------
/**
* Tests that manual hash assignments are mapped to the same operator ID.
*
* <pre>
* /-> [ (map) ] -> [ (sink)@sink0 ]
* [ (src@source ) ] -+
* \-> [ (map) ] -> [ (sink)@sink1 ]
* </pre>
*
* <pre>
* /-> [ (map) ] -> [ (reduce) ] -> [ (sink)@sink0 ]
* [ (src)@source ] -+
* \-> [ (map) ] -> [ (reduce) ] -> [ (sink)@sink1 ]
* </pre>
*/
@Test
public void testManualHashAssignment() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.disableOperatorChaining();
DataStream<String> src = env.addSource(new NoOpSourceFunction())
.name("source").uid("source");
src.map(new NoOpMapFunction())
.addSink(new NoOpSinkFunction())
.name("sink0").uid("sink0");
src.map(new NoOpMapFunction())
.addSink(new NoOpSinkFunction())
.name("sink1").uid("sink1");
JobGraph jobGraph = env.getStreamGraph().getJobGraph();
Set<JobVertexID> ids = new HashSet<>();
for (JobVertex vertex : jobGraph.getVertices()) {
assertTrue(ids.add(vertex.getID()));
}
// Resubmit a slightly different program
env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.disableOperatorChaining();
src = env.addSource(new NoOpSourceFunction())
// New map function, should be mapped to the source state
.map(new NoOpMapFunction())
.name("source").uid("source");
src.map(new NoOpMapFunction())
.keyBy(new NoOpKeySelector())
.reduce(new NoOpReduceFunction())
.addSink(new NoOpSinkFunction())
.name("sink0").uid("sink0");
src.map(new NoOpMapFunction())
.keyBy(new NoOpKeySelector())
.reduce(new NoOpReduceFunction())
.addSink(new NoOpSinkFunction())
.name("sink1").uid("sink1");
JobGraph newJobGraph = env.getStreamGraph().getJobGraph();
assertNotEquals(jobGraph.getJobID(), newJobGraph.getJobID());
for (JobVertex vertex : newJobGraph.getVertices()) {
// Verify that the expected IDs are the same
if (vertex.getName().endsWith("source")
|| vertex.getName().endsWith("sink0")
|| vertex.getName().endsWith("sink1")) {
assertTrue(ids.contains(vertex.getID()));
}
}
}
/**
* Tests that a collision on the manual hash throws an Exception.
*/
@Test(expected = IllegalArgumentException.class)
public void testManualHashAssignmentCollisionThrowsException() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.disableOperatorChaining();
env.addSource(new NoOpSourceFunction()).uid("source")
.map(new NoOpMapFunction()).uid("source") // Collision
.addSink(new NoOpSinkFunction());
// This call is necessary to generate the job graph
env.getStreamGraph().getJobGraph();
}
/**
* Tests that a manual hash for an intermediate chain node is accepted.
*/
@Test
public void testManualHashAssignmentForIntermediateNodeInChain() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.addSource(new NoOpSourceFunction())
// Intermediate chained node
.map(new NoOpMapFunction()).uid("map")
.addSink(new NoOpSinkFunction());
env.getStreamGraph().getJobGraph();
}
/**
* Tests that a manual hash at the beginning of a chain is accepted.
*/
@Test
public void testManualHashAssignmentForStartNodeInInChain() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.setParallelism(4);
env.addSource(new NoOpSourceFunction()).uid("source")
.map(new NoOpMapFunction())
.addSink(new NoOpSinkFunction());
env.getStreamGraph().getJobGraph();
}
@Test
public void testUserProvidedHashing() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
List<String> userHashes = Arrays.asList("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
env.addSource(new NoOpSourceFunction(), "src").setUidHash(userHashes.get(0))
.map(new NoOpMapFunction())
.filter(new NoOpFilterFunction())
.keyBy(new NoOpKeySelector())
.reduce(new NoOpReduceFunction()).name("reduce").setUidHash(userHashes.get(1));
StreamGraph streamGraph = env.getStreamGraph();
int idx = 1;
for (JobVertex jobVertex : streamGraph.getJobGraph().getVertices()) {
List<JobVertexID> idAlternatives = jobVertex.getIdAlternatives();
Assert.assertEquals(idAlternatives.get(idAlternatives.size() - 1).toString(), userHashes.get(idx));
--idx;
}
}
@Test
public void testUserProvidedHashingOnChainSupported() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment();
env.addSource(new NoOpSourceFunction(), "src").setUidHash("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
.map(new NoOpMapFunction()).setUidHash("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
.filter(new NoOpFilterFunction()).setUidHash("cccccccccccccccccccccccccccccccc")
.keyBy(new NoOpKeySelector())
.reduce(new NoOpReduceFunction()).name("reduce").setUidHash("dddddddddddddddddddddddddddddddd");
env.getStreamGraph().getJobGraph();
}
// ------------------------------------------------------------------------
/**
* Returns a {@link JobVertexID} to vertex name mapping for the given graph.
*/
private Map<JobVertexID, String> rememberIds(JobGraph jobGraph) {
final Map<JobVertexID, String> ids = new HashMap<>();
for (JobVertex vertex : jobGraph.getVertices()) {
ids.put(vertex.getID(), vertex.getName());
}
return ids;
}
/**
* Verifies that each {@link JobVertexID} of the {@link JobGraph} is contained in the given map
* and mapped to the same vertex name.
*/
private void verifyIdsEqual(JobGraph jobGraph, Map<JobVertexID, String> ids) {
// Verify same number of vertices
assertEquals(jobGraph.getNumberOfVertices(), ids.size());
// Verify that all IDs->name mappings are identical
for (JobVertex vertex : jobGraph.getVertices()) {
String expectedName = ids.get(vertex.getID());
assertNotNull(expectedName);
assertEquals(expectedName, vertex.getName());
}
}
/**
* Verifies that no {@link JobVertexID} of the {@link JobGraph} is contained in the given map.
*/
private void verifyIdsNotEqual(JobGraph jobGraph, Map<JobVertexID, String> ids) {
// Verify same number of vertices
assertEquals(jobGraph.getNumberOfVertices(), ids.size());
// Verify that all IDs->name mappings are identical
for (JobVertex vertex : jobGraph.getVertices()) {
assertFalse(ids.containsKey(vertex.getID()));
}
}
// ------------------------------------------------------------------------
private static class NoOpSourceFunction implements ParallelSourceFunction<String> {
private static final long serialVersionUID = -5459224792698512636L;
@Override
public void run(SourceContext<String> ctx) throws Exception {
}
@Override
public void cancel() {
}
}
private static class NoOpSinkFunction implements SinkFunction<String> {
private static final long serialVersionUID = -5654199886203297279L;
@Override
public void invoke(String value) throws Exception {
}
}
private static class NoOpMapFunction implements MapFunction<String, String> {
private static final long serialVersionUID = 6584823409744624276L;
@Override
public String map(String value) throws Exception {
return value;
}
}
private static class NoOpFilterFunction implements FilterFunction<String> {
private static final long serialVersionUID = 500005424900187476L;
@Override
public boolean filter(String value) throws Exception {
return true;
}
}
private static class NoOpKeySelector implements KeySelector<String, String> {
private static final long serialVersionUID = -96127515593422991L;
@Override
public String getKey(String value) throws Exception {
return value;
}
}
private static class NoOpReduceFunction implements ReduceFunction<String> {
private static final long serialVersionUID = -8775747640749256372L;
@Override
public String reduce(String value1, String value2) throws Exception {
return value1;
}
}
}
| apache-2.0 |
mdecourci/assertj-core | src/test/java/org/assertj/core/internal/intarrays/IntArrays_assertContainsOnly_Test.java | 5931 | /**
* 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.
*
* Copyright 2012-2015 the original author or authors.
*/
package org.assertj.core.internal.intarrays;
import static org.assertj.core.error.ShouldContainOnly.shouldContainOnly;
import static org.assertj.core.test.ErrorMessages.valuesToLookForIsNull;
import static org.assertj.core.test.IntArrays.arrayOf;
import static org.assertj.core.test.IntArrays.emptyArray;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.assertj.core.util.Lists.newArrayList;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.IntArrays;
import org.assertj.core.internal.IntArraysBaseTest;
import org.junit.Test;
/**
* Tests for <code>{@link IntArrays#assertContainsOnly(AssertionInfo, int[], int[])}</code>.
*
* @author Alex Ruiz
* @author Joel Costigliola
*/
public class IntArrays_assertContainsOnly_Test extends IntArraysBaseTest {
@Test
public void should_pass_if_actual_contains_given_values_only() {
arrays.assertContainsOnly(someInfo(), actual, arrayOf(6, 8, 10));
}
@Test
public void should_pass_if_actual_contains_given_values_only_in_different_order() {
arrays.assertContainsOnly(someInfo(), actual, arrayOf(10, 8, 6));
}
@Test
public void should_pass_if_actual_contains_given_values_only_more_than_once() {
actual = arrayOf(6, 8, 10, 8, 8, 8);
arrays.assertContainsOnly(someInfo(), actual, arrayOf(6, 8, 10));
}
@Test
public void should_pass_if_actual_contains_given_values_only_even_if_duplicated() {
arrays.assertContainsOnly(someInfo(), actual, arrayOf(6, 8, 10, 6, 8, 10));
}
@Test
public void should_pass_if_actual_and_given_values_are_empty() {
actual = emptyArray();
arrays.assertContainsOnly(someInfo(), actual, emptyArray());
}
@Test
public void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not() {
thrown.expect(AssertionError.class);
arrays.assertContainsOnly(someInfo(), actual, emptyArray());
}
@Test
public void should_throw_error_if_array_of_values_to_look_for_is_null() {
thrown.expectNullPointerException(valuesToLookForIsNull());
arrays.assertContainsOnly(someInfo(), actual, null);
}
@Test
public void should_fail_if_actual_is_null() {
thrown.expectAssertionError(actualIsNull());
arrays.assertContainsOnly(someInfo(), null, arrayOf(8));
}
@Test
public void should_fail_if_actual_does_not_contain_given_values_only() {
AssertionInfo info = someInfo();
int[] expected = { 6, 8, 20 };
try {
arrays.assertContainsOnly(info, actual, expected);
} catch (AssertionError e) {
verify(failures).failure(info, shouldContainOnly(actual, expected, newArrayList(20), newArrayList(10)));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_pass_if_actual_contains_given_values_only_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, arrayOf(6, -8, 10));
}
@Test
public void should_pass_if_actual_contains_given_values_only_in_different_order_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, arrayOf(10, -8, 6));
}
@Test
public void should_pass_if_actual_contains_given_values_only_more_than_once_according_to_custom_comparison_strategy() {
actual = arrayOf(6, -8, 10, -8, -8, -8);
arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, arrayOf(6, -8, 10));
}
@Test
public void should_pass_if_actual_contains_given_values_only_even_if_duplicated_according_to_custom_comparison_strategy() {
arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, arrayOf(6, -8, 10, 6, -8, 10));
}
@Test
public void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not_whatever_custom_comparison_strategy_is() {
thrown.expect(AssertionError.class);
arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, emptyArray());
}
@Test
public void should_throw_error_if_array_of_values_to_look_for_is_null_whatever_custom_comparison_strategy_is() {
thrown.expectNullPointerException(valuesToLookForIsNull());
arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), actual, null);
}
@Test
public void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
thrown.expectAssertionError(actualIsNull());
arraysWithCustomComparisonStrategy.assertContainsOnly(someInfo(), null, arrayOf(-8));
}
@Test
public void should_fail_if_actual_does_not_contain_given_values_only_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
int[] expected = { 6, -8, 20 };
try {
arraysWithCustomComparisonStrategy.assertContainsOnly(info, actual, expected);
} catch (AssertionError e) {
verify(failures).failure(info,
shouldContainOnly(actual, expected, newArrayList(20), newArrayList(10),
absValueComparisonStrategy));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
}
| apache-2.0 |
Darsstar/framework | shared/src/main/java/com/vaadin/shared/ui/draganddropwrapper/DragAndDropWrapperConstants.java | 1018 | /*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.shared.ui.draganddropwrapper;
import java.io.Serializable;
@Deprecated
public class DragAndDropWrapperConstants implements Serializable {
@Deprecated
public static final String HTML5_DATA_FLAVORS = "html5-data-flavors";
@Deprecated
public static final String DRAG_START_MODE = "dragStartMode";
public static final String DRAG_START_COMPONENT_ATTRIBUTE = "dragStartComponent";
}
| apache-2.0 |
modwizcode/SpongeCommon | src/main/java/org/spongepowered/common/util/gen/AbstractBiomeBuffer.java | 3100 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.util.gen;
import com.flowpowered.math.vector.Vector2i;
import com.google.common.base.Objects;
import org.spongepowered.api.util.PositionOutOfBoundsException;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.api.world.extent.BiomeArea;
import org.spongepowered.common.util.VecHelper;
/**
* Base class for biome areas. This class provides methods for retrieving the
* size and for range checking.
*/
@NonnullByDefault
public abstract class AbstractBiomeBuffer implements BiomeArea {
protected Vector2i start;
protected Vector2i size;
protected Vector2i end;
private final int xLine;
protected AbstractBiomeBuffer(Vector2i start, Vector2i size) {
this.start = start;
this.size = size;
this.end = this.start.add(this.size).sub(Vector2i.ONE);
this.xLine = size.getX();
}
protected final void checkRange(int x, int z) {
if (!VecHelper.inBounds(x, z, this.start, this.end)) {
throw new PositionOutOfBoundsException(new Vector2i(x, z), this.start, this.end);
}
}
protected int getIndex(int x, int y) {
return (y - this.start.getY()) * this.xLine + (x - this.start.getX());
}
@Override
public Vector2i getBiomeMin() {
return this.start;
}
@Override
public Vector2i getBiomeMax() {
return this.end;
}
@Override
public Vector2i getBiomeSize() {
return this.size;
}
@Override
public boolean containsBiome(int x, int z) {
return VecHelper.inBounds(x, z, this.start, this.end);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("min", this.getBiomeMin())
.add("max", this.getBiomeMax())
.toString();
}
}
| mit |
AnodeCathode/BetterStorage | src/main/java/net/mcft/copy/betterstorage/content/BetterStorageItems.java | 5233 | package net.mcft.copy.betterstorage.content;
import net.mcft.copy.betterstorage.BetterStorage;
import net.mcft.copy.betterstorage.addon.Addon;
import net.mcft.copy.betterstorage.config.GlobalConfig;
import net.mcft.copy.betterstorage.item.ItemBackpack;
import net.mcft.copy.betterstorage.item.ItemBucketSlime;
import net.mcft.copy.betterstorage.item.ItemDrinkingHelmet;
import net.mcft.copy.betterstorage.item.ItemEnderBackpack;
import net.mcft.copy.betterstorage.item.ItemPresentBook;
import net.mcft.copy.betterstorage.item.cardboard.ItemCardboardArmor;
import net.mcft.copy.betterstorage.item.cardboard.ItemCardboardAxe;
import net.mcft.copy.betterstorage.item.cardboard.ItemCardboardHoe;
import net.mcft.copy.betterstorage.item.cardboard.ItemCardboardPickaxe;
import net.mcft.copy.betterstorage.item.cardboard.ItemCardboardSheet;
import net.mcft.copy.betterstorage.item.cardboard.ItemCardboardShovel;
import net.mcft.copy.betterstorage.item.cardboard.ItemCardboardSword;
import net.mcft.copy.betterstorage.item.locking.ItemKey;
import net.mcft.copy.betterstorage.item.locking.ItemKeyring;
import net.mcft.copy.betterstorage.item.locking.ItemLock;
import net.mcft.copy.betterstorage.item.locking.ItemMasterKey;
import net.mcft.copy.betterstorage.utils.MiscUtils;
import net.minecraftforge.oredict.OreDictionary;
public final class BetterStorageItems {
public static ItemKey key;
public static ItemLock lock;
public static ItemKeyring keyring;
public static ItemCardboardSheet cardboardSheet;
public static ItemMasterKey masterKey;
public static ItemDrinkingHelmet drinkingHelmet;
public static ItemBucketSlime slimeBucket;
public static ItemPresentBook presentBook;
public static ItemBackpack itemBackpack;
public static ItemEnderBackpack itemEnderBackpack;
public static ItemCardboardArmor cardboardHelmet;
public static ItemCardboardArmor cardboardChestplate;
public static ItemCardboardArmor cardboardLeggings;
public static ItemCardboardArmor cardboardBoots;
public static ItemCardboardSword cardboardSword;
public static ItemCardboardPickaxe cardboardPickaxe;
public static ItemCardboardShovel cardboardShovel;
public static ItemCardboardAxe cardboardAxe;
public static ItemCardboardHoe cardboardHoe;
public static boolean anyCardboardItemsEnabled;
private BetterStorageItems() { }
public static void initialize() {
key = MiscUtils.conditionalNew(ItemKey.class, GlobalConfig.keyEnabled);
lock = MiscUtils.conditionalNew(ItemLock.class, GlobalConfig.lockEnabled);
keyring = MiscUtils.conditionalNew(ItemKeyring.class, GlobalConfig.keyringEnabled);
cardboardSheet = MiscUtils.conditionalNew(ItemCardboardSheet.class, GlobalConfig.cardboardSheetEnabled);
masterKey = MiscUtils.conditionalNew(ItemMasterKey.class, GlobalConfig.masterKeyEnabled);
drinkingHelmet = MiscUtils.conditionalNew(ItemDrinkingHelmet.class, GlobalConfig.drinkingHelmetEnabled);
slimeBucket = MiscUtils.conditionalNew(ItemBucketSlime.class, GlobalConfig.slimeBucketEnabled);
presentBook = new ItemPresentBook();
itemBackpack = MiscUtils.conditionalNew(ItemBackpack.class, GlobalConfig.backpackEnabled);
itemEnderBackpack = MiscUtils.conditionalNew(ItemEnderBackpack.class, GlobalConfig.enderBackpackEnabled);
cardboardHelmet = conditionalNewArmor(GlobalConfig.cardboardHelmetEnabled, 0);
cardboardChestplate = conditionalNewArmor(GlobalConfig.cardboardChestplateEnabled, 1);
cardboardLeggings = conditionalNewArmor(GlobalConfig.cardboardLeggingsEnabled, 2);
cardboardBoots = conditionalNewArmor(GlobalConfig.cardboardBootsEnabled, 3);
cardboardSword = MiscUtils.conditionalNew(ItemCardboardSword.class, GlobalConfig.cardboardSwordEnabled);
cardboardPickaxe = MiscUtils.conditionalNew(ItemCardboardPickaxe.class, GlobalConfig.cardboardPickaxeEnabled);
cardboardShovel = MiscUtils.conditionalNew(ItemCardboardShovel.class, GlobalConfig.cardboardShovelEnabled);
cardboardAxe = MiscUtils.conditionalNew(ItemCardboardAxe.class, GlobalConfig.cardboardAxeEnabled);
cardboardHoe = MiscUtils.conditionalNew(ItemCardboardHoe.class, GlobalConfig.cardboardHoeEnabled);
anyCardboardItemsEnabled = ((BetterStorageItems.cardboardHelmet != null) ||
(BetterStorageItems.cardboardChestplate != null) ||
(BetterStorageItems.cardboardLeggings != null) ||
(BetterStorageItems.cardboardBoots != null) ||
(BetterStorageItems.cardboardSword != null) ||
(BetterStorageItems.cardboardPickaxe != null) ||
(BetterStorageItems.cardboardAxe != null) ||
(BetterStorageItems.cardboardShovel != null) ||
(BetterStorageItems.cardboardHoe != null));
if (cardboardSheet != null)
OreDictionary.registerOre("sheetCardboard", cardboardSheet);
Addon.initializeItemsAll();
}
private static ItemCardboardArmor conditionalNewArmor(String configName, int armorType) {
if (!BetterStorage.globalConfig.getBoolean(configName)) return null;
return new ItemCardboardArmor(armorType);
}
}
| mit |
rayue/java-game-server | jetserver/src/main/java/org/menacheri/jetserver/protocols/impl/SimpleByteArrayProtocol.java | 3272 | package org.menacheri.jetserver.protocols.impl;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
import org.menacheri.jetserver.app.PlayerSession;
import org.menacheri.jetserver.handlers.netty.ByteArrayDecoder;
import org.menacheri.jetserver.handlers.netty.ByteArrayToChannelBufferEncoder;
import org.menacheri.jetserver.protocols.AbstractNettyProtocol;
import org.menacheri.jetserver.util.NettyUtils;
import org.springframework.beans.factory.annotation.Required;
/**
* A protocol that can be used for fast paced games where operations and other
* values can be sent as bytes which then get processed and converted to actual
* java method operations. Messages with pay load like [OPCODE][PAYLOAD] will
* find this protocol the most useful.
*
* @author Abraham Menacherry
*
*/
public class SimpleByteArrayProtocol extends AbstractNettyProtocol
{
/**
* Used to retrieve the rest of the bytes after the length field is
* stripped.
*/
private ByteArrayDecoder byteArrayDecoder;
/**
* Converts a byte array to a {@link ChannelBuffer} while sending to the client.
*/
private ByteArrayToChannelBufferEncoder byteArrayToChannelBufferEncoder;
/**
* Utility handler provided by netty to add the length of the outgoing
* message to the message as a header.
*/
private LengthFieldPrepender lengthFieldPrepender;
public SimpleByteArrayProtocol()
{
super("SIMPLE_BYTE_ARRAY_PROTOCOL");
}
public SimpleByteArrayProtocol(ByteArrayDecoder byteArrayDecoder,
LengthFieldPrepender lengthFieldPrepender)
{
super("SIMPLE_BYTE_ARRAY_PROTOCOL");
this.byteArrayDecoder = byteArrayDecoder;
this.lengthFieldPrepender = lengthFieldPrepender;
}
@Override
public void applyProtocol(PlayerSession playerSession)
{
ChannelPipeline pipeline = NettyUtils
.getPipeLineOfConnection(playerSession);
// Upstream handlers or encoders (i.e towards server) are added to
// pipeline now.
pipeline.addLast("lengthDecoder", createLengthBasedFrameDecoder());
pipeline.addLast("byteArrayDecoder", byteArrayDecoder);
// Downstream handlers - Filter for data which flows from server to
// client. Note that the last handler added is actually the first
// handler for outgoing data.
pipeline.addLast("byteArrayToChannelBufferEncoder", byteArrayToChannelBufferEncoder);
pipeline.addLast("lengthFieldPrepender", lengthFieldPrepender);
}
public ByteArrayDecoder getByteArrayDecoder()
{
return byteArrayDecoder;
}
@Required
public void setByteArrayDecoder(ByteArrayDecoder byteArrayDecoder)
{
this.byteArrayDecoder = byteArrayDecoder;
}
public LengthFieldPrepender getLengthFieldPrepender()
{
return lengthFieldPrepender;
}
@Required
public void setLengthFieldPrepender(LengthFieldPrepender lengthFieldPrepender)
{
this.lengthFieldPrepender = lengthFieldPrepender;
}
public ByteArrayToChannelBufferEncoder getByteArrayToChannelBufferEncoder()
{
return byteArrayToChannelBufferEncoder;
}
@Required
public void setByteArrayToChannelBufferEncoder(
ByteArrayToChannelBufferEncoder byteArrayToChannelBufferEncoder)
{
this.byteArrayToChannelBufferEncoder = byteArrayToChannelBufferEncoder;
}
}
| mit |
Snickermicker/smarthome | bundles/automation/org.eclipse.smarthome.automation.module.core.test/src/test/java/org/eclipse/smarthome/automation/module/core/internal/provider/AnnotationActionModuleTypeProviderTest.java | 9554 | /**
* Copyright (c) 2014,2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.automation.module.core.internal.provider;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.smarthome.automation.AnnotatedActions;
import org.eclipse.smarthome.automation.Visibility;
import org.eclipse.smarthome.automation.annotation.ActionInput;
import org.eclipse.smarthome.automation.annotation.ActionOutput;
import org.eclipse.smarthome.automation.annotation.ActionScope;
import org.eclipse.smarthome.automation.annotation.RuleAction;
import org.eclipse.smarthome.automation.module.core.provider.AnnotationActionModuleTypeHelper;
import org.eclipse.smarthome.automation.module.core.provider.i18n.ModuleTypeI18nService;
import org.eclipse.smarthome.automation.type.ActionType;
import org.eclipse.smarthome.automation.type.Input;
import org.eclipse.smarthome.automation.type.ModuleType;
import org.eclipse.smarthome.automation.type.Output;
import org.eclipse.smarthome.config.core.ConfigConstants;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameter;
import org.eclipse.smarthome.config.core.ParameterOption;
import org.eclipse.smarthome.test.java.JavaTest;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for the {@link AnnotatedActionModuleTypeProvider}
*
* @author Stefan Triller - initial contribution
*
*/
public class AnnotationActionModuleTypeProviderTest extends JavaTest {
private static final String TEST_ACTION_TYPE_ID = "binding.test.testMethod";
private static final String ACTION_LABEL = "Test Label";
private static final String ACTION_DESCRIPTION = "My Description";
private static final String ACTION_INPUT1 = "input1";
private static final String ACTION_INPUT1_DESCRIPTION = "input1 description";
private static final String ACTION_INPUT1_LABEL = "input1 label";
private static final String ACTION_INPUT1_DEFAULT_VALUE = "input1 default";
private static final String ACTION_INPUT1_REFERENCE = "input1 reference";
private static final String ACTION_INPUT2 = "input2";
private static final String ACTION_OUTPUT1 = "output1";
private static final String ACTION_OUTPUT1_DESCRIPTION = "output1 description";
private static final String ACTION_OUTPUT1_LABEL = "output1 label";
private static final String ACTION_OUTPUT1_DEFAULT_VALUE = "output1 default";
private static final String ACTION_OUTPUT1_REFERENCE = "output1 reference";
private static final String ACTION_OUTPUT1_TYPE = "java.lang.Integer";
private static final String ACTION_OUTPUT2 = "output2";
private static final String ACTION_OUTPUT2_TYPE = "java.lang.String";
private ModuleTypeI18nService moduleTypeI18nService;
private AnnotatedActions actionProviderConf1;
private AnnotatedActions actionProviderConf2;
@Before
public void setUp() {
actionProviderConf1 = new TestActionProvider();
actionProviderConf2 = new TestActionProvider();
moduleTypeI18nService = mock(ModuleTypeI18nService.class);
when(moduleTypeI18nService.getModuleTypePerLocale(any(ModuleType.class), any(), any()))
.thenAnswer(i -> i.getArguments()[0]);
}
@Test
public void testMultiServiceAnnotationActions() {
AnnotatedActionModuleTypeProvider prov = new AnnotatedActionModuleTypeProvider();
prov.setModuleTypeI18nService(moduleTypeI18nService);
HashMap<String, Object> properties1 = new HashMap<String, Object>();
properties1.put(ConfigConstants.SERVICE_CONTEXT, "conf1");
prov.addActionProvider(actionProviderConf1, properties1);
Collection<String> types = prov.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TEST_ACTION_TYPE_ID));
HashMap<String, Object> properties2 = new HashMap<String, Object>();
properties2.put(ConfigConstants.SERVICE_CONTEXT, "conf2");
prov.addActionProvider(actionProviderConf2, properties2);
// we only have ONE type but TWO configurations for it
types = prov.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TEST_ACTION_TYPE_ID));
ModuleType mt = prov.getModuleType(TEST_ACTION_TYPE_ID, null);
assertTrue(mt instanceof ActionType);
ActionType at = (ActionType) mt;
assertEquals(ACTION_LABEL, at.getLabel());
assertEquals(ACTION_DESCRIPTION, at.getDescription());
assertEquals(Visibility.HIDDEN, at.getVisibility());
assertEquals(TEST_ACTION_TYPE_ID, at.getUID());
Set<String> tags = at.getTags();
assertTrue(tags.contains("tag1"));
assertTrue(tags.contains("tag2"));
List<Input> inputs = at.getInputs();
assertEquals(2, inputs.size());
for (Input in : inputs) {
if (ACTION_INPUT1.equals(in.getName())) {
assertEquals(ACTION_INPUT1_LABEL, in.getLabel());
assertEquals(ACTION_INPUT1_DEFAULT_VALUE, in.getDefaultValue());
assertEquals(ACTION_INPUT1_DESCRIPTION, in.getDescription());
assertEquals(ACTION_INPUT1_REFERENCE, in.getReference());
assertEquals(true, in.isRequired());
assertEquals("Item", in.getType());
Set<String> inputTags = in.getTags();
assertTrue(inputTags.contains("tagIn11"));
assertTrue(inputTags.contains("tagIn12"));
} else if (ACTION_INPUT2.equals(in.getName())) {
// if the annotation does not specify a type, we use the java type
assertEquals("java.lang.String", in.getType());
}
}
List<Output> outputs = at.getOutputs();
assertEquals(2, outputs.size());
for (Output o : outputs) {
if (ACTION_OUTPUT1.equals(o.getName())) {
assertEquals(ACTION_OUTPUT1_LABEL, o.getLabel());
assertEquals(ACTION_OUTPUT1_DEFAULT_VALUE, o.getDefaultValue());
assertEquals(ACTION_OUTPUT1_DESCRIPTION, o.getDescription());
assertEquals(ACTION_OUTPUT1_REFERENCE, o.getReference());
assertEquals(ACTION_OUTPUT1_TYPE, o.getType());
Set<String> outputTags = o.getTags();
assertTrue(outputTags.contains("tagOut11"));
assertTrue(outputTags.contains("tagOut12"));
} else if (ACTION_INPUT2.equals(o.getName())) {
assertEquals(ACTION_OUTPUT2_TYPE, o.getType());
}
}
// remove the first configuration
prov.removeActionProvider(actionProviderConf1, properties1);
types = prov.getTypes();
assertEquals(1, types.size());
// check of the second configuration is still valid
mt = prov.getModuleType(TEST_ACTION_TYPE_ID, null);
List<ConfigDescriptionParameter> configParams = mt.getConfigurationDescriptions();
boolean found = false;
for (ConfigDescriptionParameter cdp : configParams) {
if (AnnotationActionModuleTypeHelper.CONFIG_PARAM.equals(cdp.getName())) {
found = true;
List<ParameterOption> parameterOptions = cdp.getOptions();
assertEquals(1, parameterOptions.size());
ParameterOption po = parameterOptions.get(0);
assertEquals("conf2", po.getValue());
}
}
assertTrue(found);
// remove the second configuration and there should be none left
prov.removeActionProvider(actionProviderConf2, properties2);
types = prov.getTypes();
assertEquals(0, types.size());
mt = prov.getModuleType(TEST_ACTION_TYPE_ID, null);
assertNull(mt);
}
@ActionScope(name = "binding.test")
private class TestActionProvider implements AnnotatedActions {
@RuleAction(label = ACTION_LABEL, description = ACTION_DESCRIPTION, visibility = Visibility.HIDDEN, tags = {
"tag1", "tag2" })
public @ActionOutput(name = ACTION_OUTPUT1, type = ACTION_OUTPUT1_TYPE, description = ACTION_OUTPUT1_DESCRIPTION, label = ACTION_OUTPUT1_LABEL, defaultValue = ACTION_OUTPUT1_DEFAULT_VALUE, reference = ACTION_OUTPUT1_REFERENCE, tags = {
"tagOut11",
"tagOut12" }) @ActionOutput(name = ACTION_OUTPUT2, type = ACTION_OUTPUT2_TYPE) Map<String, Object> testMethod(
@ActionInput(name = ACTION_INPUT1, label = ACTION_INPUT1_LABEL, defaultValue = ACTION_INPUT1_DEFAULT_VALUE, description = ACTION_INPUT1_DESCRIPTION, reference = ACTION_INPUT1_REFERENCE, required = true, type = "Item", tags = {
"tagIn11", "tagIn12" }) String input1,
@ActionInput(name = ACTION_INPUT2) String input2) {
Map<String, Object> result = new HashMap<>();
result.put("output1", 23);
result.put("output2", "hello world");
return result;
}
}
}
| epl-1.0 |
cschneider/openhab | bundles/binding/org.openhab.binding.ebus/src/main/java/org/openhab/binding/ebus/internal/parser/EBusTelegramCSVWriter.java | 4605 | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.ebus.internal.parser;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.openhab.binding.ebus.internal.EBusTelegram;
import org.openhab.binding.ebus.internal.utils.EBusUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple CSV writer to analyse eBUS telegrams with a external program
*
* @author Christian Sowada
* @since 1.7.1
*/
public class EBusTelegramCSVWriter {
private static final Logger logger = LoggerFactory
.getLogger(EBusTelegramCSVWriter.class);
private BufferedWriter writer;
private FileWriter fw;
public final static String CSV_FOLDER = getUserPersistenceDataFolder() + File.separator + "ebus";
/**
* returns the path for user data
* @return
*/
static private String getUserPersistenceDataFolder() {
String progArg = System.getProperty("smarthome.userdata");
if (progArg != null) {
return progArg + File.separator + "persistence";
} else {
return "etc";
}
}
/**
* open a csv file user data
* @param filename
* @throws IOException
*/
public void openInUserData(String filename) throws IOException {
File folder = new File(EBusTelegramCSVWriter.CSV_FOLDER);
if(!folder.exists()) {
folder.mkdirs();
}
open(new File(folder, filename));
}
/**
* Opens a CSV file
* @param csvFile The file object
* @throws IOException
*/
public void open(File csvFile) throws IOException {
fw = new FileWriter(csvFile);
writer = new BufferedWriter( fw );
if (!csvFile.exists()) {
csvFile.createNewFile();
}
writer.write("Date/Time;");
writer.write("TYPE;");
writer.write("SRC;");
writer.write("DST;");
writer.write("CMD;");
writer.write("LEN;");
writer.write("DATA;");
writer.write("CRC;");
writer.write("ACK;");
writer.write("S LEN;");
writer.write("S DATA;");
writer.write("S CRC;");
writer.write("COMMENT");
writer.newLine();
writer.flush();
}
public void close() throws IOException {
if(writer != null) {
writer.flush();
writer.close();
}
if(fw != null)
fw.close();
}
/**
* Writes a eBUS telegram to the CSV file
* @param telegram
* @param comment
* @throws IOException
*/
public synchronized void writeTelegram(EBusTelegram telegram, String comment) {
try {
if(writer == null)
return;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
writer.write(df.format(date));
writer.write(";");
writer.write('"'+EBusUtils.toHexDumpString(telegram.getType())+'"');
writer.write(";");
writer.write('"'+EBusUtils.toHexDumpString(telegram.getSource())+'"');
writer.write(";");
writer.write('"'+EBusUtils.toHexDumpString(telegram.getDestination())+'"');
writer.write(";");
short u = telegram.getCommand();
byte x = (byte) u;
byte y = (byte) (u>>8);
writer.write(EBusUtils.toHexDumpString(y));
writer.write(" ");
writer.write(EBusUtils.toHexDumpString(x));
writer.write(";");
writer.write('"'+EBusUtils.toHexDumpString((byte) telegram.getDataLen())+'"');
writer.write(";");
writer.write(EBusUtils.toHexDumpString(telegram.getData()).toString());
writer.write(";");
writer.write('"'+EBusUtils.toHexDumpString(telegram.getCRC())+'"');
writer.write(";");
if(telegram.getType() != EBusTelegram.TYPE_MASTER_SLAVE) {
writer.write(";");
writer.write(";");
writer.write(";");
writer.write(";");
} else {
writer.write('"'+"00"+'"');
writer.write(";");
writer.write('"'+EBusUtils.toHexDumpString((byte)telegram.getSlaveDataLen())+'"');
writer.write(";");
writer.write(EBusUtils.toHexDumpString(telegram.getSlaveData()).toString());
writer.write(";");
writer.write('"'+EBusUtils.toHexDumpString((byte)telegram.getSlaveCRC())+'"');
writer.write(";");
}
writer.write(comment);
writer.newLine();
writer.flush();
} catch (IOException e) {
logger.error("error", e);
}
}
}
| epl-1.0 |
opennars/opennars_googlecode | open-nars/src/com/googlecode/opennars/inference/CompositionalRules.java | 18126 | /*
* CompositionalRules.java
*
* Copyright (C) 2008 Pei Wang
*
* This file is part of Open-NARS.
*
* Open-NARS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* Open-NARS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package com.googlecode.opennars.inference;
import com.googlecode.opennars.entity.*;
import com.googlecode.opennars.language.*;
import com.googlecode.opennars.main.*;
import com.googlecode.opennars.parser.*;
/**
* Compound term composition and decomposition rules, with two premises.
* <p>
* Forward inference only, except the last rule (abdDepOuter) can also be used backward.
*/
public class CompositionalRules {
private Memory memory;
private BudgetFunctions budgetfunctions;
public CompositionalRules(Memory memory) {
this.memory = memory;
this.budgetfunctions = new BudgetFunctions(memory);
}
/* -------------------- intersections and differences -------------------- */
/**
* {<S ==> M>, <P ==> M>} |- {<(S|P) ==> M>, <(S&P) ==> M>, <(S-P) ==> M>, <(P-S) ==> M>}
*
* @param sentence The first premise
* @param belief The second premise
* @param index The location of the shared term
*/
void composeCompound(Sentence sentence, Judgement belief, int index) {
if (!sentence.isJudgment())
return; // forward only
Statement content1 = (Statement) sentence.getContent();
Statement content2 = (Statement) belief.getContent();
if (content1.getClass() != content2.getClass())
return;
if (content1.getTemporalOrder() != content2.getTemporalOrder())
return;
Term component1, component2;
component1 = content1.componentAt(1 - index);
component2 = content2.componentAt(1 - index);
Term component = content1.componentAt(index);
if ((component1 instanceof CompoundTerm) && ((CompoundTerm) component1).containAllComponents(component2)) {
decomposeCompound((CompoundTerm) component1, component2, component, index, true);
return;
} else if ((component2 instanceof CompoundTerm) && ((CompoundTerm) component2).containAllComponents(component1)) {
decomposeCompound((CompoundTerm) component2, component1, component, index, false);
return;
}
Term t1 = null;
Term t2 = null;
Term t3 = null;
Term t4 = null;
TruthValue v1 = sentence.getTruth();
TruthValue v2 = belief.getTruth();
if (index == 0) {
if (content1 instanceof Inheritance) {
t1 = IntersectionInt.make(component1, component2, this.memory);
t2 = IntersectionExt.make(component1, component2, this.memory);
t3 = DifferenceExt.make(component1, component2, this.memory);
t4 = DifferenceExt.make(component2, component1, this.memory);
} else if (content1 instanceof Implication) {
t1 = Disjunction.make(component1, component2, this.memory);
t2 = Conjunction.make(component1, component2, this.memory);
t3 = Conjunction.make(component1, Negation.make(component2, this.memory), this.memory);
t4 = Conjunction.make(component2, Negation.make(component1, this.memory), this.memory);
}
processComposed(content1, component, t1, TruthFunctions.union(v1, v2));
processComposed(content1, component, t2, TruthFunctions.intersection(v1, v2));
processComposed(content1, component, t3, TruthFunctions.difference(v1, v2));
processComposed(content1, component, t4, TruthFunctions.difference(v2, v1));
if (content1.isConstant())
introVarDepOuter(content1, content2, index);
} else {
if (content1 instanceof Inheritance) {
t1 = IntersectionExt.make(component1, component2, this.memory);
t2 = IntersectionInt.make(component1, component2, this.memory);
t3 = DifferenceInt.make(component1, component2, this.memory);
t4 = DifferenceInt.make(component2, component1, this.memory);
} else if (content1 instanceof Implication) {
t1 = Conjunction.make(component1, component2, this.memory);
t2 = Disjunction.make(component1, component2, this.memory);
t3 = Disjunction.make(component1, Negation.make(component2, this.memory), this.memory);
t4 = Disjunction.make(component2, Negation.make(component1, this.memory), this.memory);
}
processComposed(content1, t1, component, TruthFunctions.union(v1, v2));
processComposed(content1, t2, component, TruthFunctions.intersection(v1, v2));
processComposed(content1, t3, component, TruthFunctions.difference(v1, v2));
processComposed(content1, t4, component, TruthFunctions.difference(v2, v1));
if (content1.isConstant())
introVarDepOuter(content1, content2, index);
}
}
/**
* Finish composing compound term
* @param statement Type of the content
* @param subject Subject of content
* @param predicate Predicate of content
* @param truth TruthValue of the content
*/
private void processComposed(Statement statement, Term subject, Term predicate, TruthValue truth) {
if ((subject == null) || (predicate == null))
return;
Term content = Statement.make(statement, subject, predicate, this.memory);
if ((content == null) || content.equals(statement) || content.equals(this.memory.currentBelief.getContent()))
return;
BudgetValue budget = this.budgetfunctions.compoundForward(truth, content);
this.memory.doublePremiseTask(budget, content, truth);
}
/**
* {<(S|P) ==> M>, <P ==> M>} |- <S ==> M>
* @param compound The compound term to be decomposed
* @param component The part of the compound to be removed
* @param term1 The other term in the content
* @param index The location of the shared term: 0 for subject, 1 for predicate
* @param compoundTask Whether the compound comes from the task
*/
private void decomposeCompound(CompoundTerm compound, Term component, Term term1, int index, boolean compoundTask) {
Term term2 = CompoundTerm.reduceComponents(compound, component, this.memory);
if (term2 == null)
return;
Task task = this.memory.currentTask;
Sentence sentence = task.getSentence();
Judgement belief = this.memory.currentBelief;
Statement oldContent = (Statement) task.getContent();
TruthValue v1, v2;
if (compoundTask) {
v1 = sentence.getTruth();
v2 = belief.getTruth();
} else {
v1 = belief.getTruth();
v2 = sentence.getTruth();
}
TruthValue truth = null;
Term content;
if (index == 0) {
content = Statement.make(oldContent, term1, term2, this.memory);
if (content == null)
return;
if (oldContent instanceof Inheritance) {
if (compound instanceof IntersectionExt) {
truth = TruthFunctions.reduceConjunction(v1, v2);
} else if (compound instanceof IntersectionInt) {
truth = TruthFunctions.reduceDisjunction(v1, v2);
} else if ((compound instanceof SetInt) && (component instanceof SetInt)) {
truth = TruthFunctions.reduceConjunction(v1, v2);
} else if ((compound instanceof SetExt) && (component instanceof SetExt)) {
truth = TruthFunctions.reduceDisjunction(v1, v2);
} else if (compound instanceof DifferenceExt) {
if (compound.componentAt(0).equals(component)) {
truth = TruthFunctions.reduceDisjunction(v2, v1);
} else {
truth = TruthFunctions.reduceConjunctionNeg(v1, v2);
}
}
} else if (oldContent instanceof Implication) {
if (compound instanceof Conjunction) {
truth = TruthFunctions.reduceConjunction(v1, v2);
} else if (compound instanceof Disjunction) {
truth = TruthFunctions.reduceDisjunction(v1, v2);
}
}
} else {
content = Statement.make(oldContent, term2, term1, this.memory);
if (content == null)
return;
if (oldContent instanceof Inheritance) {
if (compound instanceof IntersectionInt) {
truth = TruthFunctions.reduceConjunction(v1, v2);
} else if (compound instanceof IntersectionExt) {
truth = TruthFunctions.reduceDisjunction(v1, v2);
} else if ((compound instanceof SetExt) && (component instanceof SetExt)) {
truth = TruthFunctions.reduceConjunction(v1, v2);
} else if ((compound instanceof SetInt) && (component instanceof SetInt)) {
truth = TruthFunctions.reduceDisjunction(v1, v2);
} else if (compound instanceof DifferenceInt) {
if (compound.componentAt(1).equals(component)) {
truth = TruthFunctions.reduceDisjunction(v2, v1);
} else {
truth = TruthFunctions.reduceConjunctionNeg(v1, v2);
}
}
} else if (oldContent instanceof Implication) {
if (compound instanceof Disjunction) {
truth = TruthFunctions.reduceConjunction(v1, v2);
} else if (compound instanceof Conjunction) {
truth = TruthFunctions.reduceDisjunction(v1, v2);
}
}
}
BudgetValue budget = this.budgetfunctions.compoundForward(truth, content);
this.memory.doublePremiseTask(budget, content, truth);
}
/**
* {(||, S, P), P} |- S
* @param compound The compound term to be decomposed
* @param component The part of the compound to be removed
* @param compoundTask Whether the compound comes from the task
*/
void decomposeStatement(CompoundTerm compound, Term component, boolean compoundTask) {
Task task = this.memory.currentTask;
Sentence sentence = task.getSentence();
if (!sentence.isJudgment())
return;
Judgement belief = this.memory.currentBelief;
Term content = CompoundTerm.reduceComponents(compound, component, this.memory);
if (content == null)
return;
TruthValue v1, v2;
if (compoundTask) {
v1 = sentence.getTruth();
v2 = belief.getTruth();
} else {
v1 = belief.getTruth();
v2 = sentence.getTruth();
}
TruthValue truth = null;
if (compound instanceof Conjunction) {
if (sentence instanceof Goal) {
if (compoundTask)
truth = TruthFunctions.reduceDisjunction(v1, v2);
else
return;
} else if (sentence instanceof Judgement)
truth = TruthFunctions.reduceConjunction(v1, v2);
} else if (compound instanceof Disjunction) {
if (sentence instanceof Goal) {
if (compoundTask)
truth = TruthFunctions.reduceConjunction(v1, v2);
else
return;
} else if (sentence instanceof Judgement)
truth = TruthFunctions.reduceDisjunction(v1, v2);
} else
return;
BudgetValue budget = this.budgetfunctions.compoundForward(truth, content);
this.memory.doublePremiseTask(budget, content, truth);
}
/* ---------------- dependent variable and conjunction ---------------- */
/**
* {<M --> S>, <M --> P>} |- (&&, <#x() --> S>, <#x() --> P>>
* @param premise1 The first premise <M --> P>
* @param premise2 The second premise <M --> P>
* @param index The location of the shared term: 0 for subject, 1 for predicate
*/
private Conjunction introVarDep(Statement premise1, Statement premise2, int index) {
Statement state1, state2;
Variable v1 = new Variable(Symbols.VARIABLE_TAG + "0()");
Variable v2 = new Variable(Symbols.VARIABLE_TAG + "0()");
if (index == 0) {
state1 = Statement.make(premise1, v1, premise1.getPredicate(), this.memory);
state2 = Statement.make(premise2, v2, premise2.getPredicate(), this.memory);
} else {
state1 = Statement.make(premise1, premise1.getSubject(), v1, this.memory);
state2 = Statement.make(premise2, premise2.getSubject(), v2, this.memory);
}
Conjunction content = (Conjunction) Conjunction.make(state1, state2, this.memory);
return content;
}
/**
* Introduce a dependent variable in an outer-layer conjunction
* @param premise1 The first premise <M --> S>
* @param premise2 The second premise <M --> P>
* @param index The location of the shared term: 0 for subject, 1 for predicate
*/
private void introVarDepOuter(Statement premise1, Statement premise2, int index) {
Term content = introVarDep(premise1, premise2, index);
TruthValue v1 = this.memory.currentTask.getSentence().getTruth();
TruthValue v2 = this.memory.currentBelief.getTruth();
TruthValue truth = TruthFunctions.intersection(v1, v2);
BudgetValue budget = this.budgetfunctions.compoundForward(truth, content);
this.memory.doublePremiseTask(budget, content, truth);
}
/**
* Introduce a dependent variable in an inner-layer conjunction
* @param compound The compound containing the first premise
* @param component The first premise <M --> S>
* @param premise The second premise <M --> P>
*/
void introVarDepInner(CompoundTerm compound, Term component, Term premise) {
if (!(component instanceof Statement) || !(component.getClass() == premise.getClass()))
return;
Statement premise1 = (Statement) premise;
Statement premise2 = (Statement) component;
int index;
if (premise1.getSubject().equals(premise2.getSubject()))
index = 0;
else if (premise1.getPredicate().equals(premise2.getPredicate()))
index = 1;
else
return;
Term innerContent = introVarDep(premise1, premise2, index);
if (innerContent == null)
return;
Task task = this.memory.currentTask;
Sentence sentence = task.getSentence();
Judgement belief = this.memory.currentBelief;
Term content = task.getContent();
if (compound instanceof Implication)
content = Statement.make((Statement) content, compound.componentAt(0), innerContent, this.memory);
else if (compound instanceof Conjunction)
content = CompoundTerm.replaceComponent(compound, component, innerContent, this.memory);
TruthValue truth = null;
if (sentence instanceof Goal)
truth = TruthFunctions.intersection(belief.getTruth(), sentence.getTruth()); // to be revised
else if (sentence instanceof Judgement)
truth = TruthFunctions.intersection(belief.getTruth(), sentence.getTruth());
else
return; // don't do it for questions
BudgetValue budget = this.budgetfunctions.compoundForward(truth, content);
this.memory.doublePremiseTask(budget, content, truth);
}
/**
* {(&&, <#x() --> S>, <#x() --> P>>, <M --> P>} |- <M --> S>
* @param compound The compound term to be decomposed
* @param component The part of the compound to be removed
* @param compoundTask Whether the compound comes from the task
*/
void abdVarDepOuter(CompoundTerm compound, Term component, boolean compoundTask) {
Term content = CompoundTerm.reduceComponents(compound, component, this.memory);
Task task = this.memory.currentTask;
Sentence sentence = task.getSentence();
Judgement belief = this.memory.currentBelief;
TruthValue v1 = sentence.getTruth();
TruthValue v2 = belief.getTruth();
TruthValue truth = null;
BudgetValue budget;
if (sentence instanceof Question)
budget = (compoundTask ? this.budgetfunctions.backward(v2) : this.budgetfunctions.backwardWeak(v2));
else {
if (sentence instanceof Goal)
truth = (compoundTask ? TruthFunctions.desireStrong(v1, v2) : TruthFunctions.desireWeak(v1, v2));
else
truth = (compoundTask ? TruthFunctions.existAnalogy(v1, v2) : TruthFunctions.existAnalogy(v2, v1));
budget = this.budgetfunctions.compoundForward(truth, content);
}
this.memory.doublePremiseTask(budget, content, truth);
}
}
| gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/jdwp/Event/THREAD_START/thrstart001/TestDescription.java | 3130 | /*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
*
* @summary converted from VM Testbase nsk/jdwp/Event/THREAD_START/thrstart001.
* VM Testbase keywords: [quick, jpda, jdwp]
* VM Testbase readme:
* DESCRIPTION
* This test performs checking for
* command set: Event
* command: Composite
* command set: EventRequest
* command: Set, Clear
* event kind: THREAD_START
* Test checks that
* 1) debuggee successfully creates THREAD_START event request
* for particular threadID
* 2) expected THREAD_START event is received when the thread
* started into debuggee
* 3) debuggee successfully removes event request
* Test consists of two compoments:
* debugger: thrstart001
* debuggee: thrstart001a
* First, debugger uses nsk.share support classes to launch debuggee,
* and obtains Transport object, that represents JDWP transport channel.
* Next, debugger waits for tested class loaded and breakpoint reached.
* Then debugger gets threadID from the class static field and makes
* THREAD_START event request for this thread,
* When event is received debugger checks if the received event
* is for this thread and has correct attributes. Then debugger
* removes event request.
* Finally, debugger disconnects debuggee, waits for it exited
* and exits too with proper exit code.
* COMMENTS
* Test was fixed due to test bug:
* 4797978 TEST_BUG: potential race condition in a number of JDWP tests
*
* @library /vmTestbase /test/hotspot/jtreg/vmTestbase
* /test/lib
* @run driver jdk.test.lib.FileInstaller . .
* @build nsk.jdwp.Event.THREAD_START.thrstart001
* nsk.jdwp.Event.THREAD_START.thrstart001a
* @run main/othervm PropertyResolvingWrapper
* nsk.jdwp.Event.THREAD_START.thrstart001
* -arch=${os.family}-${os.simpleArch}
* -verbose
* -waittime=5
* -debugee.vmkind=java
* -transport.address=dynamic
* -debugee.vmkeys="${test.vm.opts} ${test.java.opts}"
*/
| gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/jdi/Type/hashCode/hashcode001/TestDescription.java | 2643 | /*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
*
* @summary converted from VM Testbase nsk/jdi/Type/hashCode/hashcode001.
* VM Testbase keywords: [quick, jpda, jdi]
* VM Testbase readme:
* DESCRIPTION:
* The test for public hashCode() method of an implementing class of
* com.sun.jdi.Type interface.
* The test checks an assertion cited from spec for hashCode() method of
* java.lang.Object class:
* The general contract of hashCode is:
* - Whenever it is invoked on the same object more than once during
* an execution of a Java application, the hashCode method must
* consistently return the same integer, provided no information used
* in equals comparisons on the object is modified.
* ...
* - If two objects are equal according to the equals(Object) method,
* then calling the hashCode method on each of the two objects must
* produce the same integer result.
* COMMENTS:
* The test is aimed to increase jdi source code coverage and checks
* the code which was not yet covered by previous tests for Type
* interface. The coverage analysis was done for jdk1.4.0-b92 build.
*
* @library /vmTestbase
* /test/lib
* @run driver jdk.test.lib.FileInstaller . .
* @build nsk.jdi.Type.hashCode.hashcode001
* nsk.jdi.Type.hashCode.hashcode001a
* @run main/othervm PropertyResolvingWrapper
* nsk.jdi.Type.hashCode.hashcode001
* -verbose
* -arch=${os.family}-${os.simpleArch}
* -waittime=5
* -debugee.vmkind=java
* -transport.address=dynamic
* "-debugee.vmkeys=${test.vm.opts} ${test.java.opts}"
*/
| gpl-2.0 |
bhutchinson/kfs | kfs-purap/src/main/java/org/kuali/kfs/module/purap/document/validation/impl/PurchaseOrderAccountingLineAccessibleValidation.java | 2149 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.purap.document.validation.impl;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent;
/**
* A validation that checks whether the given accounting line is accessible to the given user or not
*/
public class PurchaseOrderAccountingLineAccessibleValidation extends PurchasingAccountsPayableAccountingLineAccessibleValidation {
/**
* Validates that the given accounting line is accessible for editing by the current user.
* <strong>This method expects a document as the first parameter and an accounting line as the second</strong>
* @see org.kuali.kfs.sys.document.validation.Validation#validate(java.lang.Object[])
*/
public boolean validate(AttributedDocumentEvent event) {
PurchaseOrderDocument financialDocument = (PurchaseOrderDocument)event.getDocument();
if (financialDocument.isDocumentStoppedInRouteNode(PurapConstants.PurchaseOrderStatuses.NODE_CONTRACT_MANAGEMENT)) {
// DO NOTHING: do not check that user owns acct lines; at this level, approvers can edit all detail on PO
return true;
}
else {
return super.validate(event);
}
}
}
| agpl-3.0 |
danieljue/beast-mcmc | src/dr/math/distributions/BifractionalDiffusionDensity.java | 16092 | package dr.math.distributions;
import dr.math.UnivariateFunction;
import cern.jet.stat.Gamma;
/**
* @author Marc Suchard
* <p/>
* **
* Most of the following functions come from:
* <p/>
* R Gorenflo, A Iskenderov and Y Luchko (2000) Mapping between solutions of fractional diffusion-wave equations.
* Fractional Calculus and Applied Analysis, 3, 75 - 86
* <p/>
* Also see:
* F. Mainardi and G. Pagnini (2003) The Wright functions as solutions of the time-fractional diffusion equation.
* Applied Mathematics and Computation, 141, pages?
*
*
* Need to read: http://www.hindawi.com/journals/ijde/2010/104505.html and http://www1.tfh-berlin.de/~luchko/papers/Luchko_111.pdf
*/
public class BifractionalDiffusionDensity implements Distribution {
public BifractionalDiffusionDensity(double v, double alpha, double beta) {
this.v = v;
this.alpha = alpha;
this.beta = beta;
coefficients = constructBifractionalDiffusionCoefficients(alpha, beta);
}
public BifractionalDiffusionDensity(double alpha, double beta) {
this(1.0, alpha, beta);
}
/**
* probability density function of the distribution
*
* @param x argument
* @return pdf value
*/
public double pdf(double x) {
return pdf(x, v);
}
public double pdf(double x, double v) {
return pdf(x, v, alpha, beta, coefficients);
}
/**
* the natural log of the probability density function of the distribution
*
* @param x argument
* @return log pdf value
*/
public double logPdf(double x) {
return logPdf(x, v, alpha, beta, coefficients);
}
/**
* cumulative density function of the distribution
*
* @param x argument
* @return cdf value
*/
public double cdf(double x) {
throw new RuntimeException("Not yet implemented");
}
/**
* quantile (inverse cumulative density function) of the distribution
*
* @param y argument
* @return icdf value
*/
public double quantile(double y) {
throw new RuntimeException("Not yet implemented");
}
/**
* mean of the distribution
*
* @return mean
*/
public double mean() {
throw new RuntimeException("Not yet implemented");
}
/**
* variance of the distribution
*
* @return variance
*/
public double variance() {
throw new RuntimeException("Not yet implemented");
}
/**
* @return a probability density function representing this distribution
*/
public UnivariateFunction getProbabilityDensityFunction() {
throw new RuntimeException("Not yet implemented");
}
public static double logPdf(double x, double v, double alpha, double beta) {
return Math.log(pdf(x, v, alpha, beta));
}
public static double logPdf(double x, double v, double alpha, double beta, double[][][] coefficients) {
return Math.log(pdf(x, v, alpha, beta, coefficients));
}
// /*
// * Taken from: Saichev AI and Zaslavsky GM (1997) Fractional kinetic equations: solutions and applications.
// * Chaos, 7, 753-764
// * @param x evaluation point
// * @param t evaluation time
// * @param alpha coefficient
// * @param beta coefficient
// * @return probability density
// */
//
// public static double logPdf(double x, double t, double alpha, double beta) {
// final double mu = beta / alpha;
// final double absX = Math.abs(x);
// final double absY = absX / Math.pow(t,mu);
// double density = 0;
// double incr = Double.MAX_VALUE;
// int m = 1; // 0th term = 0 \propto cos(pi/2)
// int sign = -1;
//
// while (Math.abs(incr) > eps && m < maxK) {
// incr = sign / Math.pow(absY, m * alpha)
// * Gamma.gamma(m * alpha + 1)
// / Gamma.gamma(m * beta + 1)
// * Math.cos(halfPI * (m * alpha + 1));
// density += incr;
// sign *= -1;
// m++;
// }
//
// return Math.log(density / (Math.PI * absX));
// }
static class SignedDouble {
double x;
boolean positive;
SignedDouble(double x, boolean positive) {
this.x = x;
this.positive = positive;
}
}
public static SignedDouble logGamma(double z) {
// To extend the gamma function to negative (non-integer) numbers, apply the relationship
// \Gamma(z) = \frac{ \Gamma(z+n) }{ z(z+1)\cdots(z+n-1),
// by choosing n such that z+n is positive
if (z > 0) {
return new SignedDouble(Gamma.logGamma(z), true);
}
int n = ((int) -z);
if (z + n == 0.0) {
return new SignedDouble(Double.NaN, true); // Zero and the negative integers are diverging poles
}
n++;
boolean positive = (n % 2 == 0);
return new SignedDouble(Gamma.logGamma(z + n) - Gamma.logGamma(-z + 1) + Gamma.logGamma(-z - n + 1), positive);
}
public static double gamma(double z) {
// To extend the gamma function to negative (non-integer) numbers, apply the relationship
// \Gamma(z) = \frac{ \Gamma(z+n) }{ z(z+1)\cdots(z+n-1),
// by choosing n such that z+n is positive
if (z > 0.0) {
return Gamma.gamma(z);
}
int n = ((int) -z);
if (z+n == 0.0) {
return Double.NaN; // Zero and the negative integers are diverging poles
}
n++;
boolean positive = (n % 2 == 0);
double result = Gamma.gamma(z + n) / Gamma.gamma(-z + 1) * Gamma.gamma(-z - n + 1);
if (!positive) result *= -1;
return result;
}
// The following comments out functions may be faster than using the generalized Wright function.
// Keep for comparison
//
// public static double infiniteSumAlphaGreaterThanBeta1(double z, double alpha, double beta) {
// double sum = 0;
// int k = 0;
// boolean isPositive = true;
//
// double incr = Double.MAX_VALUE;
// while (//(Math.abs(incr) > 1E-20) &&
// (k < maxK)) {
//
// double x1, x2, x3;
// x1 = gamma(0.5 - 0.5 * alpha - 0.5 * alpha * k);
// if (!Double.isNaN(x1)) {
// incr = x1;
// } else {
// System.err.println("Big problem!");
// System.exit(-1);
// }
// x2 = gamma(1.0 - beta - beta * k);
// if (!Double.isNaN(x2)) {
// incr /= x2;
// } else {
// incr = 0;
// }
// x3 = gamma(0.5 * alpha + 0.5 * alpha * k);
// if (!Double.isNaN(x3)) {
// incr /= x3;
// } else {
// incr = 0;
// }
// incr *= Math.pow(z, k);
// if (isPositive) {
// sum += incr;
// } else {
// sum -= incr;
// }
// isPositive = !isPositive;
// k++;
// }
// return sum;
// }
//
// public static double infiniteSumAlphaGreaterThanBeta2(double z, double alpha, double beta) {
// double sum = 0;
// int m = 0;
// boolean isPositive = true;
//
// double incr = Double.MAX_VALUE;
// while (// (Math.abs(incr) > 1E-20) &&
// (m < maxK)) {
//
// double x1, x2, x3, x4;
//
// x1 = gamma(1.0 / alpha + 2.0 / alpha * m);
// if (!Double.isNaN(x1)) {
// incr = x1;
// } else {
// System.err.println("Big problem!");
// System.exit(-1);
// }
// x2 = gamma(1.0 - 1.0 / alpha - 2.0 / alpha * m);
// if (!Double.isNaN(x2)) {
// incr *= x2;
// } else {
// System.err.println("Big problem!");
// System.exit(-1);
// }
// x3 = gamma(0.5 + m);
// if (!Double.isNaN(x3)) {
// incr /= x3;
// } else {
// incr = 0;
// }
// x4 = gamma(1.0 - beta / alpha - 2 * beta / alpha * m);
// if (!Double.isNaN(x4)) {
// incr /= x4;
// } else {
// incr = 0;
// }
// incr /= gamma(m + 1);
// incr *= Math.pow(z, m);
// if (isPositive) {
// sum += incr;
// } else {
// sum -= incr;
// }
// isPositive = !isPositive;
// m++;
//
// }
// return sum;
// }
/*
* Taken from Equation (17) in Gorenflo, Iskenderov and Luchko (2000)
*/
private static double evaluateGreensFunctionAtZero(double t, double alpha, double beta) {
if (beta == 1) {
final double oneOverAlpha = 1.0 / alpha;
return gamma(oneOverAlpha) / (Math.PI * alpha * Math.pow(t, oneOverAlpha));
} else {
final double betaOverAlpha = beta / alpha;
return 1.0 / (alpha * Math.pow(t, betaOverAlpha) * Math.sin(Math.PI / alpha) * gamma(1.0 - betaOverAlpha));
}
}
/*
* Taken from Equation (20) in Gorenflo, Iskenderov and Luchko (2000)
*/
private static double evaluateGreensFunctionAlphaEqualsBeta(double x, double t, double alpha) {
final double absX = Math.abs(x);
final double twoAlpha = 2.0 * alpha;
final double tPowAlpha = Math.pow(t, alpha);
final double piHalfAlpha = 0.5 * Math.PI * alpha;
double green = Math.pow(absX, alpha - 1.0) * tPowAlpha * Math.sin(piHalfAlpha) /
(Math.pow(t, twoAlpha) + 2 * Math.pow(absX, alpha) * tPowAlpha * Math.cos(piHalfAlpha)
+ Math.pow(absX, twoAlpha));
return oneOverPi * green;
}
/*
* Taken from Equation (18) in Gorenflo, Iskenderov and Luchko (2000)
*/
private static double evaluateGreensFunctionBetaGreaterThanAlpha(double x, double t, double alpha, double beta,
double[][][] coefficients) {
double z = Math.pow(2.0, alpha) * Math.pow(t, beta) / Math.pow(Math.abs(x), alpha);
return oneOverSqrtPi / Math.sqrt(Math.abs(x)) * generalizedWrightFunction(-z, coefficients[0], coefficients[1]);
}
/*
* Taken from Equation (19) in Gorenflo, Iskenderov and Luchko (2000)
*/
private static double evaluateGreensFunctionAlphaGreaterThanBeta(double x, double t, double alpha, double beta,
double[][][] coefficients) {
double z1 = Math.pow(Math.abs(x),alpha) / (Math.pow(2,alpha) * Math.pow(t, beta));
double z2 = x * x / (4.0 * Math.pow(t, 2 * beta / alpha));
double green1 = oneOverSqrtPi * Math.pow(Math.abs(x), alpha - 1.0) /
(Math.pow(2,alpha) * Math.pow(t, beta)) *
generalizedWrightFunction(-z1, coefficients[2], coefficients[3]);
double green2 = oneOverSqrtPi / (alpha * Math.pow(t, beta/alpha)) *
generalizedWrightFunction(-z2, coefficients[4], coefficients[5]);
return green1 + green2;
}
public static double pdf(double x, double v, double alpha, double beta) {
return pdf(x, v, alpha, beta, null);
}
public static double pdf(double x, double v, double alpha, double beta, double[][][] coefficients) {
final double t = 0.5 * v;
if (x == 0) {
return evaluateGreensFunctionAtZero(t, alpha, beta);
}
if (alpha == beta) {
return evaluateGreensFunctionAlphaEqualsBeta(x, t, alpha);
}
if (coefficients == null) {
coefficients = constructBifractionalDiffusionCoefficients(alpha, beta);
}
if (alpha > beta) {
return evaluateGreensFunctionAlphaGreaterThanBeta(x, t, alpha, beta, coefficients);
} else {
return evaluateGreensFunctionBetaGreaterThanAlpha(x, t, alpha, beta, coefficients);
}
}
/*
* Helper function to construct coefficients for generalized Wright function
*/
public static double[][][] constructBifractionalDiffusionCoefficients(double alpha, double beta) {
double[][][] coefficients = new double[6][][];
// coefficients[0:1][][] : Greens function beta > alpha
coefficients[0] = new double[][]{{0.5, alpha / 2.0}, {1.0, 1.0}};
coefficients[1] = new double[][]{{1.0, beta}, {0.0, -alpha / 2.0}};
// coefficients[2:3][][] : Greens function #1 alpha > beta
coefficients[2] = new double[][]{{0.5 - alpha / 2.0, -alpha / 2.0}, {1.0, 1.0}};
coefficients[3] = new double[][]{{1.0 - beta, -beta}, {alpha / 2.0, alpha / 2.0}};
// coefficients[4:5][][] : Greens function #2 alpha > beta
coefficients[4] = new double[][]{{1.0 / alpha, 2.0 / alpha}, {1.0 - 1.0 / alpha, -2.0 / alpha}};
coefficients[5] = new double[][]{{0.5, 1.0}, {1.0 - beta / alpha, -2.0 * beta / alpha}};
return coefficients;
}
public static double generalizedWrightFunction(double z, double[][] aAp, double[][] bBq) {
final int p = aAp.length;
final int q = bBq.length;
double sum = 0.0;
double incr;
double zPowK = 1.0;
int k = 0;
while (// incr > eps &&
k < maxK) {
incr = 1;
for (int i = 0; i < p; i++) {
final double[] aAi = aAp[i];
double x = gamma(aAi[0] + aAi[1] * k); // TODO Precompute these factors
if (!Double.isNaN(x)) {
incr *= x;
} else {
incr = Double.NaN;
}
}
for (int i = 0; i < q; i++) {
final double[] bBi = bBq[i];
double x = gamma(bBi[0] + bBi[1] * k); // TODO Precompute these factors
if (!Double.isNaN(x)) {
incr /= x;
} else {
incr = 0.0;
}
}
incr /= gamma(k+1); // k! TODO Precompute these factors
incr *= zPowK;
sum += incr;
// Get ready for next loop
zPowK *= z;
k++;
}
return sum;
}
public static void main(String[] arg) {
double alpha = 2.0;
double beta = 0.8;
double z1 = -2.34;
SignedDouble result = logGamma(z1);
System.err.println("logGamma("+z1+") = "+result.x+" "+(result.positive ? "(+)" : "(-)"));
System.err.println("gamma("+z1+") = "+ gamma(z1));
System.err.println("gamma(-2.0) = "+gamma(-2.0));
System.err.println("");
double var = 4.0;
double t = 0.5 * var;
double x = 1.0;
double[][][] coefficients = constructBifractionalDiffusionCoefficients(alpha, beta);
System.err.println("p(x = "+x+", v = "+var+") = " + evaluateGreensFunctionAlphaGreaterThanBeta(x, t, alpha,
beta, coefficients));
alpha = 0.7;
beta = 1.4;
coefficients = constructBifractionalDiffusionCoefficients(alpha, beta);
// System.err.println("p(x = "+x+", v = "+var+") = " + evaluateGreensFunctionBetaGreaterThanAlpha(x, t, alpha, beta));
System.err.println("p(x = "+x+", v = "+var+") = " + evaluateGreensFunctionBetaGreaterThanAlpha(x, t, alpha,
beta, coefficients));
}
private static double oneOverSqrtPi = 1.0 / Math.sqrt(Math.PI);
private static double oneOverPi = 1.0 / Math.PI;
public static final int maxK = 50;
private double alpha;
private double beta;
private double v;
private double[][][] coefficients;
} | lgpl-2.1 |
john-difool/pfff | data/java_stdlib/classpath_bis/org.objectweb.asm.signature.java | 250 | package org.objectweb.asm.signature;
class SignatureWriter {
int argumentStack;
int hasParameters;
int hasFormals;
int buf;
}
class SignatureVisitor {
int INSTANCEOF;
int SUPER;
int EXTENDS;
}
class SignatureReader {
int signature;
}
| lgpl-2.1 |
gytis/narayana | qa/tests/src/org/jboss/jbossts/qa/CrashRecovery05Servers/Server04.java | 3315 | /*
* JBoss, Home of Professional Open Source
* Copyright 2007, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2005-2006,
* @author JBoss Inc.
*/
//
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
//
// Arjuna Technologies Ltd.,
// Newcastle upon Tyne,
// Tyne and Wear,
// UK
//
package org.jboss.jbossts.qa.CrashRecovery05Servers;
/*
* Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved.
*
* HP Arjuna Labs,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: Server04.java,v 1.4 2003/07/15 15:33:11 jcoleman Exp $
*/
/*
* Try to get around the differences between Ansi CPP and
* K&R cpp with concatenation.
*/
/*
* Copyright (C) 1999-2001 by HP Bluestone Software, Inc. All rights Reserved.
*
* HP Arjuna Labs,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: Server04.java,v 1.4 2003/07/15 15:33:11 jcoleman Exp $
*/
import org.jboss.jbossts.qa.CrashRecovery05.*;
import org.jboss.jbossts.qa.CrashRecovery05Impls.AfterCrashServiceImpl01;
import org.jboss.jbossts.qa.Utils.OAInterface;
import org.jboss.jbossts.qa.Utils.ORBInterface;
import org.jboss.jbossts.qa.Utils.ServerIORStore;
public class Server04
{
public static void main(String args[])
{
try
{
if (ORBInterface.getORB() == null) {
ORBInterface.initORB(args, null);
OAInterface.initOA();
}
AfterCrashServiceImpl01 afterCrashServiceImpl1 = new AfterCrashServiceImpl01(args[args.length - 3].hashCode(), 0);
AfterCrashServiceImpl01 afterCrashServiceImpl2 = new AfterCrashServiceImpl01(args[args.length - 3].hashCode(), 1);
AfterCrashServicePOATie servant1 = new AfterCrashServicePOATie(afterCrashServiceImpl1);
AfterCrashServicePOATie servant2 = new AfterCrashServicePOATie(afterCrashServiceImpl2);
OAInterface.objectIsReady(servant1);
AfterCrashService afterCrashService1 = AfterCrashServiceHelper.narrow(OAInterface.corbaReference(servant1));
OAInterface.objectIsReady(servant2);
AfterCrashService afterCrashService2 = AfterCrashServiceHelper.narrow(OAInterface.corbaReference(servant2));
ServerIORStore.storeIOR(args[args.length - 2], ORBInterface.orb().object_to_string(afterCrashService1));
ServerIORStore.storeIOR(args[args.length - 1], ORBInterface.orb().object_to_string(afterCrashService2));
System.out.println("Ready");
ORBInterface.run();
}
catch (Exception exception)
{
System.err.println("Server04.main: " + exception);
exception.printStackTrace(System.err);
}
}
}
| lgpl-2.1 |
siosio/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/CopyOptionsDialog.java | 9247 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.dialogs.browser;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.ui.CommitMessage;
import com.intellij.ui.CollectionComboBoxModel;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.SimpleListCellRenderer;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.components.BorderLayoutPanel;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.api.Url;
import org.jetbrains.idea.svn.commandLine.SvnBindException;
import org.jetbrains.idea.svn.dialogs.RepositoryBrowserComponent;
import org.jetbrains.idea.svn.dialogs.RepositoryBrowserDialog;
import org.jetbrains.idea.svn.dialogs.RepositoryTreeNode;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import static com.intellij.openapi.util.text.StringUtil.isEmpty;
import static com.intellij.util.ui.JBUI.Borders.emptyTop;
import static com.intellij.util.ui.JBUI.Panels.simplePanel;
import static com.intellij.util.ui.JBUI.insets;
import static org.jetbrains.idea.svn.SvnBundle.message;
import static org.jetbrains.idea.svn.SvnBundle.messagePointer;
import static org.jetbrains.idea.svn.SvnUtil.append;
public class CopyOptionsDialog extends DialogWrapper {
private final Url myURL;
private Url myTargetUrl;
private CommitMessage myCommitMessage;
private final Project myProject;
private JTextField myNameField;
private JBLabel myURLLabel;
private RepositoryBrowserComponent myBrowser;
private JBLabel myTargetURLLabel;
private BorderLayoutPanel myMainPanel;
public CopyOptionsDialog(Project project, RepositoryTreeNode root, RepositoryTreeNode node, boolean copy) {
super(project, true);
myProject = project;
myURL = node.getURL();
createUI();
myTargetURLLabel.setForeground(copy ? FileStatus.ADDED.getColor() : FileStatus.MODIFIED.getColor());
setOKButtonText(copy ? message("button.copy") : message("button.move"));
myURLLabel.setText(myURL.toDecodedString());
TreeNode[] path = node.getSelfPath();
TreeNode[] subPath = Arrays.copyOfRange(path, 1, path.length);
myBrowser.setRepositoryURL(root.getURL(), false, new OpeningExpander.Factory(
subPath, node.getParent() instanceof RepositoryTreeNode ? (RepositoryTreeNode)node.getParent() : null));
myBrowser.addChangeListener(e -> update());
myNameField.setText(myURL.getTail());
myNameField.selectAll();
myNameField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(@NotNull DocumentEvent e) {
update();
}
});
String lastMessage = VcsConfiguration.getInstance(myProject).getLastNonEmptyCommitMessage();
if (lastMessage != null) {
myCommitMessage.setText(lastMessage);
myCommitMessage.getEditorField().selectAll();
}
Disposer.register(getDisposable(), myBrowser);
setTitle(copy ? message("copy.dialog.title") : message("move.dialog.title"));
init();
update();
}
@NotNull
public static ComboBox<String> configureRecentMessagesComponent(@NotNull Project project,
@NotNull ComboBox<String> comboBox,
@NotNull Consumer<? super String> messageConsumer) {
List<String> messages = VcsConfiguration.getInstance(project).getRecentMessages();
Collections.reverse(messages);
CollectionComboBoxModel<String> model = new CollectionComboBoxModel<>(messages);
comboBox.setModel(model);
comboBox.setRenderer(SimpleListCellRenderer.create("", commitMessage -> getPresentableCommitMessage(commitMessage)));
comboBox.addActionListener(e -> messageConsumer.accept(model.getSelected()));
return comboBox;
}
@NlsSafe
private static String getPresentableCommitMessage(@NotNull String commitMessage) {
return commitMessage.replace('\r', '|').replace('\n', '|');
}
private void createUI() {
myMainPanel = simplePanel();
myBrowser = new RepositoryBrowserComponent(SvnVcs.getInstance(myProject));
DefaultActionGroup group = new DefaultActionGroup();
group.add(new RepositoryBrowserDialog.MkDirAction(myBrowser) {
@Override
public void update(@NotNull AnActionEvent e) {
super.update(e);
e.getPresentation().setText(messagePointer("action.new.remote.folder.text"));
}
});
group.add(new RepositoryBrowserDialog.DeleteAction(myBrowser));
group.add(new RepositoryBrowserDialog.RefreshAction(myBrowser));
PopupHandler.installPopupMenu(myBrowser, group, "SvnOptionsBrowserPopup");
Splitter splitter = new Splitter(true, 0.7f);
splitter.setFirstComponent(createBrowserPartWrapper());
splitter.setSecondComponent(createCommitMessageWrapper());
myMainPanel.addToCenter(splitter);
ComboBox<String> messagesBox = configureRecentMessagesComponent(myProject, new ComboBox<>(), message -> {
if (message != null) {
myCommitMessage.setText(message);
myCommitMessage.getEditorField().selectAll();
}
});
myMainPanel.addToBottom(
simplePanel()
.addToTop(new JBLabel(message("label.recent.messages")))
.addToBottom(messagesBox)
.withBorder(emptyTop(4))
);
}
@NotNull
private JPanel createCommitMessageWrapper() {
myCommitMessage = new CommitMessage(myProject, false, false, true);
Disposer.register(getDisposable(), myCommitMessage);
return simplePanel(myCommitMessage).addToTop(new JBLabel(message("label.commit.message")));
}
@NotNull
private JPanel createBrowserPartWrapper() {
JPanel wrapper = new JPanel(new GridBagLayout());
GridBag gridBag =
new GridBag().setDefaultAnchor(GridBagConstraints.NORTHWEST).setDefaultFill(GridBagConstraints.NONE).setDefaultInsets(insets(1))
.setDefaultWeightX(1).setDefaultWeightY(0);
gridBag.nextLine().next().weightx(0);
wrapper.add(new JBLabel(message("label.source.url")), gridBag);
gridBag.next().fillCellHorizontally();
myURLLabel = new JBLabel();
myURLLabel.setFont(myURLLabel.getFont().deriveFont(Font.BOLD));
wrapper.add(myURLLabel, gridBag);
gridBag.nextLine().next().weightx(0).pady(4);
wrapper.add(new JBLabel(message("label.target.location")), gridBag);
gridBag.nextLine().next().fillCell().weighty(1).coverLine(2);
wrapper.add(myBrowser, gridBag);
gridBag.nextLine().next().weightx(0).pady(4);
wrapper.add(new JBLabel(message("label.target.name")), gridBag);
gridBag.next().fillCellHorizontally();
myNameField = new JTextField();
wrapper.add(myNameField, gridBag);
gridBag.nextLine().next().weightx(0).pady(2);
wrapper.add(new JBLabel(message("label.target.url")), gridBag);
gridBag.next().fillCellHorizontally();
myTargetURLLabel = new JBLabel();
myTargetURLLabel.setFont(myTargetURLLabel.getFont().deriveFont(Font.BOLD));
wrapper.add(myTargetURLLabel, gridBag);
return wrapper;
}
@Override
@NonNls
protected String getDimensionServiceKey() {
return "svn4idea.copy.options";
}
public String getCommitMessage() {
return myCommitMessage.getComment();
}
public Url getSourceURL() {
return myURL;
}
public String getName() {
return myNameField.getText();
}
@Nullable
public Url getTargetURL() {
return myTargetUrl;
}
@Nullable
public RepositoryTreeNode getTargetParentNode() {
return myBrowser.getSelectedNode();
}
@Override
@Nullable
protected JComponent createCenterPanel() {
return myMainPanel;
}
private void update() {
myTargetUrl = buildTargetUrl();
myTargetURLLabel.setText(myTargetUrl != null ? myTargetUrl.toDecodedString() : "");
getOKAction().setEnabled(myTargetUrl != null && !myURL.equals(myTargetUrl));
}
private @Nullable Url buildTargetUrl() {
RepositoryTreeNode locationNode = myBrowser.getSelectedNode();
if (locationNode == null) return null;
Url location = locationNode.getURL();
String name = myNameField.getText();
if (isEmpty(name)) return null;
try {
return append(location, name);
}
catch (SvnBindException e) {
return null;
}
}
@Override
public JComponent getPreferredFocusedComponent() {
return myNameField;
}
}
| apache-2.0 |
wuhais/acmeair-netflixoss-weave | workspace/acmeair-webapp/src/main/java/com/acmeair/web/TripFlightOptions.java | 1825 | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
import java.util.List;
/**
* TripFlightOptions is the main return type when searching for flights.
*
* The object will return as many tripLeg's worth of Flight options as requested. So if the user
* requests a one way flight they will get a List that has only one TripLegInfo and it will have
* a list of flights that are options for that flight. If a user selects round trip, they will
* have a List of two TripLegInfo objects. If a user does a multi-leg flight then the list will
* be whatever size they requested. For now, only supporting one way and return flights so the
* list should always be of size one or two.
*
*
* @author aspyker
*
*/
public class TripFlightOptions {
private int tripLegs;
private List<TripLegInfo> tripFlights;
public int getTripLegs() {
return tripLegs;
}
public void setTripLegs(int tripLegs) {
this.tripLegs = tripLegs;
}
public List<TripLegInfo> getTripFlights() {
return tripFlights;
}
public void setTripFlights(List<TripLegInfo> tripFlights) {
this.tripFlights = tripFlights;
}
} | apache-2.0 |
jomarko/kie-wb-common | kie-wb-common-dmn/kie-wb-common-dmn-backend/src/main/java/org/kie/workbench/common/dmn/backend/definition/v1_1/QNamePropertyConverter.java | 3412 | /*
* 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.kie.workbench.common.dmn.backend.definition.v1_1;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import org.kie.dmn.model.api.DMNModelInstrumentedBase;
import org.kie.dmn.model.v1_1.TDefinitions;
import org.kie.workbench.common.dmn.api.property.dmn.QName;
import org.kie.workbench.common.dmn.api.property.dmn.types.BuiltInType;
public class QNamePropertyConverter {
/**
* @return maybe null
*/
public static QName wbFromDMN(final javax.xml.namespace.QName qName, final DMNModelInstrumentedBase parent) {
if (Objects.isNull(qName)) {
return BuiltInType.UNDEFINED.asQName();
}
//Convert DMN1.1 QName typeRefs to DMN1.2 (the editor only supports DMN1.2)
if (parent instanceof org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase && parent.getURIFEEL().equals(parent.getNamespaceURI(qName.getPrefix()))) {
return new QName(QName.NULL_NS_URI, qName.getLocalPart());
}
if (parent instanceof org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase) {
final String defaultNs = getDefaultNamespace(parent);
final String localNs = parent.getNamespaceURI(qName.getPrefix());
if (defaultNs.equalsIgnoreCase(localNs)) {
return new QName(QName.NULL_NS_URI, qName.getLocalPart());
}
}
return new QName(qName.getNamespaceURI(),
qName.getLocalPart(),
qName.getPrefix());
}
/*
* Handles setting QName as appropriate back on DMN node
*/
public static void setDMNfromWB(final QName qname,
final Consumer<javax.xml.namespace.QName> setter) {
if (qname != null) {
setter.accept(dmnFromWB(qname).orElse(null));
}
}
public static Optional<javax.xml.namespace.QName> dmnFromWB(final QName wb) {
if (wb != null) {
if (Objects.equals(wb, BuiltInType.UNDEFINED.asQName())) {
return Optional.empty();
}
return Optional.of(new javax.xml.namespace.QName(wb.getNamespaceURI(),
wb.getLocalPart(),
wb.getPrefix()));
} else {
return Optional.empty();
}
}
public static String getDefaultNamespace(final DMNModelInstrumentedBase parent) {
if (parent instanceof TDefinitions) {
final TDefinitions def = (TDefinitions) parent;
return def.getNamespace();
} else if (!Objects.isNull(parent.getParent())) {
return getDefaultNamespace(parent.getParent());
}
return "";
}
}
| apache-2.0 |
genericDataCompany/hsandbox | common/mahout-distribution-0.7-hadoop1/math/src/test/java/org/apache/mahout/math/jet/stat/ProbabilityTest.java | 11884 | /*
* 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.mahout.math.jet.stat;
import org.apache.mahout.math.MahoutTestCase;
import org.junit.Test;
import java.util.Locale;
public final class ProbabilityTest extends MahoutTestCase {
@Test
public void testNormalCdf() {
// computed by R
// pnorm(seq(-5,5, length.out=100))
double[] ref = {
2.866516e-07, 4.816530e-07, 8.013697e-07, 1.320248e-06, 2.153811e-06,
3.479323e-06, 5.565743e-06, 8.816559e-06, 1.383023e-05, 2.148428e-05,
3.305072e-05, 5.035210e-05, 7.596947e-05, 1.135152e-04, 1.679855e-04,
2.462079e-04, 3.574003e-04, 5.138562e-04, 7.317683e-04, 1.032198e-03,
1.442193e-03, 1.996034e-03, 2.736602e-03, 3.716808e-03, 5.001037e-03,
6.666521e-03, 8.804535e-03, 1.152131e-02, 1.493850e-02, 1.919309e-02,
2.443656e-02, 3.083320e-02, 3.855748e-02, 4.779035e-02, 5.871452e-02,
7.150870e-02, 8.634102e-02, 1.033618e-01, 1.226957e-01, 1.444345e-01,
1.686293e-01, 1.952845e-01, 2.243525e-01, 2.557301e-01, 2.892574e-01,
3.247181e-01, 3.618436e-01, 4.003175e-01, 4.397847e-01, 4.798600e-01,
5.201400e-01, 5.602153e-01, 5.996825e-01, 6.381564e-01, 6.752819e-01,
7.107426e-01, 7.442699e-01, 7.756475e-01, 8.047155e-01, 8.313707e-01,
8.555655e-01, 8.773043e-01, 8.966382e-01, 9.136590e-01, 9.284913e-01,
9.412855e-01, 9.522096e-01, 9.614425e-01, 9.691668e-01, 9.755634e-01,
9.808069e-01, 9.850615e-01, 9.884787e-01, 9.911955e-01, 9.933335e-01,
9.949990e-01, 9.962832e-01, 9.972634e-01, 9.980040e-01, 9.985578e-01,
9.989678e-01, 9.992682e-01, 9.994861e-01, 9.996426e-01, 9.997538e-01,
9.998320e-01, 9.998865e-01, 9.999240e-01, 9.999496e-01, 9.999669e-01,
9.999785e-01, 9.999862e-01, 9.999912e-01, 9.999944e-01, 9.999965e-01,
9.999978e-01, 9.999987e-01, 9.999992e-01, 9.999995e-01, 9.999997e-01
};
assertEquals(0.682689492137 / 2 + 0.5, Probability.normal(1), 1.0e-7);
int i = 0;
for (double x = -5; x <= 5.005; x += 10.0 / 99) {
assertEquals("Test 1 cdf function at " + x, ref[i], Probability.normal(x), 1.0e-6);
assertEquals("Test 2 cdf function at " + x, ref[i], Probability.normal(12, 1, x + 12), 1.0e-6);
assertEquals("Test 3 cdf function at " + x, ref[i], Probability.normal(12, 0.25, x / 2.0 + 12), 1.0e-6);
i++;
}
}
@Test
public void testBetaCdf() {
// values computed using:
//> pbeta(seq(0, 1, length.out=100), 1, 1)
//> pbeta(seq(0, 1, length.out=100), 2, 1)
//> pbeta(seq(0, 1, length.out=100), 2, 5)
//> pbeta(seq(0, 1, length.out=100), 0.2, 5)
//> pbeta(seq(0, 1, length.out=100), 0.2, 0.01)
double[][] ref = new double[5][];
ref[0] = new double[]{
0.00000000, 0.01010101, 0.02020202, 0.03030303, 0.04040404, 0.05050505,
0.06060606, 0.07070707, 0.08080808, 0.09090909, 0.10101010, 0.11111111,
0.12121212, 0.13131313, 0.14141414, 0.15151515, 0.16161616, 0.17171717,
0.18181818, 0.19191919, 0.20202020, 0.21212121, 0.22222222, 0.23232323,
0.24242424, 0.25252525, 0.26262626, 0.27272727, 0.28282828, 0.29292929,
0.30303030, 0.31313131, 0.32323232, 0.33333333, 0.34343434, 0.35353535,
0.36363636, 0.37373737, 0.38383838, 0.39393939, 0.40404040, 0.41414141,
0.42424242, 0.43434343, 0.44444444, 0.45454545, 0.46464646, 0.47474747,
0.48484848, 0.49494949, 0.50505051, 0.51515152, 0.52525253, 0.53535354,
0.54545455, 0.55555556, 0.56565657, 0.57575758, 0.58585859, 0.59595960,
0.60606061, 0.61616162, 0.62626263, 0.63636364, 0.64646465, 0.65656566,
0.66666667, 0.67676768, 0.68686869, 0.69696970, 0.70707071, 0.71717172,
0.72727273, 0.73737374, 0.74747475, 0.75757576, 0.76767677, 0.77777778,
0.78787879, 0.79797980, 0.80808081, 0.81818182, 0.82828283, 0.83838384,
0.84848485, 0.85858586, 0.86868687, 0.87878788, 0.88888889, 0.89898990,
0.90909091, 0.91919192, 0.92929293, 0.93939394, 0.94949495, 0.95959596,
0.96969697, 0.97979798, 0.98989899, 1.00000000
};
ref[1] = new double[]{
0.0000000000, 0.0001020304, 0.0004081216, 0.0009182736, 0.0016324865,
0.0025507601, 0.0036730946, 0.0049994898, 0.0065299459, 0.0082644628,
0.0102030405, 0.0123456790, 0.0146923783, 0.0172431385, 0.0199979594,
0.0229568411, 0.0261197837, 0.0294867871, 0.0330578512, 0.0368329762,
0.0408121620, 0.0449954086, 0.0493827160, 0.0539740843, 0.0587695133,
0.0637690032, 0.0689725538, 0.0743801653, 0.0799918376, 0.0858075707,
0.0918273646, 0.0980512193, 0.1044791348, 0.1111111111, 0.1179471483,
0.1249872462, 0.1322314050, 0.1396796245, 0.1473319049, 0.1551882461,
0.1632486481, 0.1715131109, 0.1799816345, 0.1886542190, 0.1975308642,
0.2066115702, 0.2158963371, 0.2253851648, 0.2350780533, 0.2449750026,
0.2550760127, 0.2653810836, 0.2758902153, 0.2866034078, 0.2975206612,
0.3086419753, 0.3199673503, 0.3314967860, 0.3432302826, 0.3551678400,
0.3673094582, 0.3796551372, 0.3922048771, 0.4049586777, 0.4179165391,
0.4310784614, 0.4444444444, 0.4580144883, 0.4717885930, 0.4857667585,
0.4999489848, 0.5143352719, 0.5289256198, 0.5437200286, 0.5587184981,
0.5739210285, 0.5893276196, 0.6049382716, 0.6207529844, 0.6367717580,
0.6529945924, 0.6694214876, 0.6860524436, 0.7028874605, 0.7199265381,
0.7371696766, 0.7546168758, 0.7722681359, 0.7901234568, 0.8081828385,
0.8264462810, 0.8449137843, 0.8635853484, 0.8824609734, 0.9015406591,
0.9208244057, 0.9403122130, 0.9600040812, 0.9799000102, 1.0000000000
};
ref[2] = new double[]{
0.000000000, 0.001489698, 0.005799444, 0.012698382, 0.021966298, 0.033393335,
0.046779694, 0.061935356, 0.078679798, 0.096841712, 0.116258735, 0.136777178,
0.158251755, 0.180545326, 0.203528637, 0.227080061, 0.251085352, 0.275437393,
0.300035957, 0.324787463, 0.349604743, 0.374406809, 0.399118623, 0.423670875,
0.447999763, 0.472046772, 0.495758466, 0.519086275, 0.541986291, 0.564419069,
0.586349424, 0.607746242, 0.628582288, 0.648834019, 0.668481403, 0.687507740,
0.705899486, 0.723646086, 0.740739801, 0.757175549, 0.772950746, 0.788065147,
0.802520695, 0.816321377, 0.829473074, 0.841983426, 0.853861691, 0.865118615,
0.875766302, 0.885818092, 0.895288433, 0.904192771, 0.912547431, 0.920369513,
0.927676778, 0.934487554, 0.940820632, 0.946695177, 0.952130629, 0.957146627,
0.961762916, 0.965999275, 0.969875437, 0.973411020, 0.976625460, 0.979537944,
0.982167353, 0.984532203, 0.986650598, 0.988540173, 0.990218056, 0.991700827,
0.993004475, 0.994144371, 0.995135237, 0.995991117, 0.996725360, 0.997350600,
0.997878739, 0.998320942, 0.998687627, 0.998988463, 0.999232371, 0.999427531,
0.999581387, 0.999700663, 0.999791377, 0.999858864, 0.999907798, 0.999942219,
0.999965567, 0.999980718, 0.999990021, 0.999995342, 0.999998111, 0.999999376,
0.999999851, 0.999999980, 0.999999999, 1.000000000
};
ref[3] = new double[]{
0.0000000, 0.5858072, 0.6684658, 0.7201859, 0.7578936, 0.7873991, 0.8114552,
0.8316029, 0.8487998, 0.8636849, 0.8767081, 0.8881993, 0.8984080, 0.9075280,
0.9157131, 0.9230876, 0.9297536, 0.9357958, 0.9412856, 0.9462835, 0.9508414,
0.9550044, 0.9588113, 0.9622963, 0.9654896, 0.9684178, 0.9711044, 0.9735707,
0.9758356, 0.9779161, 0.9798276, 0.9815839, 0.9831977, 0.9846805, 0.9860426,
0.9872936, 0.9884422, 0.9894965, 0.9904638, 0.9913509, 0.9921638, 0.9929085,
0.9935900, 0.9942134, 0.9947832, 0.9953034, 0.9957779, 0.9962104, 0.9966041,
0.9969621, 0.9972872, 0.9975821, 0.9978492, 0.9980907, 0.9983088, 0.9985055,
0.9986824, 0.9988414, 0.9989839, 0.9991113, 0.9992251, 0.9993265, 0.9994165,
0.9994963, 0.9995668, 0.9996288, 0.9996834, 0.9997311, 0.9997727, 0.9998089,
0.9998401, 0.9998671, 0.9998901, 0.9999098, 0.9999265, 0.9999406, 0.9999524,
0.9999622, 0.9999703, 0.9999769, 0.9999823, 0.9999866, 0.9999900, 0.9999927,
0.9999947, 0.9999963, 0.9999975, 0.9999983, 0.9999989, 0.9999993, 0.9999996,
0.9999998, 0.9999999, 0.9999999, 1.0000000, 1.0000000, 1.0000000, 1.0000000,
1.0000000, 1.0000000
};
ref[4] = new double[]{
0.00000000, 0.01908202, 0.02195656, 0.02385194, 0.02530810, 0.02650923,
0.02754205, 0.02845484, 0.02927741, 0.03002959, 0.03072522, 0.03137444,
0.03198487, 0.03256240, 0.03311171, 0.03363655, 0.03414001, 0.03462464,
0.03509259, 0.03554568, 0.03598550, 0.03641339, 0.03683054, 0.03723799,
0.03763667, 0.03802739, 0.03841091, 0.03878787, 0.03915890, 0.03952453,
0.03988529, 0.04024162, 0.04059396, 0.04094272, 0.04128827, 0.04163096,
0.04197113, 0.04230909, 0.04264515, 0.04297958, 0.04331268, 0.04364471,
0.04397592, 0.04430658, 0.04463693, 0.04496722, 0.04529770, 0.04562860,
0.04596017, 0.04629265, 0.04662629, 0.04696134, 0.04729804, 0.04763666,
0.04797747, 0.04832073, 0.04866673, 0.04901578, 0.04936816, 0.04972422,
0.05008428, 0.05044871, 0.05081789, 0.05119222, 0.05157213, 0.05195809,
0.05235059, 0.05275018, 0.05315743, 0.05357298, 0.05399753, 0.05443184,
0.05487673, 0.05533315, 0.05580212, 0.05628480, 0.05678247, 0.05729660,
0.05782885, 0.05838111, 0.05895557, 0.05955475, 0.06018161, 0.06083965,
0.06153300, 0.06226670, 0.06304685, 0.06388102, 0.06477877, 0.06575235,
0.06681788, 0.06799717, 0.06932077, 0.07083331, 0.07260394, 0.07474824,
0.07748243, 0.08129056, 0.08771055, 1.00000000
};
double[] alpha = {1.0, 2.0, 2.0, 0.2, 0.2};
double[] beta = {1.0, 1.0, 5.0, 5.0, 0.01};
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 100; i++) {
double x = i / 99.0;
String p = String.format(Locale.ENGLISH,
"pbeta(q=%6.4f, shape1=%5.3f shape2=%5.3f) = %.8f",
x, alpha[j], beta[j], ref[j][i]);
assertEquals(p, ref[j][i], Probability.beta(alpha[j], beta[j], x), 1.0e-7);
}
}
}
@Test
public void testLogGamma() {
double[] xValues = {1.1, 2.1, 3.1, 4.1, 5.1, 20.1, 100.1, -0.9};
double[] ref = {
-0.04987244, 0.04543774, 0.78737508, 1.91877719, 3.32976417, 39.63719250, 359.59427179, 2.35807317
};
for (int i = 0; i < xValues.length; i++) {
double x = xValues[i];
assertEquals(ref[i], Gamma.logGamma(x), 1.0e-7);
}
}
}
| apache-2.0 |
fred84/elasticsearch | server/src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexClusterStateUpdateRequest.java | 5538 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.indices.create;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.shrink.ResizeType;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.cluster.ack.ClusterStateUpdateRequest;
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.Index;
import org.elasticsearch.transport.TransportMessage;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Cluster state update request that allows to create an index
*/
public class CreateIndexClusterStateUpdateRequest extends ClusterStateUpdateRequest<CreateIndexClusterStateUpdateRequest> {
private final TransportMessage originalMessage;
private final String cause;
private final String index;
private final String providedName;
private final boolean updateAllTypes;
private Index recoverFrom;
private ResizeType resizeType;
private IndexMetaData.State state = IndexMetaData.State.OPEN;
private Settings settings = Settings.Builder.EMPTY_SETTINGS;
private final Map<String, String> mappings = new HashMap<>();
private final Set<Alias> aliases = new HashSet<>();
private final Map<String, IndexMetaData.Custom> customs = new HashMap<>();
private final Set<ClusterBlock> blocks = new HashSet<>();
private ActiveShardCount waitForActiveShards = ActiveShardCount.DEFAULT;
public CreateIndexClusterStateUpdateRequest(TransportMessage originalMessage, String cause, String index, String providedName,
boolean updateAllTypes) {
this.originalMessage = originalMessage;
this.cause = cause;
this.index = index;
this.updateAllTypes = updateAllTypes;
this.providedName = providedName;
}
public CreateIndexClusterStateUpdateRequest settings(Settings settings) {
this.settings = settings;
return this;
}
public CreateIndexClusterStateUpdateRequest mappings(Map<String, String> mappings) {
this.mappings.putAll(mappings);
return this;
}
public CreateIndexClusterStateUpdateRequest aliases(Set<Alias> aliases) {
this.aliases.addAll(aliases);
return this;
}
public CreateIndexClusterStateUpdateRequest customs(Map<String, IndexMetaData.Custom> customs) {
this.customs.putAll(customs);
return this;
}
public CreateIndexClusterStateUpdateRequest blocks(Set<ClusterBlock> blocks) {
this.blocks.addAll(blocks);
return this;
}
public CreateIndexClusterStateUpdateRequest state(IndexMetaData.State state) {
this.state = state;
return this;
}
public CreateIndexClusterStateUpdateRequest recoverFrom(Index recoverFrom) {
this.recoverFrom = recoverFrom;
return this;
}
public CreateIndexClusterStateUpdateRequest waitForActiveShards(ActiveShardCount waitForActiveShards) {
this.waitForActiveShards = waitForActiveShards;
return this;
}
public CreateIndexClusterStateUpdateRequest resizeType(ResizeType resizeType) {
this.resizeType = resizeType;
return this;
}
public TransportMessage originalMessage() {
return originalMessage;
}
public String cause() {
return cause;
}
public String index() {
return index;
}
public IndexMetaData.State state() {
return state;
}
public Settings settings() {
return settings;
}
public Map<String, String> mappings() {
return mappings;
}
public Set<Alias> aliases() {
return aliases;
}
public Map<String, IndexMetaData.Custom> customs() {
return customs;
}
public Set<ClusterBlock> blocks() {
return blocks;
}
public Index recoverFrom() {
return recoverFrom;
}
/** True if all fields that span multiple types should be updated, false otherwise */
public boolean updateAllTypes() {
return updateAllTypes;
}
/**
* The name that was provided by the user. This might contain a date math expression.
* @see IndexMetaData#SETTING_INDEX_PROVIDED_NAME
*/
public String getProvidedName() {
return providedName;
}
public ActiveShardCount waitForActiveShards() {
return waitForActiveShards;
}
/**
* Returns the resize type or null if this is an ordinary create index request
*/
public ResizeType resizeType() {
return resizeType;
}
}
| apache-2.0 |
cpcloud/arrow | java/vector/src/main/java/org/apache/arrow/vector/ipc/message/MessageResult.java | 1928 | /*
* 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.arrow.vector.ipc.message;
import org.apache.arrow.flatbuf.Message;
import org.apache.arrow.memory.ArrowBuf;
/**
* Class to hold the Message metadata and body data when reading messages through a
* MessageChannelReader.
*/
public class MessageResult {
/**
* Construct with a valid Message metadata and optional ArrowBuf containing message body
* data, if any.
*
* @param message Deserialized Flatbuffer Message metadata description
* @param bodyBuffer Optional ArrowBuf containing message body data, null if message has no body
*/
MessageResult(Message message, ArrowBuf bodyBuffer) {
this.message = message;
this.bodyBuffer = bodyBuffer;
}
/**
* Get the Message metadata.
*
* @return the Flatbuffer Message metadata
*/
public Message getMessage() {
return message;
}
/**
* Get the message body data.
*
* @return an ArrowBuf containing the message body data or null if the message has no body
*/
public ArrowBuf getBodyBuffer() {
return bodyBuffer;
}
private final Message message;
private final ArrowBuf bodyBuffer;
}
| apache-2.0 |
vakninr/spring-boot | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.java | 11013 | /*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.mongo.embedded;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import de.flapdoodle.embed.mongo.Command;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.DownloadConfigBuilder;
import de.flapdoodle.embed.mongo.config.ExtractedArtifactStoreBuilder;
import de.flapdoodle.embed.mongo.config.IMongodConfig;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.config.RuntimeConfigBuilder;
import de.flapdoodle.embed.mongo.config.Storage;
import de.flapdoodle.embed.mongo.distribution.Feature;
import de.flapdoodle.embed.mongo.distribution.IFeatureAwareVersion;
import de.flapdoodle.embed.process.config.IRuntimeConfig;
import de.flapdoodle.embed.process.config.io.ProcessOutput;
import de.flapdoodle.embed.process.io.Processors;
import de.flapdoodle.embed.process.io.Slf4jLevel;
import de.flapdoodle.embed.process.io.progress.Slf4jProgressListener;
import de.flapdoodle.embed.process.runtime.Network;
import de.flapdoodle.embed.process.store.ArtifactStoreBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.mongo.MongoClientDependsOnBeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.data.mongo.ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.ReactiveMongoClientFactoryBean;
import org.springframework.util.Assert;
/**
* {@link EnableAutoConfiguration Auto-configuration} for Embedded Mongo.
*
* @author Henryk Konsek
* @author Andy Wilkinson
* @author Yogesh Lonkar
* @author Mark Paluch
* @since 1.3.0
*/
@Configuration
@EnableConfigurationProperties({ MongoProperties.class, EmbeddedMongoProperties.class })
@AutoConfigureBefore(MongoAutoConfiguration.class)
@ConditionalOnClass({ Mongo.class, MongodStarter.class })
public class EmbeddedMongoAutoConfiguration {
private static final byte[] IP4_LOOPBACK_ADDRESS = { 127, 0, 0, 1 };
private static final byte[] IP6_LOOPBACK_ADDRESS = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1 };
private final MongoProperties properties;
private final EmbeddedMongoProperties embeddedProperties;
private final ApplicationContext context;
private final IRuntimeConfig runtimeConfig;
public EmbeddedMongoAutoConfiguration(MongoProperties properties,
EmbeddedMongoProperties embeddedProperties, ApplicationContext context,
IRuntimeConfig runtimeConfig) {
this.properties = properties;
this.embeddedProperties = embeddedProperties;
this.context = context;
this.runtimeConfig = runtimeConfig;
}
@Bean(initMethod = "start", destroyMethod = "stop")
@ConditionalOnMissingBean
public MongodExecutable embeddedMongoServer(IMongodConfig mongodConfig)
throws IOException {
Integer configuredPort = this.properties.getPort();
if (configuredPort == null || configuredPort == 0) {
setEmbeddedPort(mongodConfig.net().getPort());
}
MongodStarter mongodStarter = getMongodStarter(this.runtimeConfig);
return mongodStarter.prepare(mongodConfig);
}
private MongodStarter getMongodStarter(IRuntimeConfig runtimeConfig) {
if (runtimeConfig == null) {
return MongodStarter.getDefaultInstance();
}
return MongodStarter.getInstance(runtimeConfig);
}
@Bean
@ConditionalOnMissingBean
public IMongodConfig embeddedMongoConfiguration() throws IOException {
IFeatureAwareVersion featureAwareVersion = new ToStringFriendlyFeatureAwareVersion(
this.embeddedProperties.getVersion(),
this.embeddedProperties.getFeatures());
MongodConfigBuilder builder = new MongodConfigBuilder()
.version(featureAwareVersion);
if (this.embeddedProperties.getStorage() != null) {
builder.replication(
new Storage(this.embeddedProperties.getStorage().getDatabaseDir(),
this.embeddedProperties.getStorage().getReplSetName(),
this.embeddedProperties.getStorage().getOplogSize() != null
? this.embeddedProperties.getStorage().getOplogSize()
: 0));
}
Integer configuredPort = this.properties.getPort();
if (configuredPort != null && configuredPort > 0) {
builder.net(new Net(getHost().getHostAddress(), configuredPort,
Network.localhostIsIPv6()));
}
else {
builder.net(new Net(getHost().getHostAddress(),
Network.getFreeServerPort(getHost()), Network.localhostIsIPv6()));
}
return builder.build();
}
private InetAddress getHost() throws UnknownHostException {
if (this.properties.getHost() == null) {
return InetAddress.getByAddress(Network.localhostIsIPv6()
? IP6_LOOPBACK_ADDRESS : IP4_LOOPBACK_ADDRESS);
}
return InetAddress.getByName(this.properties.getHost());
}
private void setEmbeddedPort(int port) {
setPortProperty(this.context, port);
}
private void setPortProperty(ApplicationContext currentContext, int port) {
if (currentContext instanceof ConfigurableApplicationContext) {
MutablePropertySources sources = ((ConfigurableApplicationContext) currentContext)
.getEnvironment().getPropertySources();
getMongoPorts(sources).put("local.mongo.port", port);
}
if (currentContext.getParent() != null) {
setPortProperty(currentContext.getParent(), port);
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> getMongoPorts(MutablePropertySources sources) {
PropertySource<?> propertySource = sources.get("mongo.ports");
if (propertySource == null) {
propertySource = new MapPropertySource("mongo.ports", new HashMap<>());
sources.addFirst(propertySource);
}
return (Map<String, Object>) propertySource.getSource();
}
@Configuration
@ConditionalOnClass(Logger.class)
@ConditionalOnMissingBean(IRuntimeConfig.class)
static class RuntimeConfigConfiguration {
@Bean
public IRuntimeConfig embeddedMongoRuntimeConfig() {
Logger logger = LoggerFactory
.getLogger(getClass().getPackage().getName() + ".EmbeddedMongo");
ProcessOutput processOutput = new ProcessOutput(
Processors.logTo(logger, Slf4jLevel.INFO),
Processors.logTo(logger, Slf4jLevel.ERROR), Processors.named(
"[console>]", Processors.logTo(logger, Slf4jLevel.DEBUG)));
return new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger)
.processOutput(processOutput).artifactStore(getArtifactStore(logger))
.build();
}
private ArtifactStoreBuilder getArtifactStore(Logger logger) {
return new ExtractedArtifactStoreBuilder().defaults(Command.MongoD)
.download(new DownloadConfigBuilder()
.defaultsForCommand(Command.MongoD)
.progressListener(new Slf4jProgressListener(logger)).build());
}
}
/**
* Additional configuration to ensure that {@link MongoClient} beans depend on the
* {@code embeddedMongoServer} bean.
*/
@Configuration
@ConditionalOnClass({ MongoClient.class, MongoClientFactoryBean.class })
protected static class EmbeddedMongoDependencyConfiguration
extends MongoClientDependsOnBeanFactoryPostProcessor {
public EmbeddedMongoDependencyConfiguration() {
super("embeddedMongoServer");
}
}
/**
* Additional configuration to ensure that {@link MongoClient} beans depend on the
* {@code embeddedMongoServer} bean.
*/
@Configuration
@ConditionalOnClass({ com.mongodb.reactivestreams.client.MongoClient.class,
ReactiveMongoClientFactoryBean.class })
protected static class EmbeddedReactiveMongoDependencyConfiguration
extends ReactiveStreamsMongoClientDependsOnBeanFactoryPostProcessor {
public EmbeddedReactiveMongoDependencyConfiguration() {
super("embeddedMongoServer");
}
}
/**
* A workaround for the lack of a {@code toString} implementation on
* {@code GenericFeatureAwareVersion}.
*/
private final static class ToStringFriendlyFeatureAwareVersion
implements IFeatureAwareVersion {
private final String version;
private final Set<Feature> features;
private ToStringFriendlyFeatureAwareVersion(String version,
Set<Feature> features) {
Assert.notNull(version, "version must not be null");
this.version = version;
this.features = (features == null ? Collections.<Feature>emptySet()
: features);
}
@Override
public String asInDownloadPath() {
return this.version;
}
@Override
public boolean enabled(Feature feature) {
return this.features.contains(feature);
}
@Override
public String toString() {
return this.version;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.features.hashCode();
result = prime * result + this.version.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() == obj.getClass()) {
ToStringFriendlyFeatureAwareVersion other = (ToStringFriendlyFeatureAwareVersion) obj;
boolean equals = true;
equals = equals && this.features.equals(other.features);
equals = equals && this.version.equals(other.version);
return equals;
}
return super.equals(obj);
}
}
}
| apache-2.0 |
masslight/aws-apigateway-swagger-importer | src/com/amazonaws/service/apigateway/importer/impl/ApiGatewaySwaggerFileImporter.java | 2656 | /*
* Copyright 2010-2015 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.service.apigateway.importer.impl;
import com.amazonaws.service.apigateway.importer.ApiFileImporter;
import com.amazonaws.service.apigateway.importer.SwaggerApiImporter;
import com.google.inject.Inject;
import com.wordnik.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import static java.lang.String.format;
public class ApiGatewaySwaggerFileImporter implements ApiFileImporter {
private static final Log LOG = LogFactory.getLog(ApiGatewaySwaggerFileImporter.class);
private final SwaggerParser parser;
private final SwaggerApiImporter client;
@Inject
public ApiGatewaySwaggerFileImporter(SwaggerParser parser, SwaggerApiImporter client) {
this.parser = parser;
this.client = client;
}
@Override
public String importApi(String filePath) {
LOG.info(format("Attempting to create API from Swagger definition. " +
"Swagger file: %s", filePath));
final Swagger swagger = parse(filePath);
return client.createApi(swagger, new File(filePath).getName());
}
@Override
public void updateApi(String apiId, String filePath) {
LOG.info(format("Attempting to update API from Swagger definition. " +
"API identifier: %s Swagger file: %s", apiId, filePath));
final Swagger swagger = parse(filePath);
client.updateApi(apiId, swagger);
}
@Override
public void deploy(String apiId, String deploymentStage) {
client.deploy(apiId, deploymentStage);
}
@Override
public void deleteApi(String apiId) {
client.deleteApi(apiId);
}
private Swagger parse(String filePath) {
final Swagger swagger = parser.read(filePath);
if (swagger != null && swagger.getPaths() != null) {
LOG.info("Parsed Swagger with " + swagger.getPaths().size() + " paths");
}
return swagger;
}
}
| apache-2.0 |
siosio/intellij-community | platform/util/text-matching/src/com/intellij/psi/codeStyle/MinusculeMatcherImpl.java | 23640 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.codeStyle;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.Strings;
import com.intellij.util.containers.FList;
import com.intellij.util.text.CharArrayCharSequence;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.text.NameUtilCore;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
/**
* Tells whether a string matches a specific pattern. Allows for lowercase camel-hump matching.
* Used in navigation, code completion, speed search etc.
*
* @see NameUtil#buildMatcher(String)
*
* @author peter
*/
class MinusculeMatcherImpl extends MinusculeMatcher {
/** Camel-hump matching is >O(n), so for larger prefixes we fall back to simpler matching to avoid pauses */
private static final int MAX_CAMEL_HUMP_MATCHING_LENGTH = 100;
private final char[] myPattern;
private final String myHardSeparators;
private final NameUtil.MatchingCaseSensitivity myOptions;
private final boolean myHasHumps;
private final boolean myHasSeparators;
private final boolean myHasDots;
private final boolean[] isLowerCase;
private final boolean[] isUpperCase;
private final boolean[] isWordSeparator;
private final char[] toUpperCase;
private final char[] toLowerCase;
private final char[] myMeaningfulCharacters;
private final int myMinNameLength;
/**
* Constructs a matcher by a given pattern.
* @param pattern the pattern
* @param options case sensitivity settings
* @param hardSeparators A string of characters (empty by default). Lowercase humps don't work for parts separated by any of these characters.
* Need either an explicit uppercase letter or the same separator character in prefix
*/
MinusculeMatcherImpl(@NotNull String pattern, @NotNull NameUtil.MatchingCaseSensitivity options, @NotNull String hardSeparators) {
myOptions = options;
myPattern = Strings.trimEnd(pattern, "* ").toCharArray();
myHardSeparators = hardSeparators;
isLowerCase = new boolean[myPattern.length];
isUpperCase = new boolean[myPattern.length];
isWordSeparator = new boolean[myPattern.length];
toUpperCase = new char[myPattern.length];
toLowerCase = new char[myPattern.length];
StringBuilder meaningful = new StringBuilder();
for (int k = 0; k < myPattern.length; k++) {
char c = myPattern[k];
isLowerCase[k] = Character.isLowerCase(c);
isUpperCase[k] = Character.isUpperCase(c);
isWordSeparator[k] = isWordSeparator(c);
toUpperCase[k] = Strings.toUpperCase(c);
toLowerCase[k] = Strings.toLowerCase(c);
if (!isWildcard(k)) {
meaningful.append(toLowerCase[k]);
meaningful.append(toUpperCase[k]);
}
}
int i = 0;
while (isWildcard(i)) i++;
myHasHumps = hasFlag(i + 1, isUpperCase) && hasFlag(i, isLowerCase);
myHasSeparators = hasFlag(i, isWordSeparator);
myHasDots = hasDots(i);
myMeaningfulCharacters = meaningful.toString().toCharArray();
myMinNameLength = myMeaningfulCharacters.length / 2;
}
private static boolean isWordSeparator(char c) {
return Character.isWhitespace(c) || c == '_' || c == '-' || c == ':' || c == '+' || c == '.';
}
private static int nextWord(@NotNull String name, int start) {
if (start < name.length() && Character.isDigit(name.charAt(start))) {
return start + 1; //treat each digit as a separate hump
}
return NameUtilCore.nextWord(name, start);
}
private boolean hasFlag(int start, boolean[] flags) {
for (int i = start; i < myPattern.length; i++) {
if (flags[i]) {
return true;
}
}
return false;
}
private boolean hasDots(int start) {
for (int i = start; i < myPattern.length; i++) {
if (myPattern[i] == '.') {
return true;
}
}
return false;
}
@NotNull
private static FList<TextRange> prependRange(@NotNull FList<TextRange> ranges, int from, int length) {
TextRange head = ranges.getHead();
if (head != null && head.getStartOffset() == from + length) {
return ranges.getTail().prepend(new TextRange(from, head.getEndOffset()));
}
return ranges.prepend(TextRange.from(from, length));
}
@Override
public int matchingDegree(@NotNull String name, boolean valueStartCaseMatch, @Nullable FList<? extends TextRange> fragments) {
if (fragments == null) return Integer.MIN_VALUE;
if (fragments.isEmpty()) return 0;
final TextRange first = fragments.getHead();
boolean startMatch = first.getStartOffset() == 0;
boolean valuedStartMatch = startMatch && valueStartCaseMatch;
int matchingCase = 0;
int p = -1;
int skippedHumps = 0;
int nextHumpStart = 0;
boolean humpStartMatchedUpperCase = false;
for (TextRange range : fragments) {
for (int i = range.getStartOffset(); i < range.getEndOffset(); i++) {
boolean afterGap = i == range.getStartOffset() && first != range;
boolean isHumpStart = false;
while (nextHumpStart <= i) {
if (nextHumpStart == i) {
isHumpStart = true;
}
else if (afterGap) {
skippedHumps++;
}
nextHumpStart = nextWord(name, nextHumpStart);
}
char c = name.charAt(i);
p = Strings.indexOf(myPattern, c, p + 1, myPattern.length, false);
if (p < 0) {
break;
}
if (isHumpStart) {
humpStartMatchedUpperCase = c == myPattern[p] && isUpperCase[p];
}
matchingCase += evaluateCaseMatching(valuedStartMatch, p, humpStartMatchedUpperCase, i, afterGap, isHumpStart, c);
}
}
int startIndex = first.getStartOffset();
boolean afterSeparator = Strings.indexOfAny(name, myHardSeparators, 0, startIndex) >= 0;
boolean wordStart = startIndex == 0 || NameUtilCore.isWordStart(name, startIndex) && !NameUtilCore.isWordStart(name, startIndex - 1);
boolean finalMatch = fragments.get(fragments.size() - 1).getEndOffset() == name.length();
return (wordStart ? 1000 : 0) +
matchingCase -
fragments.size() +
-skippedHumps * 10 +
(afterSeparator ? 0 : 2) +
(startMatch ? 1 : 0) +
(finalMatch ? 1 : 0);
}
private int evaluateCaseMatching(boolean valuedStartMatch,
int patternIndex,
boolean humpStartMatchedUpperCase,
int nameIndex,
boolean afterGap,
boolean isHumpStart,
char nameChar) {
if (afterGap && isHumpStart && isLowerCase[patternIndex]) {
return -10; // disprefer when there's a hump but nothing in the pattern indicates the user meant it to be hump
}
if (nameChar == myPattern[patternIndex]) {
if (isUpperCase[patternIndex]) return 50; // strongly prefer user's uppercase matching uppercase: they made an effort to press Shift
if (nameIndex == 0 && valuedStartMatch) return 150; // the very first letter case distinguishes classes in Java etc
if (isHumpStart) return 1; // if a lowercase matches lowercase hump start, that also means something
} else if (isHumpStart) {
// disfavor hump starts where pattern letter case doesn't match name case
return -1;
} else if (isLowerCase[patternIndex] && humpStartMatchedUpperCase) {
// disfavor lowercase non-humps matching uppercase in the name
return -1;
}
return 0;
}
@Override
@NotNull
public String getPattern() {
return new String(myPattern);
}
@Override
@Nullable
public FList<TextRange> matchingFragments(@NotNull String name) {
if (name.length() < myMinNameLength) {
return null;
}
if (myPattern.length > MAX_CAMEL_HUMP_MATCHING_LENGTH) {
return matchBySubstring(name);
}
int length = name.length();
int patternIndex = 0;
boolean isAscii = true;
for (int i = 0; i < length; ++i) {
char c = name.charAt(i);
if (c >= 128) {
isAscii = false;
}
if (patternIndex < myMeaningfulCharacters.length &&
(c == myMeaningfulCharacters[patternIndex] || c == myMeaningfulCharacters[patternIndex + 1])) {
patternIndex += 2;
}
}
if (patternIndex < myMinNameLength * 2) {
return null;
}
return matchWildcards(name, 0, 0, isAscii);
}
@Nullable
private FList<TextRange> matchBySubstring(@NotNull String name) {
boolean infix = isPatternChar(0, '*');
char[] patternWithoutWildChar = filterWildcard(myPattern);
if (name.length() < patternWithoutWildChar.length) {
return null;
}
if (infix) {
int index = Strings.indexOfIgnoreCase(name, new CharArrayCharSequence(patternWithoutWildChar, 0, patternWithoutWildChar.length), 0);
if (index >= 0) {
return FList.<TextRange>emptyList().prepend(TextRange.from(index, patternWithoutWildChar.length - 1));
}
return null;
}
if (CharArrayUtil.regionMatches(patternWithoutWildChar, 0, patternWithoutWildChar.length, name)) {
return FList.<TextRange>emptyList().prepend(new TextRange(0, patternWithoutWildChar.length));
}
return null;
}
private static char[] filterWildcard(char[] source) {
char[] buffer = new char[source.length];
int i = 0;
for (char c : source) {
if (c != '*') buffer[i++] = c;
}
return Arrays.copyOf(buffer, i);
}
/**
* After a wildcard (* or space), search for the first non-wildcard pattern character in the name starting from nameIndex
* and try to {@link #matchFragment} for it.
*/
@Nullable
private FList<TextRange> matchWildcards(@NotNull String name,
int patternIndex,
int nameIndex,
boolean isAsciiName) {
if (nameIndex < 0) {
return null;
}
if (!isWildcard(patternIndex)) {
if (patternIndex == myPattern.length) {
return FList.emptyList();
}
return matchFragment(name, patternIndex, nameIndex, isAsciiName);
}
do {
patternIndex++;
} while (isWildcard(patternIndex));
if (patternIndex == myPattern.length) {
// the trailing space should match if the pattern ends with the last word part, or only its first hump character
if (isTrailingSpacePattern() && nameIndex != name.length() && (patternIndex < 2 || !isUpperCaseOrDigit(myPattern[patternIndex - 2]))) {
int spaceIndex = name.indexOf(' ', nameIndex);
if (spaceIndex >= 0) {
return FList.<TextRange>emptyList().prepend(TextRange.from(spaceIndex, 1));
}
return null;
}
return FList.emptyList();
}
return matchSkippingWords(name, patternIndex,
findNextPatternCharOccurrence(name, nameIndex, patternIndex, isAsciiName),
true, isAsciiName);
}
private boolean isTrailingSpacePattern() {
return isPatternChar(myPattern.length - 1, ' ');
}
private static boolean isUpperCaseOrDigit(char p) {
return Character.isUpperCase(p) || Character.isDigit(p);
}
/**
* Enumerates places in name that could be matched by the pattern at patternIndex position
* and invokes {@link #matchFragment} at those candidate positions
*/
@Nullable
private FList<TextRange> matchSkippingWords(@NotNull String name,
final int patternIndex,
int nameIndex,
boolean allowSpecialChars,
boolean isAsciiName) {
int maxFoundLength = 0;
while (nameIndex >= 0) {
int fragmentLength = seemsLikeFragmentStart(name, patternIndex, nameIndex) ? maxMatchingFragment(name, patternIndex, nameIndex) : 0;
// match the remaining pattern only if we haven't already seen fragment of the same (or bigger) length
// because otherwise it means that we already tried to match remaining pattern letters after it with the remaining name and failed
// but now we have the same remaining pattern letters and even less remaining name letters, and so will fail as well
if (fragmentLength > maxFoundLength || nameIndex + fragmentLength == name.length() && isTrailingSpacePattern()) {
if (!isMiddleMatch(name, patternIndex, nameIndex)) {
maxFoundLength = fragmentLength;
}
FList<TextRange> ranges = matchInsideFragment(name, patternIndex, nameIndex, isAsciiName, fragmentLength);
if (ranges != null) {
return ranges;
}
}
int next = findNextPatternCharOccurrence(name, nameIndex + 1, patternIndex, isAsciiName);
nameIndex = allowSpecialChars ? next : checkForSpecialChars(name, nameIndex + 1, next, patternIndex);
}
return null;
}
private int findNextPatternCharOccurrence(@NotNull String name,
int startAt,
int patternIndex,
boolean isAsciiName) {
return !isPatternChar(patternIndex - 1, '*') && !isWordSeparator[patternIndex]
? indexOfWordStart(name, patternIndex, startAt, isAsciiName)
: indexOfIgnoreCase(name, startAt, myPattern[patternIndex], patternIndex, isAsciiName);
}
private int checkForSpecialChars(String name, int start, int end, int patternIndex) {
if (end < 0) return -1;
// pattern humps are allowed to match in words separated by " ()", lowercase characters aren't
if (!myHasSeparators && !myHasHumps && Strings.containsAnyChar(name, myHardSeparators, start, end)) {
return -1;
}
// if the user has typed a dot, don't skip other dots between humps
// but one pattern dot may match several name dots
if (myHasDots && !isPatternChar(patternIndex - 1, '.') && Strings.contains(name, start, end, '.')) {
return -1;
}
return end;
}
private boolean seemsLikeFragmentStart(@NotNull String name, int patternIndex, int nextOccurrence) {
// uppercase should match either uppercase or a word start
return !isUpperCase[patternIndex] ||
Character.isUpperCase(name.charAt(nextOccurrence)) ||
NameUtilCore.isWordStart(name, nextOccurrence) ||
// accept uppercase matching lowercase if the whole prefix is uppercase and case sensitivity allows that
!myHasHumps && myOptions != NameUtil.MatchingCaseSensitivity.ALL;
}
private boolean charEquals(char patternChar, int patternIndex, char c, boolean isIgnoreCase) {
return patternChar == c ||
isIgnoreCase && (toLowerCase[patternIndex] == c || toUpperCase[patternIndex] == c);
}
@Nullable
private FList<TextRange> matchFragment(@NotNull String name,
int patternIndex,
int nameIndex,
boolean isAsciiName) {
int fragmentLength = maxMatchingFragment(name, patternIndex, nameIndex);
return fragmentLength == 0 ? null : matchInsideFragment(name, patternIndex, nameIndex, isAsciiName, fragmentLength);
}
private int maxMatchingFragment(@NotNull String name, int patternIndex, int nameIndex) {
if (!isFirstCharMatching(name, nameIndex, patternIndex)) {
return 0;
}
int i = 1;
boolean ignoreCase = myOptions != NameUtil.MatchingCaseSensitivity.ALL;
while (nameIndex + i < name.length() && patternIndex + i < myPattern.length) {
char nameChar = name.charAt(nameIndex + i);
if (!charEquals(myPattern[patternIndex + i], patternIndex + i, nameChar, ignoreCase)) {
if (isSkippingDigitBetweenPatternDigits(patternIndex + i, nameChar)) {
return 0;
}
break;
}
i++;
}
return i;
}
private boolean isSkippingDigitBetweenPatternDigits(int patternIndex, char nameChar) {
return Character.isDigit(myPattern[patternIndex]) && Character.isDigit(myPattern[patternIndex - 1]) && Character.isDigit(nameChar);
}
// we've found the longest fragment matching pattern and name
@Nullable
private FList<TextRange> matchInsideFragment(@NotNull String name,
int patternIndex,
int nameIndex,
boolean isAsciiName,
int fragmentLength) {
// exact middle matches have to be at least of length 3, to prevent too many irrelevant matches
int minFragment = isMiddleMatch(name, patternIndex, nameIndex)
? 3 : 1;
FList<TextRange> camelHumpRanges = improveCamelHumps(name, patternIndex, nameIndex, isAsciiName, fragmentLength, minFragment);
if (camelHumpRanges != null) {
return camelHumpRanges;
}
return findLongestMatchingPrefix(name, patternIndex, nameIndex, isAsciiName, fragmentLength, minFragment);
}
private boolean isMiddleMatch(@NotNull String name, int patternIndex, int nameIndex) {
return isPatternChar(patternIndex - 1, '*') && !isWildcard(patternIndex + 1) &&
Character.isLetterOrDigit(name.charAt(nameIndex)) && !NameUtilCore.isWordStart(name, nameIndex);
}
@Nullable
private FList<TextRange> findLongestMatchingPrefix(@NotNull String name,
int patternIndex,
int nameIndex,
boolean isAsciiName,
int fragmentLength, int minFragment) {
if (patternIndex + fragmentLength >= myPattern.length) {
return FList.<TextRange>emptyList().prepend(TextRange.from(nameIndex, fragmentLength));
}
// try to match the remainder of pattern with the remainder of name
// it may not succeed with the longest matching fragment, then try shorter matches
int i = fragmentLength;
while (i >= minFragment || (i > 0 && isWildcard(patternIndex + i))) {
FList<TextRange> ranges;
if (isWildcard(patternIndex + i)) {
ranges = matchWildcards(name, patternIndex + i, nameIndex + i, isAsciiName);
}
else {
int nextOccurrence = findNextPatternCharOccurrence(name, nameIndex + i + 1, patternIndex + i, isAsciiName);
nextOccurrence = checkForSpecialChars(name, nameIndex + i, nextOccurrence, patternIndex + i);
if (nextOccurrence >= 0) {
ranges = matchSkippingWords(name, patternIndex + i, nextOccurrence, false, isAsciiName);
} else {
ranges = null;
}
}
if (ranges != null) {
return prependRange(ranges, nameIndex, i);
}
i--;
}
return null;
}
/**
* When pattern is "CU" and the name is "CurrentUser", we already have a prefix "Cu" that matches,
* but we try to find uppercase "U" later in name for better matching degree
*/
private FList<TextRange> improveCamelHumps(@NotNull String name,
int patternIndex,
int nameIndex,
boolean isAsciiName,
int maxFragment,
int minFragment) {
for (int i = minFragment; i < maxFragment; i++) {
if (isUppercasePatternVsLowercaseNameChar(name, patternIndex + i, nameIndex + i)) {
FList<TextRange> ranges = findUppercaseMatchFurther(name, patternIndex + i, nameIndex + i, isAsciiName);
if (ranges != null) {
return prependRange(ranges, nameIndex, i);
}
}
}
return null;
}
private boolean isUppercasePatternVsLowercaseNameChar(String name, int patternIndex, int nameIndex) {
return isUpperCase[patternIndex] && myPattern[patternIndex] != name.charAt(nameIndex);
}
private FList<TextRange> findUppercaseMatchFurther(String name,
int patternIndex,
int nameIndex,
boolean isAsciiName) {
int nextWordStart = indexOfWordStart(name, patternIndex, nameIndex, isAsciiName);
return matchWildcards(name, patternIndex, nextWordStart, isAsciiName);
}
private boolean isFirstCharMatching(@NotNull String name, int nameIndex, int patternIndex) {
if (nameIndex >= name.length()) return false;
boolean ignoreCase = myOptions != NameUtil.MatchingCaseSensitivity.ALL;
char patternChar = myPattern[patternIndex];
if (!charEquals(patternChar, patternIndex, name.charAt(nameIndex), ignoreCase)) return false;
if (myOptions == NameUtil.MatchingCaseSensitivity.FIRST_LETTER &&
(patternIndex == 0 || patternIndex == 1 && isWildcard(0)) &&
hasCase(patternChar) &&
Character.isUpperCase(patternChar) != Character.isUpperCase(name.charAt(0))) {
return false;
}
return true;
}
private static boolean hasCase(char patternChar) {
return Character.isUpperCase(patternChar) || Character.isLowerCase(patternChar);
}
private boolean isWildcard(int patternIndex) {
if (patternIndex >= 0 && patternIndex < myPattern.length) {
char pc = myPattern[patternIndex];
return pc == ' ' || pc == '*';
}
return false;
}
private boolean isPatternChar(int patternIndex, char c) {
return patternIndex >= 0 && patternIndex < myPattern.length && myPattern[patternIndex] == c;
}
private int indexOfWordStart(@NotNull String name, int patternIndex, int startFrom, boolean isAsciiName) {
final char p = myPattern[patternIndex];
if (startFrom >= name.length() ||
myHasHumps && isLowerCase[patternIndex] && !(patternIndex > 0 && isWordSeparator[patternIndex - 1])) {
return -1;
}
int i = startFrom;
boolean isSpecialSymbol = !Character.isLetterOrDigit(p);
while (true) {
i = indexOfIgnoreCase(name, i, p, patternIndex, isAsciiName);
if (i < 0) return -1;
if (isSpecialSymbol || NameUtilCore.isWordStart(name, i)) return i;
i++;
}
}
private int indexOfIgnoreCase(String name, int fromIndex, char p, int patternIndex, boolean isAsciiName) {
if (isAsciiName && Strings.isAscii(p)) {
char pUpper = toUpperCase[patternIndex];
char pLower = toLowerCase[patternIndex];
for (int i = fromIndex; i < name.length(); i++) {
char c = name.charAt(i);
if (c == p || toUpperAscii(c) == pUpper || toLowerAscii(c) == pLower) {
return i;
}
}
return -1;
}
return Strings.indexOfIgnoreCase(name, p, fromIndex);
}
private static char toUpperAscii(char c) {
if (c >= 'a' && c <= 'z') {
return (char)(c + ('A' - 'a'));
}
return c;
}
private static char toLowerAscii(char c) {
if (c >= 'A' && c <= 'Z') {
return (char)(c - ('A' - 'a'));
}
return c;
}
@NonNls
@Override
public String toString() {
return "MinusculeMatcherImpl{myPattern=" + new String(myPattern) + ", myOptions=" + myOptions + '}';
}
}
| apache-2.0 |
ysung-pivotal/incubator-geode | gemfire-core/src/test/java/com/gemstone/gemfire/internal/offheap/InlineKeyJUnitTest.java | 8913 | package com.gemstone.gemfire.internal.offheap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Properties;
import java.util.UUID;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionShortcut;
import com.gemstone.gemfire.cache.util.ObjectSizer;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.VMThinRegionEntryOffHeapIntKey;
import com.gemstone.gemfire.internal.cache.VMThinRegionEntryOffHeapLongKey;
import com.gemstone.gemfire.internal.cache.VMThinRegionEntryOffHeapObjectKey;
import com.gemstone.gemfire.internal.cache.VMThinRegionEntryOffHeapStringKey1;
import com.gemstone.gemfire.internal.cache.VMThinRegionEntryOffHeapStringKey2;
import com.gemstone.gemfire.internal.cache.VMThinRegionEntryOffHeapUUIDKey;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
@Category(IntegrationTest.class)
public class InlineKeyJUnitTest {
private GemFireCacheImpl createCache() {
Properties props = new Properties();
props.setProperty("locators", "");
props.setProperty("mcast-port", "0");
props.setProperty("off-heap-memory-size", "1m");
GemFireCacheImpl result = (GemFireCacheImpl) new CacheFactory(props).create();
return result;
}
private void closeCache(GemFireCacheImpl gfc) {
gfc.close();
}
@Test
public void testInlineKeys() {
GemFireCacheImpl gfc = createCache();
try {
Region r = gfc.createRegionFactory(RegionShortcut.LOCAL).setConcurrencyChecksEnabled(false).setOffHeap(true).create("inlineKeyRegion");
LocalRegion lr = (LocalRegion) r;
Object key = Integer.valueOf(1);
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected int entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapIntKey);
key = Long.valueOf(2);
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected long entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapLongKey);
key = new UUID(1L, 2L);
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected uuid entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapUUIDKey);
key = "";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey1);
key = "1";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey1);
key = "12";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey1);
key = "123";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey1);
key = "1234";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey1);
key = "12345";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey1);
key = "123456";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey1);
key = "1234567";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey1);
key = "12345678";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey2);
key = "123456789";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey2);
key = "1234567890";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey2);
key = "12345678901";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey2);
key = "123456789012";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey2);
key = "1234567890123";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey2);
key = "12345678901234";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey2);
key = "123456789012345";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string entry but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapStringKey2);
key = "1234567890123456";
r.create(key, null);
assertEquals(true, r.containsKey(key));
assertTrue("expected string object but was " + lr.getRegionEntry(key).getClass(), lr.getRegionEntry(key) instanceof VMThinRegionEntryOffHeapObjectKey);
} finally {
closeCache(gfc);
}
}
private static int getMemSize(Object o) {
return ObjectSizer.REFLECTION_SIZE.sizeof(o);
}
@Test
public void testMemoryOverhead() {
Object re = new VMThinRegionEntryOffHeapIntKey(null, 1, null);
//System.out.println("VMThinRegionEntryIntKey=" + getMemSize(re));
Object re2 = new VMThinRegionEntryOffHeapObjectKey(null, 1, null);
//System.out.println("VMThinRegionEntryObjectKey=" + getMemSize(re2));
assertTrue(getMemSize(re) < getMemSize(re2));
re = new VMThinRegionEntryOffHeapLongKey(null, 1L, null);
//System.out.println("VMThinRegionEntryLongKey=" + getMemSize(re));
re2 = new VMThinRegionEntryOffHeapObjectKey(null, 1L, null);
//System.out.println("VMThinRegionEntryObjectKey=" + getMemSize(re2));
assertTrue(getMemSize(re) < getMemSize(re2));
re = new VMThinRegionEntryOffHeapUUIDKey(null, new UUID(1L, 2L), null);
//System.out.println("VMThinRegionEntryUUIDKey=" + getMemSize(re));
re2 = new VMThinRegionEntryOffHeapObjectKey(null, new UUID(1L, 2L), null);
//System.out.println("VMThinRegionEntryObjectKey=" + getMemSize(re2));
assertTrue(getMemSize(re) < getMemSize(re2));
re = new VMThinRegionEntryOffHeapStringKey1(null, "1234567", null, true);
//System.out.println("VMThinRegionEntryStringKey1=" + getMemSize(re));
re2 = new VMThinRegionEntryOffHeapObjectKey(null, "1234567", null);
//System.out.println("VMThinRegionEntryObjectKey=" + getMemSize(re2));
assertTrue(getMemSize(re) < getMemSize(re2));
re = new VMThinRegionEntryOffHeapStringKey2(null, "123456789012345", null, true);
//System.out.println("VMThinRegionEntryStringKey2=" + getMemSize(re));
re2 = new VMThinRegionEntryOffHeapObjectKey(null, "123456789012345", null);
//System.out.println("VMThinRegionEntryObjectKey=" + getMemSize(re2));
assertTrue(getMemSize(re) < getMemSize(re2));
}
}
| apache-2.0 |
kidaa/isis | core/viewer-wicket/ui/src/main/java/org/apache/isis/viewer/wicket/ui/components/scalars/jdkdates/JavaSqlTimePanelFactory.java | 1618 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.viewer.wicket.ui.components.scalars.jdkdates;
import org.apache.wicket.Component;
import org.apache.isis.viewer.wicket.model.models.ScalarModel;
import org.apache.isis.viewer.wicket.ui.ComponentFactory;
import org.apache.isis.viewer.wicket.ui.components.scalars.ComponentFactoryScalarAbstract;
/**
* {@link ComponentFactory} for {@link JavaSqlTimePanel}.
*/
public class JavaSqlTimePanelFactory extends ComponentFactoryScalarAbstract {
private static final long serialVersionUID = 1L;
public JavaSqlTimePanelFactory() {
super(JavaSqlTimePanel.class, java.util.Date.class);
}
@Override
public Component createComponent(final String id, final ScalarModel scalarModel) {
return new JavaSqlTimePanel(id, scalarModel);
}
}
| apache-2.0 |
ict-carch/hadoop-plus | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationStateDataPBImpl.java | 4213 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb;
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationSubmissionContextPBImpl;
import org.apache.hadoop.yarn.api.records.impl.pb.ProtoBase;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProto;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProtoOrBuilder;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData;
public class ApplicationStateDataPBImpl
extends ProtoBase<ApplicationStateDataProto>
implements ApplicationStateData {
ApplicationStateDataProto proto =
ApplicationStateDataProto.getDefaultInstance();
ApplicationStateDataProto.Builder builder = null;
boolean viaProto = false;
private ApplicationSubmissionContext applicationSubmissionContext = null;
public ApplicationStateDataPBImpl() {
builder = ApplicationStateDataProto.newBuilder();
}
public ApplicationStateDataPBImpl(
ApplicationStateDataProto proto) {
this.proto = proto;
viaProto = true;
}
public ApplicationStateDataProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
private void mergeLocalToBuilder() {
if (this.applicationSubmissionContext != null) {
builder.setApplicationSubmissionContext(
((ApplicationSubmissionContextPBImpl)applicationSubmissionContext)
.getProto());
}
}
private void mergeLocalToProto() {
if (viaProto)
maybeInitBuilder();
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = ApplicationStateDataProto.newBuilder(proto);
}
viaProto = false;
}
@Override
public long getSubmitTime() {
ApplicationStateDataProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasSubmitTime()) {
return -1;
}
return (p.getSubmitTime());
}
@Override
public void setSubmitTime(long submitTime) {
maybeInitBuilder();
builder.setSubmitTime(submitTime);
}
@Override
public String getUser() {
ApplicationStateDataProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasUser()) {
return null;
}
return (p.getUser());
}
@Override
public void setUser(String user) {
maybeInitBuilder();
builder.setUser(user);
}
@Override
public ApplicationSubmissionContext getApplicationSubmissionContext() {
ApplicationStateDataProtoOrBuilder p = viaProto ? proto : builder;
if(applicationSubmissionContext != null) {
return applicationSubmissionContext;
}
if (!p.hasApplicationSubmissionContext()) {
return null;
}
applicationSubmissionContext =
new ApplicationSubmissionContextPBImpl(
p.getApplicationSubmissionContext());
return applicationSubmissionContext;
}
@Override
public void setApplicationSubmissionContext(
ApplicationSubmissionContext context) {
maybeInitBuilder();
if (context == null) {
builder.clearApplicationSubmissionContext();
}
this.applicationSubmissionContext = context;
}
}
| apache-2.0 |
drewwills/uPortal | uportal-war/src/main/java/org/jasig/portal/utils/DocumentFactory.java | 4747 | /**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.portal.utils;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.portal.utils.threading.SingletonDoubleCheckedCreator;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Produces an empty Document implementation
* @author Bernie Durfee, bdurfee@interactivebusiness.com
* @version $Revision$
*/
public final class DocumentFactory {
private static final Log log = LogFactory.getLog(DocumentFactory.class);
protected static final SingletonDoubleCheckedCreator<DocumentBuilderFactory> documentBuilderFactoryInstance = new DocumentBuilderFactoryCreator();
protected static final ThreadLocal<DocumentBuilder> localDocumentBuilder = new DocumentBuilderLocal();
/**
* Returns a new copy of a Document implementation. This will
* return an <code>IPortalDocument</code> implementation.
* @return an empty org.w3c.dom.Document implementation
*/
public static Document getThreadDocument() {
return getThreadDocumentBuilder().newDocument();
}
public static Document getDocumentFromStream(InputStream stream, String publicId) throws IOException, SAXException {
DocumentBuilder builder = getThreadDocumentBuilder();
InputSource source = new InputSource(stream);
source.setPublicId(publicId);
Document doc = builder.parse(source);
return doc;
}
public static Document getDocumentFromStream(InputStream stream, EntityResolver er, String publicId)
throws IOException, SAXException {
DocumentBuilder builder = getThreadDocumentBuilder();
builder.setEntityResolver(er);
InputSource source = new InputSource(stream);
source.setPublicId(publicId);
Document doc = builder.parse(source);
return doc;
}
/**
* @return The DocumentBuilder for the current thread. The returned references should NEVER be retained outside of the stack.
*/
public static DocumentBuilder getThreadDocumentBuilder() {
return localDocumentBuilder.get();
}
private static final class DocumentBuilderFactoryCreator extends
SingletonDoubleCheckedCreator<DocumentBuilderFactory> {
@Override
protected DocumentBuilderFactory createSingleton(Object... args) {
final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setValidating(false);
return dbFactory;
}
}
private static final class DocumentBuilderLocal extends ThreadLocal<DocumentBuilder> {
@Override
protected DocumentBuilder initialValue() {
final DocumentBuilderFactory documentBuilderFactory = documentBuilderFactoryInstance.get();
try {
return documentBuilderFactory.newDocumentBuilder();
}
catch (ParserConfigurationException e) {
throw new IllegalStateException("Failed to create new DocumentBuilder for thread: " + Thread.currentThread().getName(), e);
}
}
@Override
public DocumentBuilder get() {
DocumentBuilder documentBuilder = super.get();
//Handle a DocumentBuilder not getting created correctly
if (documentBuilder == null) {
log.warn("No DocumentBuilder existed for this thread, an initialValue() call must have failed");
documentBuilder = this.initialValue();
this.set(documentBuilder);
}
return documentBuilder;
}
}
}
| apache-2.0 |
vigosser/lemon | src/main/java/com/mossle/model/persistence/manager/ModelInfoManager.java | 285 | package com.mossle.model.persistence.manager;
import com.mossle.core.hibernate.HibernateEntityDao;
import com.mossle.model.persistence.domain.ModelInfo;
import org.springframework.stereotype.Service;
@Service
public class ModelInfoManager extends HibernateEntityDao<ModelInfo> {
}
| apache-2.0 |
asurve/arvind-sysml | src/main/java/org/apache/sysml/lops/AppendM.java | 3752 | /*
* 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.sysml.lops;
import org.apache.sysml.lops.LopProperties.ExecLocation;
import org.apache.sysml.lops.LopProperties.ExecType;
import org.apache.sysml.lops.compile.JobType;
import org.apache.sysml.parser.Expression.*;
public class AppendM extends Lop
{
public static final String OPCODE = "mappend";
public enum CacheType {
RIGHT,
RIGHT_PART,
}
private boolean _cbind = true;
private CacheType _cacheType = null;
public AppendM(Lop input1, Lop input2, Lop input3, DataType dt, ValueType vt, boolean cbind, boolean partitioned, ExecType et)
{
super(Lop.Type.Append, dt, vt);
init(input1, input2, input3, dt, vt, et);
_cbind = cbind;
_cacheType = partitioned ? CacheType.RIGHT_PART : CacheType.RIGHT;
}
public void init(Lop input1, Lop input2, Lop input3, DataType dt, ValueType vt, ExecType et)
{
addInput(input1);
input1.addOutput(this);
addInput(input2);
input2.addOutput(this);
addInput(input3);
input3.addOutput(this);
boolean breaksAlignment = false;
boolean aligner = false;
boolean definesMRJob = false;
if( et == ExecType.MR )
{
lps.addCompatibility(JobType.GMR);
lps.setProperties( inputs, ExecType.MR, ExecLocation.Map, breaksAlignment, aligner, definesMRJob );
}
else //SPARK
{
lps.addCompatibility(JobType.INVALID);
lps.setProperties( inputs, ExecType.SPARK, ExecLocation.ControlProgram, breaksAlignment, aligner, definesMRJob );
}
}
@Override
public String toString() {
return "Operation = AppendM";
}
//called when append executes in MR
public String getInstructions(int input_index1, int input_index2, int input_index3, int output_index)
throws LopsException
{
return getInstructions(
String.valueOf(input_index1),
String.valueOf(input_index2),
String.valueOf(input_index3),
String.valueOf(output_index) );
}
//called when append executes in SP
public String getInstructions(String input1, String input2, String input3, String output)
throws LopsException
{
StringBuilder sb = new StringBuilder();
sb.append( getExecType() );
sb.append( OPERAND_DELIMITOR );
sb.append( OPCODE );
sb.append( OPERAND_DELIMITOR );
sb.append( getInputs().get(0).prepInputOperand(input1));
sb.append( OPERAND_DELIMITOR );
sb.append( getInputs().get(1).prepInputOperand(input2));
sb.append( OPERAND_DELIMITOR );
sb.append( getInputs().get(2).prepScalarInputOperand(getExecType()));
sb.append( OPERAND_DELIMITOR );
sb.append( prepOutputOperand(output) );
//note: for SP: no cache type
if( getExecType()==ExecType.MR ){
sb.append(Lop.OPERAND_DELIMITOR);
sb.append(_cacheType);
}
sb.append( OPERAND_DELIMITOR );
sb.append( _cbind );
return sb.toString();
}
public boolean usesDistributedCache() {
return true;
}
public int[] distributedCacheInputIndex() {
return new int[]{2}; // second input is from distributed cache
}
}
| apache-2.0 |
saurabh2590/Library-ZXING1 | src/com/google/zxing/client/android/PreferencesActivity.java | 3996 | /*
* Copyright (C) 2008 ZXing 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.zxing.client.android;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import java.util.ArrayList;
import java.util.Collection;
/**
* The main settings activity.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class PreferencesActivity extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
public static final String KEY_DECODE_1D = "preferences_decode_1D";
public static final String KEY_DECODE_QR = "preferences_decode_QR";
public static final String KEY_DECODE_DATA_MATRIX = "preferences_decode_Data_Matrix";
public static final String KEY_CUSTOM_PRODUCT_SEARCH = "preferences_custom_product_search";
public static final String KEY_PLAY_BEEP = "preferences_play_beep";
public static final String KEY_VIBRATE = "preferences_vibrate";
public static final String KEY_COPY_TO_CLIPBOARD = "preferences_copy_to_clipboard";
public static final String KEY_FRONT_LIGHT_MODE = "preferences_front_light_mode";
public static final String KEY_BULK_MODE = "preferences_bulk_mode";
public static final String KEY_REMEMBER_DUPLICATES = "preferences_remember_duplicates";
public static final String KEY_SUPPLEMENTAL = "preferences_supplemental";
public static final String KEY_AUTO_FOCUS = "preferences_auto_focus";
public static final String KEY_INVERT_SCAN = "preferences_invert_scan";
public static final String KEY_SEARCH_COUNTRY = "preferences_search_country";
public static final String KEY_DISABLE_CONTINUOUS_FOCUS = "preferences_disable_continuous_focus";
//public static final String KEY_DISABLE_EXPOSURE = "preferences_disable_exposure";
public static final String KEY_HELP_VERSION_SHOWN = "preferences_help_version_shown";
private CheckBoxPreference decode1D;
private CheckBoxPreference decodeQR;
private CheckBoxPreference decodeDataMatrix;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.preferences);
PreferenceScreen preferences = getPreferenceScreen();
preferences.getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
decode1D = (CheckBoxPreference) preferences.findPreference(KEY_DECODE_1D);
decodeQR = (CheckBoxPreference) preferences.findPreference(KEY_DECODE_QR);
decodeDataMatrix = (CheckBoxPreference) preferences.findPreference(KEY_DECODE_DATA_MATRIX);
disableLastCheckedPref();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
disableLastCheckedPref();
}
private void disableLastCheckedPref() {
Collection<CheckBoxPreference> checked = new ArrayList<CheckBoxPreference>(3);
if (decode1D.isChecked()) {
checked.add(decode1D);
}
if (decodeQR.isChecked()) {
checked.add(decodeQR);
}
if (decodeDataMatrix.isChecked()) {
checked.add(decodeDataMatrix);
}
boolean disable = checked.size() < 2;
CheckBoxPreference[] checkBoxPreferences = {decode1D, decodeQR, decodeDataMatrix};
for (CheckBoxPreference pref : checkBoxPreferences) {
pref.setEnabled(!(disable && checked.contains(pref)));
}
}
}
| apache-2.0 |
nmcl/scratch | graalvm/transactions/fork/narayana/XTS/WS-T/dev/src/com/arjuna/webservices11/wsba/CoordinatorCompletionParticipantInboundEvents.java | 4351 | /*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2005-2006,
* @author JBoss Inc.
*/
package com.arjuna.webservices11.wsba;
import com.arjuna.webservices.SoapFault;
import com.arjuna.webservices11.wsarj.ArjunaContext;
import org.jboss.ws.api.addressing.MAP;
import org.oasis_open.docs.ws_tx.wsba._2006._06.NotificationType;
import org.oasis_open.docs.ws_tx.wsba._2006._06.StatusType;
/**
* The Participant events.
*/
public interface CoordinatorCompletionParticipantInboundEvents
{
/**
* Handle the cancel event.
* @param cancel The cancel notification.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void cancel(final NotificationType cancel, final MAP map, final ArjunaContext arjunaContext) ;
/**
* Handle the close event.
* @param close The close notification.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void close(final NotificationType close, final MAP map, final ArjunaContext arjunaContext) ;
/**
* Handle the compensate event.
* @param compensate The compensate notification.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void compensate(final NotificationType compensate, final MAP map, final ArjunaContext arjunaContext) ;
/**
* Handle the complete event.
* @param complete The complete notification.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void complete(final NotificationType complete, final MAP map, final ArjunaContext arjunaContext) ;
/**
* Handle the exited event.
* @param exited The exited notification.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void exited(final NotificationType exited, final MAP map, final ArjunaContext arjunaContext) ;
/**
* Handle the failed event.
* @param failed The failed notification.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void failed(final NotificationType failed, final MAP map, final ArjunaContext arjunaContext) ;
/**
* Handle the not completed event.
* @param notCompleted The not completed notification.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void notCompleted(final NotificationType notCompleted, final MAP map, final ArjunaContext arjunaContext) ;
/**
* Handle the getStatus event.
* @param getStatus The getStatus notification.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void getStatus(final NotificationType getStatus, final MAP map, final ArjunaContext arjunaContext) ;
/**
* Handle the status event.
* @param status The status type.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void status(final StatusType status, final MAP map, final ArjunaContext arjunaContext) ;
/**
* Handle the soap fault event.
* @param soapFault The soap fault.
* @param map The addressing context.
* @param arjunaContext The arjuna context.
*/
public void soapFault(final SoapFault soapFault, final MAP map, final ArjunaContext arjunaContext) ;
}
| apache-2.0 |
YolandaMDavis/nifi | nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/test/java/org/apache/nifi/processors/standard/TestListenRELP.java | 14620 | /*
* 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.nifi.processors.standard;
import java.io.IOException;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import javax.net.ssl.SSLContext;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSessionFactory;
import org.apache.nifi.processor.util.listen.dispatcher.ChannelDispatcher;
import org.apache.nifi.processor.util.listen.response.ChannelResponder;
import org.apache.nifi.processors.standard.relp.event.RELPEvent;
import org.apache.nifi.processors.standard.relp.frame.RELPEncoder;
import org.apache.nifi.processors.standard.relp.frame.RELPFrame;
import org.apache.nifi.processors.standard.relp.response.RELPResponse;
import org.apache.nifi.provenance.ProvenanceEventRecord;
import org.apache.nifi.provenance.ProvenanceEventType;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.security.util.SslContextFactory;
import org.apache.nifi.ssl.SSLContextService;
import org.apache.nifi.ssl.StandardSSLContextService;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
public class TestListenRELP {
// TODO: The NiFi SSL classes don't yet support TLSv1.3, so set the CS version explicitly
private static final String TLS_PROTOCOL_VERSION = "TLSv1.2";
public static final String OPEN_FRAME_DATA = "relp_version=0\nrelp_software=librelp,1.2.7,http://librelp.adiscon.com\ncommands=syslog";
public static final String SYSLOG_FRAME_DATA = "this is a syslog message here";
static final RELPFrame OPEN_FRAME = new RELPFrame.Builder()
.txnr(1)
.command("open")
.dataLength(OPEN_FRAME_DATA.length())
.data(OPEN_FRAME_DATA.getBytes(StandardCharsets.UTF_8))
.build();
static final RELPFrame SYSLOG_FRAME = new RELPFrame.Builder()
.txnr(2)
.command("syslog")
.dataLength(SYSLOG_FRAME_DATA.length())
.data(SYSLOG_FRAME_DATA.getBytes(StandardCharsets.UTF_8))
.build();
static final RELPFrame CLOSE_FRAME = new RELPFrame.Builder()
.txnr(3)
.command("close")
.dataLength(0)
.data(new byte[0])
.build();
private RELPEncoder encoder;
private ResponseCapturingListenRELP proc;
private TestRunner runner;
@Before
public void setup() {
encoder = new RELPEncoder(StandardCharsets.UTF_8);
proc = new ResponseCapturingListenRELP();
runner = TestRunners.newTestRunner(proc);
runner.setProperty(ListenRELP.PORT, "0");
}
@Test
public void testListenRELP() throws IOException, InterruptedException {
final List<RELPFrame> frames = new ArrayList<>();
frames.add(OPEN_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(CLOSE_FRAME);
// three syslog frames should be transferred and three responses should be sent
run(frames, 3, 3, null);
final List<ProvenanceEventRecord> events = runner.getProvenanceEvents();
Assert.assertNotNull(events);
Assert.assertEquals(3, events.size());
final ProvenanceEventRecord event = events.get(0);
Assert.assertEquals(ProvenanceEventType.RECEIVE, event.getEventType());
Assert.assertTrue("transit uri must be set and start with proper protocol", event.getTransitUri().toLowerCase().startsWith("relp"));
final List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenRELP.REL_SUCCESS);
Assert.assertEquals(3, mockFlowFiles.size());
final MockFlowFile mockFlowFile = mockFlowFiles.get(0);
Assert.assertEquals(String.valueOf(SYSLOG_FRAME.getTxnr()), mockFlowFile.getAttribute(ListenRELP.RELPAttributes.TXNR.key()));
Assert.assertEquals(SYSLOG_FRAME.getCommand(), mockFlowFile.getAttribute(ListenRELP.RELPAttributes.COMMAND.key()));
Assert.assertTrue(!StringUtils.isBlank(mockFlowFile.getAttribute(ListenRELP.RELPAttributes.PORT.key())));
Assert.assertTrue(!StringUtils.isBlank(mockFlowFile.getAttribute(ListenRELP.RELPAttributes.SENDER.key())));
}
@Test
public void testBatching() throws IOException, InterruptedException {
runner.setProperty(ListenRELP.MAX_BATCH_SIZE, "5");
final List<RELPFrame> frames = new ArrayList<>();
frames.add(OPEN_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(CLOSE_FRAME);
// one syslog frame should be transferred since we are batching, but three responses should be sent
run(frames, 1, 3, null);
final List<ProvenanceEventRecord> events = runner.getProvenanceEvents();
Assert.assertNotNull(events);
Assert.assertEquals(1, events.size());
final ProvenanceEventRecord event = events.get(0);
Assert.assertEquals(ProvenanceEventType.RECEIVE, event.getEventType());
Assert.assertTrue("transit uri must be set and start with proper protocol", event.getTransitUri().toLowerCase().startsWith("relp"));
final List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenRELP.REL_SUCCESS);
Assert.assertEquals(1, mockFlowFiles.size());
final MockFlowFile mockFlowFile = mockFlowFiles.get(0);
Assert.assertEquals(SYSLOG_FRAME.getCommand(), mockFlowFile.getAttribute(ListenRELP.RELPAttributes.COMMAND.key()));
Assert.assertTrue(!StringUtils.isBlank(mockFlowFile.getAttribute(ListenRELP.RELPAttributes.PORT.key())));
Assert.assertTrue(!StringUtils.isBlank(mockFlowFile.getAttribute(ListenRELP.RELPAttributes.SENDER.key())));
}
@Test
public void testTLS() throws InitializationException, IOException, InterruptedException {
final SSLContextService sslContextService = new StandardSSLContextService();
runner.addControllerService("ssl-context", sslContextService);
runner.setProperty(sslContextService, StandardSSLContextService.SSL_ALGORITHM, TLS_PROTOCOL_VERSION);
runner.setProperty(sslContextService, StandardSSLContextService.TRUSTSTORE, "src/test/resources/truststore.jks");
runner.setProperty(sslContextService, StandardSSLContextService.TRUSTSTORE_PASSWORD, "passwordpassword");
runner.setProperty(sslContextService, StandardSSLContextService.TRUSTSTORE_TYPE, "JKS");
runner.setProperty(sslContextService, StandardSSLContextService.KEYSTORE, "src/test/resources/keystore.jks");
runner.setProperty(sslContextService, StandardSSLContextService.KEYSTORE_PASSWORD, "passwordpassword");
runner.setProperty(sslContextService, StandardSSLContextService.KEYSTORE_TYPE, "JKS");
runner.enableControllerService(sslContextService);
runner.setProperty(ListenRELP.SSL_CONTEXT_SERVICE, "ssl-context");
final List<RELPFrame> frames = new ArrayList<>();
frames.add(OPEN_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(SYSLOG_FRAME);
frames.add(CLOSE_FRAME);
// three syslog frames should be transferred and three responses should be sent
run(frames, 5, 5, sslContextService);
}
@Test
public void testNoEventsAvailable() throws IOException, InterruptedException {
MockListenRELP mockListenRELP = new MockListenRELP(new ArrayList<RELPEvent>());
runner = TestRunners.newTestRunner(mockListenRELP);
runner.setProperty(ListenRELP.PORT, "1");
runner.run();
runner.assertAllFlowFilesTransferred(ListenRELP.REL_SUCCESS, 0);
}
@Test
public void testBatchingWithDifferentSenders() throws IOException, InterruptedException {
final String sender1 = "sender1";
final String sender2 = "sender2";
final ChannelResponder<SocketChannel> responder = Mockito.mock(ChannelResponder.class);
final List<RELPEvent> mockEvents = new ArrayList<>();
mockEvents.add(new RELPEvent(sender1, SYSLOG_FRAME.getData(), responder, SYSLOG_FRAME.getTxnr(), SYSLOG_FRAME.getCommand()));
mockEvents.add(new RELPEvent(sender1, SYSLOG_FRAME.getData(), responder, SYSLOG_FRAME.getTxnr(), SYSLOG_FRAME.getCommand()));
mockEvents.add(new RELPEvent(sender2, SYSLOG_FRAME.getData(), responder, SYSLOG_FRAME.getTxnr(), SYSLOG_FRAME.getCommand()));
mockEvents.add(new RELPEvent(sender2, SYSLOG_FRAME.getData(), responder, SYSLOG_FRAME.getTxnr(), SYSLOG_FRAME.getCommand()));
MockListenRELP mockListenRELP = new MockListenRELP(mockEvents);
runner = TestRunners.newTestRunner(mockListenRELP);
runner.setProperty(ListenRELP.PORT, "1");
runner.setProperty(ListenRELP.MAX_BATCH_SIZE, "10");
runner.run();
runner.assertAllFlowFilesTransferred(ListenRELP.REL_SUCCESS, 2);
}
protected void run(final List<RELPFrame> frames, final int expectedTransferred, final int expectedResponses, final SSLContextService sslContextService)
throws IOException, InterruptedException {
Socket socket = null;
try {
// schedule to start listening on a random port
final ProcessSessionFactory processSessionFactory = runner.getProcessSessionFactory();
final ProcessContext context = runner.getProcessContext();
proc.onScheduled(context);
// create a client connection to the port the dispatcher is listening on
final int realPort = proc.getDispatcherPort();
// create either a regular socket or ssl socket based on context being passed in
if (sslContextService != null) {
final SSLContext sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.REQUIRED);
socket = sslContext.getSocketFactory().createSocket("localhost", realPort);
} else {
socket = new Socket("localhost", realPort);
}
Thread.sleep(100);
// send the frames to the port the processors is listening on
sendFrames(frames, socket);
long responseTimeout = 30000;
// this first loop waits until the internal queue of the processor has the expected
// number of messages ready before proceeding, we want to guarantee they are all there
// before onTrigger gets a chance to run
long startTimeQueueSizeCheck = System.currentTimeMillis();
while (proc.getQueueSize() < expectedResponses
&& (System.currentTimeMillis() - startTimeQueueSizeCheck < responseTimeout)) {
Thread.sleep(100);
}
// want to fail here if the queue size isn't what we expect
Assert.assertEquals(expectedResponses, proc.getQueueSize());
// call onTrigger until we got a respond for all the frames, or a certain amount of time passes
long startTimeProcessing = System.currentTimeMillis();
while (proc.responses.size() < expectedResponses
&& (System.currentTimeMillis() - startTimeProcessing < responseTimeout)) {
proc.onTrigger(context, processSessionFactory);
Thread.sleep(100);
}
// should have gotten a response for each frame
Assert.assertEquals(expectedResponses, proc.responses.size());
// should have transferred the expected events
runner.assertTransferCount(ListenRELP.REL_SUCCESS, expectedTransferred);
} finally {
// unschedule to close connections
proc.onUnscheduled();
IOUtils.closeQuietly(socket);
}
}
private void sendFrames(final List<RELPFrame> frames, final Socket socket) throws IOException, InterruptedException {
// send the provided messages
for (final RELPFrame frame : frames) {
byte[] encodedFrame = encoder.encode(frame);
socket.getOutputStream().write(encodedFrame);
}
socket.getOutputStream().flush();
}
// Extend ListenRELP so we can use the CapturingSocketChannelResponseDispatcher
private static class ResponseCapturingListenRELP extends ListenRELP {
private List<RELPResponse> responses = new ArrayList<>();
@Override
protected void respond(RELPEvent event, RELPResponse relpResponse) {
this.responses.add(relpResponse);
super.respond(event, relpResponse);
}
}
// Extend ListenRELP to mock the ChannelDispatcher and allow us to return staged events
private static class MockListenRELP extends ListenRELP {
private List<RELPEvent> mockEvents;
public MockListenRELP(List<RELPEvent> mockEvents) {
this.mockEvents = mockEvents;
}
@OnScheduled
@Override
public void onScheduled(ProcessContext context) throws IOException {
super.onScheduled(context);
events.addAll(mockEvents);
}
@Override
protected ChannelDispatcher createDispatcher(ProcessContext context, BlockingQueue<RELPEvent> events) throws IOException {
return Mockito.mock(ChannelDispatcher.class);
}
}
}
| apache-2.0 |
intel-hadoop/incubator-sentry | sentry-provider/sentry-provider-db/src/gen/thrift/gen-javabean/org/apache/sentry/provider/db/service/thrift/TSentryPrivilegeMap.java | 16784 | /**
* Autogenerated by Thrift Compiler (0.9.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.sentry.provider.db.service.thrift;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TSentryPrivilegeMap implements org.apache.thrift.TBase<TSentryPrivilegeMap, TSentryPrivilegeMap._Fields>, java.io.Serializable, Cloneable {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TSentryPrivilegeMap");
private static final org.apache.thrift.protocol.TField PRIVILEGE_MAP_FIELD_DESC = new org.apache.thrift.protocol.TField("privilegeMap", org.apache.thrift.protocol.TType.MAP, (short)1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new TSentryPrivilegeMapStandardSchemeFactory());
schemes.put(TupleScheme.class, new TSentryPrivilegeMapTupleSchemeFactory());
}
private Map<String,Set<TSentryPrivilege>> privilegeMap; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
PRIVILEGE_MAP((short)1, "privilegeMap");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // PRIVILEGE_MAP
return PRIVILEGE_MAP;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.PRIVILEGE_MAP, new org.apache.thrift.meta_data.FieldMetaData("privilegeMap", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.MapMetaData(org.apache.thrift.protocol.TType.MAP,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING),
new org.apache.thrift.meta_data.SetMetaData(org.apache.thrift.protocol.TType.SET,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TSentryPrivilege.class)))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TSentryPrivilegeMap.class, metaDataMap);
}
public TSentryPrivilegeMap() {
}
public TSentryPrivilegeMap(
Map<String,Set<TSentryPrivilege>> privilegeMap)
{
this();
this.privilegeMap = privilegeMap;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public TSentryPrivilegeMap(TSentryPrivilegeMap other) {
if (other.isSetPrivilegeMap()) {
Map<String,Set<TSentryPrivilege>> __this__privilegeMap = new HashMap<String,Set<TSentryPrivilege>>();
for (Map.Entry<String, Set<TSentryPrivilege>> other_element : other.privilegeMap.entrySet()) {
String other_element_key = other_element.getKey();
Set<TSentryPrivilege> other_element_value = other_element.getValue();
String __this__privilegeMap_copy_key = other_element_key;
Set<TSentryPrivilege> __this__privilegeMap_copy_value = new HashSet<TSentryPrivilege>();
for (TSentryPrivilege other_element_value_element : other_element_value) {
__this__privilegeMap_copy_value.add(new TSentryPrivilege(other_element_value_element));
}
__this__privilegeMap.put(__this__privilegeMap_copy_key, __this__privilegeMap_copy_value);
}
this.privilegeMap = __this__privilegeMap;
}
}
public TSentryPrivilegeMap deepCopy() {
return new TSentryPrivilegeMap(this);
}
@Override
public void clear() {
this.privilegeMap = null;
}
public int getPrivilegeMapSize() {
return (this.privilegeMap == null) ? 0 : this.privilegeMap.size();
}
public void putToPrivilegeMap(String key, Set<TSentryPrivilege> val) {
if (this.privilegeMap == null) {
this.privilegeMap = new HashMap<String,Set<TSentryPrivilege>>();
}
this.privilegeMap.put(key, val);
}
public Map<String,Set<TSentryPrivilege>> getPrivilegeMap() {
return this.privilegeMap;
}
public void setPrivilegeMap(Map<String,Set<TSentryPrivilege>> privilegeMap) {
this.privilegeMap = privilegeMap;
}
public void unsetPrivilegeMap() {
this.privilegeMap = null;
}
/** Returns true if field privilegeMap is set (has been assigned a value) and false otherwise */
public boolean isSetPrivilegeMap() {
return this.privilegeMap != null;
}
public void setPrivilegeMapIsSet(boolean value) {
if (!value) {
this.privilegeMap = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case PRIVILEGE_MAP:
if (value == null) {
unsetPrivilegeMap();
} else {
setPrivilegeMap((Map<String,Set<TSentryPrivilege>>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case PRIVILEGE_MAP:
return getPrivilegeMap();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case PRIVILEGE_MAP:
return isSetPrivilegeMap();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof TSentryPrivilegeMap)
return this.equals((TSentryPrivilegeMap)that);
return false;
}
public boolean equals(TSentryPrivilegeMap that) {
if (that == null)
return false;
boolean this_present_privilegeMap = true && this.isSetPrivilegeMap();
boolean that_present_privilegeMap = true && that.isSetPrivilegeMap();
if (this_present_privilegeMap || that_present_privilegeMap) {
if (!(this_present_privilegeMap && that_present_privilegeMap))
return false;
if (!this.privilegeMap.equals(that.privilegeMap))
return false;
}
return true;
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
boolean present_privilegeMap = true && (isSetPrivilegeMap());
builder.append(present_privilegeMap);
if (present_privilegeMap)
builder.append(privilegeMap);
return builder.toHashCode();
}
public int compareTo(TSentryPrivilegeMap other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
TSentryPrivilegeMap typedOther = (TSentryPrivilegeMap)other;
lastComparison = Boolean.valueOf(isSetPrivilegeMap()).compareTo(typedOther.isSetPrivilegeMap());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetPrivilegeMap()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.privilegeMap, typedOther.privilegeMap);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TSentryPrivilegeMap(");
boolean first = true;
sb.append("privilegeMap:");
if (this.privilegeMap == null) {
sb.append("null");
} else {
sb.append(this.privilegeMap);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (!isSetPrivilegeMap()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'privilegeMap' is unset! Struct:" + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class TSentryPrivilegeMapStandardSchemeFactory implements SchemeFactory {
public TSentryPrivilegeMapStandardScheme getScheme() {
return new TSentryPrivilegeMapStandardScheme();
}
}
private static class TSentryPrivilegeMapStandardScheme extends StandardScheme<TSentryPrivilegeMap> {
public void read(org.apache.thrift.protocol.TProtocol iprot, TSentryPrivilegeMap struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // PRIVILEGE_MAP
if (schemeField.type == org.apache.thrift.protocol.TType.MAP) {
{
org.apache.thrift.protocol.TMap _map88 = iprot.readMapBegin();
struct.privilegeMap = new HashMap<String,Set<TSentryPrivilege>>(2*_map88.size);
for (int _i89 = 0; _i89 < _map88.size; ++_i89)
{
String _key90; // required
Set<TSentryPrivilege> _val91; // required
_key90 = iprot.readString();
{
org.apache.thrift.protocol.TSet _set92 = iprot.readSetBegin();
_val91 = new HashSet<TSentryPrivilege>(2*_set92.size);
for (int _i93 = 0; _i93 < _set92.size; ++_i93)
{
TSentryPrivilege _elem94; // required
_elem94 = new TSentryPrivilege();
_elem94.read(iprot);
_val91.add(_elem94);
}
iprot.readSetEnd();
}
struct.privilegeMap.put(_key90, _val91);
}
iprot.readMapEnd();
}
struct.setPrivilegeMapIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, TSentryPrivilegeMap struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.privilegeMap != null) {
oprot.writeFieldBegin(PRIVILEGE_MAP_FIELD_DESC);
{
oprot.writeMapBegin(new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.SET, struct.privilegeMap.size()));
for (Map.Entry<String, Set<TSentryPrivilege>> _iter95 : struct.privilegeMap.entrySet())
{
oprot.writeString(_iter95.getKey());
{
oprot.writeSetBegin(new org.apache.thrift.protocol.TSet(org.apache.thrift.protocol.TType.STRUCT, _iter95.getValue().size()));
for (TSentryPrivilege _iter96 : _iter95.getValue())
{
_iter96.write(oprot);
}
oprot.writeSetEnd();
}
}
oprot.writeMapEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class TSentryPrivilegeMapTupleSchemeFactory implements SchemeFactory {
public TSentryPrivilegeMapTupleScheme getScheme() {
return new TSentryPrivilegeMapTupleScheme();
}
}
private static class TSentryPrivilegeMapTupleScheme extends TupleScheme<TSentryPrivilegeMap> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, TSentryPrivilegeMap struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
{
oprot.writeI32(struct.privilegeMap.size());
for (Map.Entry<String, Set<TSentryPrivilege>> _iter97 : struct.privilegeMap.entrySet())
{
oprot.writeString(_iter97.getKey());
{
oprot.writeI32(_iter97.getValue().size());
for (TSentryPrivilege _iter98 : _iter97.getValue())
{
_iter98.write(oprot);
}
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, TSentryPrivilegeMap struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
{
org.apache.thrift.protocol.TMap _map99 = new org.apache.thrift.protocol.TMap(org.apache.thrift.protocol.TType.STRING, org.apache.thrift.protocol.TType.SET, iprot.readI32());
struct.privilegeMap = new HashMap<String,Set<TSentryPrivilege>>(2*_map99.size);
for (int _i100 = 0; _i100 < _map99.size; ++_i100)
{
String _key101; // required
Set<TSentryPrivilege> _val102; // required
_key101 = iprot.readString();
{
org.apache.thrift.protocol.TSet _set103 = new org.apache.thrift.protocol.TSet(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
_val102 = new HashSet<TSentryPrivilege>(2*_set103.size);
for (int _i104 = 0; _i104 < _set103.size; ++_i104)
{
TSentryPrivilege _elem105; // required
_elem105 = new TSentryPrivilege();
_elem105.read(iprot);
_val102.add(_elem105);
}
}
struct.privilegeMap.put(_key101, _val102);
}
}
struct.setPrivilegeMapIsSet(true);
}
}
}
| apache-2.0 |
howepeng/isis | core/runtime/src/test/java/org/apache/isis/core/runtime/system/JavaObjectMarkedAsTransient.java | 999 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.core.runtime.system;
import org.apache.isis.applib.marker.NonPersistable;
public class JavaObjectMarkedAsTransient implements NonPersistable {
}
| apache-2.0 |
alexzaitzev/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCacheGetOrCreateWithNameRequest.java | 1887 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.platform.client.cache;
import org.apache.ignite.binary.BinaryRawReader;
import org.apache.ignite.internal.processors.platform.client.ClientConnectionContext;
import org.apache.ignite.internal.processors.platform.client.ClientRequest;
import org.apache.ignite.internal.processors.platform.client.ClientResponse;
import org.apache.ignite.plugin.security.SecurityPermission;
/**
* Cache create with name request.
*/
public class ClientCacheGetOrCreateWithNameRequest extends ClientRequest {
/** Cache name. */
private final String cacheName;
/**
* Constructor.
*
* @param reader Reader.
*/
public ClientCacheGetOrCreateWithNameRequest(BinaryRawReader reader) {
super(reader);
cacheName = reader.readString();
}
/** {@inheritDoc} */
@Override public ClientResponse process(ClientConnectionContext ctx) {
authorize(ctx, SecurityPermission.CACHE_CREATE);
ctx.kernalContext().grid().getOrCreateCache(cacheName);
return super.process(ctx);
}
}
| apache-2.0 |
laki88/carbon-governance | components/governance/org.wso2.carbon.governance.comparator/src/main/java/org/wso2/carbon/governance/comparator/wsdl/WSDLBindingsComparator.java | 6390 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.governance.comparator.wsdl;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.governance.comparator.Comparison;
import org.wso2.carbon.governance.comparator.ComparisonException;
import org.wso2.carbon.governance.comparator.common.DefaultComparison;
import org.wso2.carbon.governance.comparator.utils.ComparatorConstants;
import org.wso2.carbon.governance.comparator.utils.WSDLComparisonUtils;
import javax.wsdl.Binding;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class WSDLBindingsComparator extends AbstractWSDLComparator {
private Log log = LogFactory.getLog(WSDLBindingsComparator.class);
@Override
public void compareInternal(Definition base, Definition changed, DefaultComparison comparison)
throws ComparisonException {
compareBindings(base, changed, comparison);
}
protected void compareBindings(Definition base, Definition changed,
DefaultComparison comparison) {
Map<QName, Binding> baseBinding = base.getAllBindings();
Map<QName, Binding> changedBinding = changed.getAllBindings();
DefaultComparison.DefaultSection section = null;
MapDifference<QName, Binding> mapDiff = Maps.difference(baseBinding, changedBinding);
//If both side imports are equal, return
if (mapDiff.areEqual()) {
return;
}
Map<QName, Binding> additions = mapDiff.entriesOnlyOnRight();
if (section == null && additions.size() > 0) {
section = comparison.newSection();
}
processAdditions(section, additions, changed);
Map<QName, Binding> removals = mapDiff.entriesOnlyOnLeft();
if (section == null && removals.size() > 0) {
section = comparison.newSection();
}
processRemovals(section, removals, base);
Map<QName, MapDifference.ValueDifference<Binding>> changes = mapDiff.entriesDiffering();
section = processChanges(section, comparison, changes, base, changed);
if (section != null) {
comparison.addSection(ComparatorConstants.WSDL_BINDINGS, section);
}
}
private void processAdditions(DefaultComparison.DefaultSection section, Map<QName, Binding> additions,
Definition definition) {
if (additions.size() > 0) {
section.addSectionSummary(Comparison.SectionType.CONTENT_ADDITION, ComparatorConstants.NEW_BINDING);
DefaultComparison.DefaultSection.DefaultTextContent content = section.newTextContent();
content.setContent(getBindingsOnly(additions.values(), definition));
section.addContent(Comparison.SectionType.CONTENT_ADDITION, content);
}
}
private void processRemovals(DefaultComparison.DefaultSection section, Map<QName, Binding> removals,
Definition definition) {
if (removals.size() > 0) {
section.addSectionSummary(Comparison.SectionType.CONTENT_REMOVAL, ComparatorConstants.REMOVE_BINDING);
DefaultComparison.DefaultSection.DefaultTextContent content = section.newTextContent();
content.setContent(getBindingsOnly(removals.values(), definition));
section.addContent(Comparison.SectionType.CONTENT_REMOVAL, content);
}
}
private DefaultComparison.DefaultSection processChanges(DefaultComparison.DefaultSection section,
DefaultComparison comparison, Map<QName, MapDifference.ValueDifference<Binding>> changes, Definition base,
Definition changed) {
if (changes.size() > 0) {
List<Binding> left = new ArrayList<>();
List<Binding> right = new ArrayList<>();
for (MapDifference.ValueDifference<Binding> diff : changes.values()) {
if (!diff.leftValue().toString().equals(diff.rightValue().toString())) {
left.add(diff.leftValue());
right.add(diff.rightValue());
}
}
if (left.size() > 0) {
if (section == null) {
section = comparison.newSection();
}
section.addSectionSummary(Comparison.SectionType.CONTENT_CHANGE, ComparatorConstants.CHANGED_BINDING);
DefaultComparison.DefaultSection.DefaultTextChangeContent content = section.newTextChangeContent();
DefaultComparison.DefaultSection.DefaultTextChange change = section.newTextChange();
change.setOriginal(getBindingsOnly(left, base));
change.setChanged(getBindingsOnly(right, changed));
content.setContent(change);
section.addContent(Comparison.SectionType.CONTENT_CHANGE, content);
}
}
return section;
}
private String getBindingsOnly(Collection<Binding> bindings, Definition definition) {
try {
Definition tempDefinition = WSDLComparisonUtils.getWSDLDefinition();
for (Binding binding : bindings) {
tempDefinition.addBinding(binding);
}
WSDLComparisonUtils.copyNamespaces(definition, tempDefinition);
return WSDLComparisonUtils.getWSDLWithoutDeclaration(tempDefinition);
} catch (WSDLException e) {
log.error(e);
}
return null;
}
}
| apache-2.0 |
howepeng/isis | core/applib/src/main/java/org/apache/isis/applib/FatalException.java | 1742 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.applib;
/**
* Indicates that an unexpected, non-recoverable (fatal) exception has occurred within
* the application logic.
*
* <p>
* Throwing this exception will (dependent on the viewer) result in some sort of an error page being displayed to the user.
*
* <p>
* Note that this exception has identical semantics to {@link NonRecoverableException}, and can be considered a
* synonym.
*
* @see RecoverableException
* @see ApplicationException
* @see NonRecoverableException
*/
public class FatalException extends NonRecoverableException {
private static final long serialVersionUID = 1L;
public FatalException(final String msg) {
super(msg);
}
public FatalException(final Throwable cause) {
this(cause.getMessage(), cause);
}
public FatalException(final String msg, final Throwable cause) {
super(msg, cause);
}
}
| apache-2.0 |
jk1/intellij-community | plugins/InspectionGadgets/testsrc/com/siyeh/ig/serialization/NonSerializableWithSerialVersionUIDFieldInspectionTest.java | 372 | package com.siyeh.ig.serialization;
import com.siyeh.ig.IGInspectionTestCase;
public class NonSerializableWithSerialVersionUIDFieldInspectionTest
extends IGInspectionTestCase {
public void test() {
doTest("com/siyeh/igtest/serialization/non_serializable_with_serial_version_uid_field",
new NonSerializableWithSerialVersionUIDFieldInspection());
}
} | apache-2.0 |
rlovtangen/groovy-core | subprojects/groovy-swing/src/main/java/groovy/model/NestedValueModel.java | 1104 | /**
* 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 groovy.model;
/**
* Represents a nested value model such as a PropertyModel
* or a ClosureModel
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @version $Revision$
*/
public interface NestedValueModel {
ValueModel getSourceModel();
}
| apache-2.0 |
mbiarnes/drools-wb | drools-wb-screens/drools-wb-guided-dtable-editor/drools-wb-guided-dtable-editor-client/src/main/java/org/drools/workbench/screens/guided/dtable/client/wizard/table/pages/SummaryPage.java | 3121 | /*
* 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.drools.workbench.screens.guided.dtable.client.wizard.table.pages;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.drools.workbench.screens.guided.dtable.client.resources.i18n.GuidedDecisionTableConstants;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.kie.workbench.common.services.shared.validation.ValidationService;
import org.uberfire.client.callbacks.Callback;
import org.uberfire.ext.widgets.core.client.wizards.WizardPageStatusChangeEvent;
/**
* A summary page for the guided Decision Table Wizard
*/
@Dependent
public class SummaryPage extends AbstractGuidedDecisionTableWizardPage
implements
SummaryPageView.Presenter {
@Inject
private SummaryPageView view;
@Inject
private Event<WizardPageStatusChangeEvent> wizardPageStatusChangeEvent;
@Inject
private Caller<ValidationService> fileNameValidationService;
private boolean isBaseFileNameValid = false;
@Override
public String getTitle() {
return GuidedDecisionTableConstants.INSTANCE.DecisionTableWizardSummary();
}
@Override
public void isComplete( final Callback<Boolean> callback ) {
callback.callback( isBaseFileNameValid );
}
@Override
public void initialise() {
view.init( this );
view.setBaseFileName( baseFileName );
view.setContextPath( contextPath );
view.setTableFormat( tableFormat );
view.setHitPolicy( hitPolicy );
content.setWidget( view );
stateChanged();
}
@Override
public void prepareView() {
//Nothing required
}
@Override
public void stateChanged() {
fileNameValidationService.call( new RemoteCallback<Boolean>() {
@Override
public void callback( final Boolean response ) {
isBaseFileNameValid = Boolean.TRUE.equals( response );
view.setValidBaseFileName( isBaseFileNameValid );
fireEvent();
}
} ).isFileNameValid( view.getBaseFileName() );
}
// package protected to allow overriding in tests
void fireEvent() {
final WizardPageStatusChangeEvent event = new WizardPageStatusChangeEvent( this );
wizardPageStatusChangeEvent.fire( event );
}
@Override
public String getBaseFileName() {
return view.getBaseFileName();
}
}
| apache-2.0 |
HonzaKral/elasticsearch | server/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java | 18473 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.admin.indices.create;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.UnavailableShardsException;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_WAIT_FOR_ACTIVE_SHARDS;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.core.IsNull.notNullValue;
@ClusterScope(scope = Scope.TEST)
public class CreateIndexIT extends ESIntegTestCase {
public void testCreationDateGivenFails() {
try {
prepareCreate("test").setSettings(Settings.builder().put(IndexMetadata.SETTING_CREATION_DATE, 4L)).get();
fail();
} catch (IllegalArgumentException ex) {
assertEquals("unknown setting [index.creation_date] please check that any required plugins are installed, or check the " +
"breaking changes documentation for removed settings", ex.getMessage());
}
}
public void testCreationDateGenerated() {
long timeBeforeRequest = System.currentTimeMillis();
prepareCreate("test").get();
long timeAfterRequest = System.currentTimeMillis();
ClusterStateResponse response = client().admin().cluster().prepareState().get();
ClusterState state = response.getState();
assertThat(state, notNullValue());
Metadata metadata = state.getMetadata();
assertThat(metadata, notNullValue());
ImmutableOpenMap<String, IndexMetadata> indices = metadata.getIndices();
assertThat(indices, notNullValue());
assertThat(indices.size(), equalTo(1));
IndexMetadata index = indices.get("test");
assertThat(index, notNullValue());
assertThat(index.getCreationDate(), allOf(lessThanOrEqualTo(timeAfterRequest), greaterThanOrEqualTo(timeBeforeRequest)));
}
public void testNonNestedMappings() throws Exception {
assertAcked(prepareCreate("test")
.setMapping(XContentFactory.jsonBuilder().startObject()
.startObject("properties")
.startObject("date")
.field("type", "date")
.endObject()
.endObject()
.endObject()));
GetMappingsResponse response = client().admin().indices().prepareGetMappings("test").get();
MappingMetadata mappings = response.mappings().get("test");
assertNotNull(mappings);
assertFalse(mappings.sourceAsMap().isEmpty());
}
public void testEmptyNestedMappings() throws Exception {
assertAcked(prepareCreate("test")
.setMapping(XContentFactory.jsonBuilder().startObject().endObject()));
GetMappingsResponse response = client().admin().indices().prepareGetMappings("test").get();
MappingMetadata mappings = response.mappings().get("test");
assertNotNull(mappings);
assertTrue(mappings.sourceAsMap().isEmpty());
}
public void testMappingParamAndNestedMismatch() throws Exception {
MapperParsingException e = expectThrows(MapperParsingException.class, () -> prepareCreate("test")
.setMapping(XContentFactory.jsonBuilder().startObject()
.startObject("type2").endObject()
.endObject()).get());
assertThat(e.getMessage(), startsWith("Failed to parse mapping: Root mapping definition has unsupported parameters"));
}
public void testEmptyMappings() throws Exception {
assertAcked(prepareCreate("test")
.setMapping(XContentFactory.jsonBuilder().startObject()
.startObject("_doc").endObject()
.endObject()));
GetMappingsResponse response = client().admin().indices().prepareGetMappings("test").get();
MappingMetadata mappings = response.mappings().get("test");
assertNotNull(mappings);
assertTrue(mappings.sourceAsMap().isEmpty());
}
public void testInvalidShardCountSettings() throws Exception {
int value = randomIntBetween(-10, 0);
try {
prepareCreate("test").setSettings(Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, value)
.build())
.get();
fail("should have thrown an exception about the primary shard count");
} catch (IllegalArgumentException e) {
assertEquals("Failed to parse value [" + value + "] for setting [index.number_of_shards] must be >= 1", e.getMessage());
}
value = randomIntBetween(-10, -1);
try {
prepareCreate("test").setSettings(Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, value)
.build())
.get();
fail("should have thrown an exception about the replica shard count");
} catch (IllegalArgumentException e) {
assertEquals("Failed to parse value [" + value + "] for setting [index.number_of_replicas] must be >= 0", e.getMessage());
}
}
public void testCreateIndexWithBlocks() {
try {
setClusterReadOnly(true);
assertBlocked(prepareCreate("test"));
} finally {
setClusterReadOnly(false);
}
}
public void testCreateIndexWithMetadataBlocks() {
assertAcked(prepareCreate("test").setSettings(Settings.builder().put(IndexMetadata.SETTING_BLOCKS_METADATA, true)));
assertBlocked(client().admin().indices().prepareGetSettings("test"), IndexMetadata.INDEX_METADATA_BLOCK);
disableIndexBlock("test", IndexMetadata.SETTING_BLOCKS_METADATA);
}
public void testUnknownSettingFails() {
try {
prepareCreate("test").setSettings(Settings.builder()
.put("index.unknown.value", "this must fail")
.build())
.get();
fail("should have thrown an exception about the shard count");
} catch (IllegalArgumentException e) {
assertEquals("unknown setting [index.unknown.value] please check that any required plugins are installed, or check the" +
" breaking changes documentation for removed settings", e.getMessage());
}
}
public void testInvalidShardCountSettingsWithoutPrefix() throws Exception {
int value = randomIntBetween(-10, 0);
try {
prepareCreate("test").setSettings(Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS.substring(IndexMetadata.INDEX_SETTING_PREFIX.length()), value)
.build())
.get();
fail("should have thrown an exception about the shard count");
} catch (IllegalArgumentException e) {
assertEquals("Failed to parse value [" + value + "] for setting [index.number_of_shards] must be >= 1", e.getMessage());
}
value = randomIntBetween(-10, -1);
try {
prepareCreate("test").setSettings(Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS.substring(IndexMetadata.INDEX_SETTING_PREFIX.length()), value)
.build())
.get();
fail("should have thrown an exception about the shard count");
} catch (IllegalArgumentException e) {
assertEquals("Failed to parse value [" + value + "] for setting [index.number_of_replicas] must be >= 0", e.getMessage());
}
}
public void testCreateAndDeleteIndexConcurrently() throws InterruptedException {
createIndex("test");
final AtomicInteger indexVersion = new AtomicInteger(0);
final Object indexVersionLock = new Object();
final CountDownLatch latch = new CountDownLatch(1);
int numDocs = randomIntBetween(1, 10);
for (int i = 0; i < numDocs; i++) {
client().prepareIndex("test").setSource("index_version", indexVersion.get()).get();
}
synchronized (indexVersionLock) { // not necessarily needed here but for completeness we lock here too
indexVersion.incrementAndGet();
}
client().admin().indices().prepareDelete("test").execute(new ActionListener<AcknowledgedResponse>() { // this happens async!!!
@Override
public void onResponse(AcknowledgedResponse deleteIndexResponse) {
Thread thread = new Thread() {
@Override
public void run() {
try {
// recreate that index
client().prepareIndex("test").setSource("index_version", indexVersion.get()).get();
synchronized (indexVersionLock) {
// we sync here since we have to ensure that all indexing operations below for a given ID are done before
// we increment the index version otherwise a doc that is in-flight could make it into an index that it
// was supposed to be deleted for and our assertion fail...
indexVersion.incrementAndGet();
}
// from here on all docs with index_version == 0|1 must be gone!!!! only 2 are ok;
assertAcked(client().admin().indices().prepareDelete("test").get());
} finally {
latch.countDown();
}
}
};
thread.start();
}
@Override
public void onFailure(Exception e) {
throw new RuntimeException(e);
}
}
);
numDocs = randomIntBetween(100, 200);
for (int i = 0; i < numDocs; i++) {
try {
synchronized (indexVersionLock) {
client().prepareIndex("test").setSource("index_version", indexVersion.get())
.setTimeout(TimeValue.timeValueSeconds(10)).get();
}
} catch (IndexNotFoundException inf) {
// fine
} catch (UnavailableShardsException ex) {
assertEquals(ex.getCause().getClass(), IndexNotFoundException.class);
// fine we run into a delete index while retrying
}
}
latch.await();
refresh();
// we only really assert that we never reuse segments of old indices or anything like this here and that nothing fails with
// crazy exceptions
SearchResponse expected = client().prepareSearch("test").setIndicesOptions(IndicesOptions.lenientExpandOpen())
.setQuery(new RangeQueryBuilder("index_version").from(indexVersion.get(), true)).get();
SearchResponse all = client().prepareSearch("test").setIndicesOptions(IndicesOptions.lenientExpandOpen()).get();
assertEquals(expected + " vs. " + all, expected.getHits().getTotalHits().value, all.getHits().getTotalHits().value);
logger.info("total: {}", expected.getHits().getTotalHits().value);
}
public void testRestartIndexCreationAfterFullClusterRestart() throws Exception {
client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put("cluster.routing.allocation.enable",
"none")).get();
client().admin().indices().prepareCreate("test").setWaitForActiveShards(ActiveShardCount.NONE).setSettings(indexSettings()).get();
internalCluster().fullRestart();
ensureGreen("test");
}
public void testFailureToCreateIndexCleansUpIndicesService() {
final int numReplicas = internalCluster().numDataNodes();
Settings settings = Settings.builder()
.put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1)
.put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), numReplicas)
.build();
assertAcked(client().admin().indices().prepareCreate("test-idx-1")
.setSettings(settings)
.addAlias(new Alias("alias1").writeIndex(true))
.get());
assertRequestBuilderThrows(client().admin().indices().prepareCreate("test-idx-2")
.setSettings(settings)
.addAlias(new Alias("alias1").writeIndex(true)),
IllegalStateException.class);
IndicesService indicesService = internalCluster().getInstance(IndicesService.class, internalCluster().getMasterName());
for (IndexService indexService : indicesService) {
assertThat(indexService.index().getName(), not("test-idx-2"));
}
}
/**
* This test ensures that index creation adheres to the {@link IndexMetadata#SETTING_WAIT_FOR_ACTIVE_SHARDS}.
*/
public void testDefaultWaitForActiveShardsUsesIndexSetting() throws Exception {
final int numReplicas = internalCluster().numDataNodes();
Settings settings = Settings.builder()
.put(SETTING_WAIT_FOR_ACTIVE_SHARDS.getKey(), Integer.toString(numReplicas))
.put(IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1)
.put(IndexMetadata.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), numReplicas)
.build();
assertAcked(client().admin().indices().prepareCreate("test-idx-1").setSettings(settings).get());
// all should fail
settings = Settings.builder()
.put(settings)
.put(SETTING_WAIT_FOR_ACTIVE_SHARDS.getKey(), "all")
.build();
assertFalse(client().admin().indices().prepareCreate("test-idx-2").setSettings(settings).setTimeout("100ms").get()
.isShardsAcknowledged());
// the numeric equivalent of all should also fail
settings = Settings.builder()
.put(settings)
.put(SETTING_WAIT_FOR_ACTIVE_SHARDS.getKey(), Integer.toString(numReplicas + 1))
.build();
assertFalse(client().admin().indices().prepareCreate("test-idx-3").setSettings(settings).setTimeout("100ms").get()
.isShardsAcknowledged());
}
public void testInvalidPartitionSize() {
BiFunction<Integer, Integer, Boolean> createPartitionedIndex = (shards, partitionSize) -> {
CreateIndexResponse response;
try {
response = prepareCreate("test_" + shards + "_" + partitionSize)
.setSettings(Settings.builder()
.put("index.number_of_shards", shards)
.put("index.number_of_routing_shards", shards)
.put("index.routing_partition_size", partitionSize))
.execute().actionGet();
} catch (IllegalStateException | IllegalArgumentException e) {
return false;
}
return response.isAcknowledged();
};
assertFalse(createPartitionedIndex.apply(3, 6));
assertFalse(createPartitionedIndex.apply(3, 0));
assertFalse(createPartitionedIndex.apply(3, 3));
assertTrue(createPartitionedIndex.apply(3, 1));
assertTrue(createPartitionedIndex.apply(3, 2));
assertTrue(createPartitionedIndex.apply(1, 1));
}
public void testIndexNameInResponse() {
CreateIndexResponse response = prepareCreate("foo")
.setSettings(Settings.builder().build())
.get();
assertEquals("Should have index name in response", "foo", response.index());
}
}
| apache-2.0 |
mbiarnes/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-api/src/main/java/org/kie/workbench/common/stunner/bpmn/documentation/model/BPMNDocumentation.java | 2305 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.bpmn.documentation.model;
import com.google.gwt.core.client.GWT;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import org.kie.workbench.common.stunner.bpmn.documentation.model.element.ElementDetails;
import org.kie.workbench.common.stunner.bpmn.documentation.model.general.ProcessOverview;
import org.kie.workbench.common.stunner.core.documentation.model.DiagramDocumentation;
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
public class BPMNDocumentation implements DiagramDocumentation {
private ProcessOverview process;
private ElementDetails elementsDetails;
private String diagramImage;
private String moduleName;
private BPMNDocumentation() {
}
@JsOverlay
public static final BPMNDocumentation create(ProcessOverview process, ElementDetails elementsDetails,
String diagramImage) {
final BPMNDocumentation instance = new BPMNDocumentation();
instance.process = process;
instance.elementsDetails = elementsDetails;
instance.diagramImage = diagramImage;
instance.moduleName = GWT.getModuleName();
return instance;
}
@JsOverlay
public final ProcessOverview getProcess() {
return process;
}
@JsOverlay
public final ElementDetails getElementsDetails() {
return elementsDetails;
}
@JsOverlay
public final String getDiagramImage() {
return diagramImage;
}
@JsOverlay
public final String getModuleName() {
return moduleName;
}
}
| apache-2.0 |
xs2maverick/javacc-svn | src/main/java/jjdoc.java | 1934 | /* Copyright (c) 2006, Sun Microsystems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Sun Microsystems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Intermediary between OS script and main program of application.
* Having this intermediary allows the OS scripts to be package name
* independent.
*/
public final class jjdoc {
private jjdoc() {}
public static void main(String[] args) throws Exception {
org.javacc.jjdoc.JJDocMain.main(args);
}
}
| bsd-3-clause |
scheib/chromium | components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/ClearWebsiteStorageDialog.java | 2346 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.browser_ui.site_settings;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.preference.Preference;
import androidx.preference.PreferenceDialogFragmentCompat;
import org.chromium.base.Callback;
/**
* The fragment used to display the clear website storage confirmation dialog.
*/
public class ClearWebsiteStorageDialog extends PreferenceDialogFragmentCompat {
public static final String TAG = "ClearWebsiteStorageDialog";
private static Callback<Boolean> sCallback;
// The view containing the dialog ui elements.
private View mDialogView;
public static ClearWebsiteStorageDialog newInstance(
Preference preference, Callback<Boolean> callback) {
ClearWebsiteStorageDialog fragment = new ClearWebsiteStorageDialog();
sCallback = callback;
Bundle bundle = new Bundle(1);
bundle.putString(PreferenceDialogFragmentCompat.ARG_KEY, preference.getKey());
fragment.setArguments(bundle);
return fragment;
}
@Override
protected void onBindDialogView(View view) {
mDialogView = view;
TextView signedOutView = view.findViewById(R.id.signed_out_text);
TextView offlineTextView = view.findViewById(R.id.offline_text);
signedOutView.setText(ClearWebsiteStorage.getSignedOutText());
offlineTextView.setText(ClearWebsiteStorage.getOfflineText());
super.onBindDialogView(view);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mDialogView != null) {
// When the device switches to multi-window in landscape mode, the height of the
// offlineTextView is not calculated correctly (its height gets truncated) and a layout
// pass is needed to fix it. See https://crbug.com/1072922.
mDialogView.getHandler().post(mDialogView::requestLayout);
}
}
@Override
public void onDialogClosed(boolean positiveResult) {
sCallback.onResult(positiveResult);
}
}
| bsd-3-clause |
strahanjen/strahanjen.github.io | elasticsearch-master/core/src/main/java/org/elasticsearch/search/aggregations/metrics/percentiles/PercentilesAggregationBuilder.java | 9253 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.metrics.percentiles;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.InternalAggregation.Type;
import org.elasticsearch.search.aggregations.metrics.percentiles.hdr.HDRPercentilesAggregatorFactory;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.TDigestPercentilesAggregatorFactory;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSource.Numeric;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder.LeafOnly;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
public class PercentilesAggregationBuilder extends LeafOnly<ValuesSource.Numeric, PercentilesAggregationBuilder> {
public static final String NAME = Percentiles.TYPE_NAME;
public static final Type TYPE = new Type(NAME);
private double[] percents = PercentilesParser.DEFAULT_PERCENTS;
private PercentilesMethod method = PercentilesMethod.TDIGEST;
private int numberOfSignificantValueDigits = 3;
private double compression = 100.0;
private boolean keyed = true;
public PercentilesAggregationBuilder(String name) {
super(name, TYPE, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
}
/**
* Read from a stream.
*/
public PercentilesAggregationBuilder(StreamInput in) throws IOException {
super(in, TYPE, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
percents = in.readDoubleArray();
keyed = in.readBoolean();
numberOfSignificantValueDigits = in.readVInt();
compression = in.readDouble();
method = PercentilesMethod.readFromStream(in);
}
@Override
protected void innerWriteTo(StreamOutput out) throws IOException {
out.writeDoubleArray(percents);
out.writeBoolean(keyed);
out.writeVInt(numberOfSignificantValueDigits);
out.writeDouble(compression);
method.writeTo(out);
}
/**
* Set the values to compute percentiles from.
*/
public PercentilesAggregationBuilder percentiles(double... percents) {
if (percents == null) {
throw new IllegalArgumentException("[percents] must not be null: [" + name + "]");
}
double[] sortedPercents = Arrays.copyOf(percents, percents.length);
Arrays.sort(sortedPercents);
this.percents = sortedPercents;
return this;
}
/**
* Get the values to compute percentiles from.
*/
public double[] percentiles() {
return percents;
}
/**
* Set whether the XContent response should be keyed
*/
public PercentilesAggregationBuilder keyed(boolean keyed) {
this.keyed = keyed;
return this;
}
/**
* Get whether the XContent response should be keyed
*/
public boolean keyed() {
return keyed;
}
/**
* Expert: set the number of significant digits in the values. Only relevant
* when using {@link PercentilesMethod#HDR}.
*/
public PercentilesAggregationBuilder numberOfSignificantValueDigits(int numberOfSignificantValueDigits) {
if (numberOfSignificantValueDigits < 0 || numberOfSignificantValueDigits > 5) {
throw new IllegalArgumentException("[numberOfSignificantValueDigits] must be between 0 and 5: [" + name + "]");
}
this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
return this;
}
/**
* Expert: get the number of significant digits in the values. Only relevant
* when using {@link PercentilesMethod#HDR}.
*/
public int numberOfSignificantValueDigits() {
return numberOfSignificantValueDigits;
}
/**
* Expert: set the compression. Higher values improve accuracy but also
* memory usage. Only relevant when using {@link PercentilesMethod#TDIGEST}.
*/
public PercentilesAggregationBuilder compression(double compression) {
if (compression < 0.0) {
throw new IllegalArgumentException(
"[compression] must be greater than or equal to 0. Found [" + compression + "] in [" + name + "]");
}
this.compression = compression;
return this;
}
/**
* Expert: get the compression. Higher values improve accuracy but also
* memory usage. Only relevant when using {@link PercentilesMethod#TDIGEST}.
*/
public double compression() {
return compression;
}
public PercentilesAggregationBuilder method(PercentilesMethod method) {
if (method == null) {
throw new IllegalArgumentException("[method] must not be null: [" + name + "]");
}
this.method = method;
return this;
}
public PercentilesMethod method() {
return method;
}
@Override
protected ValuesSourceAggregatorFactory<Numeric, ?> innerBuild(AggregationContext context, ValuesSourceConfig<Numeric> config,
AggregatorFactory<?> parent, Builder subFactoriesBuilder) throws IOException {
switch (method) {
case TDIGEST:
return new TDigestPercentilesAggregatorFactory(name, type, config, percents, compression, keyed, context, parent,
subFactoriesBuilder, metaData);
case HDR:
return new HDRPercentilesAggregatorFactory(name, type, config, percents, numberOfSignificantValueDigits, keyed, context, parent,
subFactoriesBuilder, metaData);
default:
throw new IllegalStateException("Illegal method [" + method.getName() + "]");
}
}
@Override
protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
builder.array(PercentilesParser.PERCENTS_FIELD.getPreferredName(), percents);
builder.field(AbstractPercentilesParser.KEYED_FIELD.getPreferredName(), keyed);
builder.startObject(method.getName());
if (method == PercentilesMethod.TDIGEST) {
builder.field(AbstractPercentilesParser.COMPRESSION_FIELD.getPreferredName(), compression);
} else {
builder.field(AbstractPercentilesParser.NUMBER_SIGNIFICANT_DIGITS_FIELD.getPreferredName(), numberOfSignificantValueDigits);
}
builder.endObject();
return builder;
}
@Override
protected boolean innerEquals(Object obj) {
PercentilesAggregationBuilder other = (PercentilesAggregationBuilder) obj;
if (!Objects.equals(method, other.method)) {
return false;
}
boolean equalSettings = false;
switch (method) {
case HDR:
equalSettings = Objects.equals(numberOfSignificantValueDigits, other.numberOfSignificantValueDigits);
break;
case TDIGEST:
equalSettings = Objects.equals(compression, other.compression);
break;
default:
throw new IllegalStateException("Illegal method [" + method.getName() + "]");
}
return equalSettings
&& Objects.deepEquals(percents, other.percents)
&& Objects.equals(keyed, other.keyed)
&& Objects.equals(method, other.method);
}
@Override
protected int innerHashCode() {
switch (method) {
case HDR:
return Objects.hash(Arrays.hashCode(percents), keyed, numberOfSignificantValueDigits, method);
case TDIGEST:
return Objects.hash(Arrays.hashCode(percents), keyed, compression, method);
default:
throw new IllegalStateException("Illegal method [" + method.getName() + "]");
}
}
@Override
public String getWriteableName() {
return NAME;
}
}
| bsd-3-clause |
kaituo/sedge | trunk/src/org/apache/pig/tools/pigstats/PigProgressNotificationListener.java | 3479 | /*
* 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.pig.tools.pigstats;
import org.apache.pig.classification.InterfaceAudience;
import org.apache.pig.classification.InterfaceStability;
import org.apache.pig.PigRunner;
/**
* Should be implemented by an object that wants to receive notifications
* from {@link PigRunner}.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public interface PigProgressNotificationListener extends java.util.EventListener {
/**
* Invoked just before launching MR jobs spawned by the script.
* @param scriptId the unique id of the script
* @param numJobsToLaunch the total number of MR jobs spawned by the script
*/
public void launchStartedNotification(String scriptId, int numJobsToLaunch);
/**
* Invoked just before submitting a batch of MR jobs.
* @param scriptId the unique id of the script
* @param numJobsSubmitted the number of MR jobs in the batch
*/
public void jobsSubmittedNotification(String scriptId, int numJobsSubmitted);
/**
* Invoked after a MR job is started.
* @param scriptId the unique id of the script
* @param assignedJobId the MR job id
*/
public void jobStartedNotification(String scriptId, String assignedJobId);
/**
* Invoked just after a MR job is completed successfully.
* @param scriptId the unique id of the script
* @param jobStats the {@link JobStats} object associated with the MR job
*/
public void jobFinishedNotification(String scriptId, JobStats jobStats);
/**
* Invoked when a MR job fails.
* @param scriptId the unique id of the script
* @param jobStats the {@link JobStats} object associated with the MR job
*/
public void jobFailedNotification(String scriptId, JobStats jobStats);
/**
* Invoked just after an output is successfully written.
* @param scriptId the unique id of the script
* @param outputStats the {@link OutputStats} object associated with the output
*/
public void outputCompletedNotification(String scriptId, OutputStats outputStats);
/**
* Invoked to update the execution progress.
* @param scriptId the unique id of the script
* @param progress the percentage of the execution progress
*/
public void progressUpdatedNotification(String scriptId, int progress);
/**
* Invoked just after all MR jobs spawned by the script are completed.
* @param scriptId the unique id of the script
* @param numJobsSucceeded the total number of MR jobs succeeded
*/
public void launchCompletedNotification(String scriptId, int numJobsSucceeded);
}
| mit |
taimur97/tilt-game-android | temple_core/src/main/java/temple/core/ui/form/validation/rules/CountUppercaseValidationRule.java | 1102 | package temple.core.ui.form.validation.rules;
import temple.core.common.interfaces.IHasValue;
import temple.core.ui.form.validation.rules.AbstractValidationRule;
import temple.core.ui.form.validation.rules.IValidationRule;
/**
* Created by erikpoort on 14/08/14.
* MediaMonks
*/
public class CountUppercaseValidationRule extends AbstractValidationRule
implements IValidationRule {
private final int _numberOfUppercases;
public CountUppercaseValidationRule(IHasValue element, int numberOfUppercases) {
super(element);
_numberOfUppercases = numberOfUppercases;
}
private int countUppercases() {
String string = getTarget().getValue().toString();
char[] charArray = string.toCharArray();
int leni = charArray.length;
int count = 0;
for (int i = 0; i < leni; i++) {
if (charArray[i] >= 65 && charArray[i] <= 90) {
count++;
}
}
return count;
}
@Override
public boolean isValid() {
return countUppercases() >= _numberOfUppercases;
}
}
| mit |
plumer/codana | tomcat_files/8.0.22/ReplicatedMapEntry.java | 4001 | /*
* 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.catalina.tribes.tipis;
import java.io.IOException;
import java.io.Serializable;
/**
*
* For smarter replication, an object can implement this interface to replicate diffs<br>
* The replication logic will call the methods in the following order:<br>
* <code>
* 1. if ( entry.isDirty() ) <br>
* try {
* 2. entry.lock();<br>
* 3. byte[] diff = entry.getDiff();<br>
* 4. entry.reset();<br>
* } finally {<br>
* 5. entry.unlock();<br>
* }<br>
* }<br>
* </code>
* <br>
* <br>
* When the data is deserialized the logic is called in the following order<br>
* <code>
* 1. ReplicatedMapEntry entry = (ReplicatedMapEntry)objectIn.readObject();<br>
* 2. if ( isBackup(entry)||isPrimary(entry) ) entry.setOwner(owner); <br>
* </code>
* <br>
*
*
* @version 1.0
*/
public interface ReplicatedMapEntry extends Serializable {
/**
* Has the object changed since last replication
* and is not in a locked state
* @return boolean
*/
public boolean isDirty();
/**
* If this returns true, the map will extract the diff using getDiff()
* Otherwise it will serialize the entire object.
* @return boolean
*/
public boolean isDiffable();
/**
* Returns a diff and sets the dirty map to false
* @return byte[]
* @throws IOException
*/
public byte[] getDiff() throws IOException;
/**
* Applies a diff to an existing object.
* @param diff byte[]
* @param offset int
* @param length int
* @throws IOException
*/
public void applyDiff(byte[] diff, int offset, int length) throws IOException, ClassNotFoundException;
/**
* Resets the current diff state and resets the dirty flag
*/
public void resetDiff();
/**
* Lock during serialization
*/
public void lock();
/**
* Unlock after serialization
*/
public void unlock();
/**
* This method is called after the object has been
* created on a remote map. On this method,
* the object can initialize itself for any data that wasn't
*
* @param owner Object
*/
public void setOwner(Object owner);
/**
* For accuracy checking, a serialized attribute can contain a version number
* This number increases as modifications are made to the data.
* The replicated map can use this to ensure accuracy on a periodic basis
* @return long - the version number or -1 if the data is not versioned
*/
public long getVersion();
/**
* Forces a certain version to a replicated map entry<br>
* @param version long
*/
public void setVersion(long version);
/**
* Return the last replicate time.
*/
public long getLastTimeReplicated();
/**
* Set the last replicate time.
* @param lastTimeReplicated
*/
public void setLastTimeReplicated(long lastTimeReplicated);
/**
* If this returns true, to replicate that an object has been accessed
* @return boolean
*/
public boolean isAccessReplicate();
/**
* Access to an existing object.
*/
public void accessEntry();
} | mit |
prayuditb/tryout-01 | websocket/client/Client/node_modules/react-native/ReactAndroid/src/main/java/com/facebook/yoga/YogaNodeAPI.java | 3376 | /**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.yoga;
// This only exists for legacy reasons. It will be removed sometime in the near future.
public interface YogaNodeAPI<YogaNodeType extends YogaNodeAPI> {
int getChildCount();
YogaNodeType getChildAt(int i);
void addChildAt(YogaNodeType child, int i);
YogaNodeType removeChildAt(int i);
YogaNodeType getParent();
int indexOf(YogaNodeType child);
void setMeasureFunction(YogaMeasureFunction measureFunction);
void setBaselineFunction(YogaBaselineFunction measureFunction);
boolean isMeasureDefined();
void calculateLayout();
boolean isDirty();
boolean hasNewLayout();
void dirty();
void markLayoutSeen();
void copyStyle(YogaNodeType srcNode);
YogaDirection getStyleDirection();
void setDirection(YogaDirection direction);
YogaFlexDirection getFlexDirection();
void setFlexDirection(YogaFlexDirection flexDirection);
YogaJustify getJustifyContent();
void setJustifyContent(YogaJustify justifyContent);
YogaAlign getAlignItems();
void setAlignItems(YogaAlign alignItems);
YogaAlign getAlignSelf();
void setAlignSelf(YogaAlign alignSelf);
YogaAlign getAlignContent();
void setAlignContent(YogaAlign alignContent);
YogaPositionType getPositionType();
void setPositionType(YogaPositionType positionType);
void setWrap(YogaWrap flexWrap);
void setFlex(float flex);
float getFlexGrow();
void setFlexGrow(float flexGrow);
float getFlexShrink();
void setFlexShrink(float flexShrink);
YogaValue getFlexBasis();
void setFlexBasis(float flexBasis);
void setFlexBasisPercent(float percent);
YogaValue getMargin(YogaEdge edge);
void setMargin(YogaEdge edge, float margin);
void setMarginPercent(YogaEdge edge, float percent);
YogaValue getPadding(YogaEdge edge);
void setPadding(YogaEdge edge, float padding);
void setPaddingPercent(YogaEdge edge, float percent);
float getBorder(YogaEdge edge);
void setBorder(YogaEdge edge, float border);
YogaValue getPosition(YogaEdge edge);
void setPosition(YogaEdge edge, float position);
void setPositionPercent(YogaEdge edge, float percent);
YogaValue getWidth();
void setWidth(float width);
void setWidthPercent(float percent);
YogaValue getHeight();
void setHeight(float height);
void setHeightPercent(float percent);
YogaValue getMaxWidth();
void setMaxWidth(float maxWidth);
void setMaxWidthPercent(float percent);
YogaValue getMinWidth();
void setMinWidth(float minWidth);
void setMinWidthPercent(float percent);
YogaValue getMaxHeight();
void setMaxHeight(float maxHeight);
void setMaxHeightPercent(float percent);
YogaValue getMinHeight();
void setMinHeight(float minHeight);
void setMinHeightPercent(float percent);
float getLayoutX();
float getLayoutY();
float getLayoutWidth();
float getLayoutHeight();
float getLayoutMargin(YogaEdge edge);
float getLayoutPadding(YogaEdge edge);
YogaDirection getLayoutDirection();
YogaOverflow getOverflow();
void setOverflow(YogaOverflow overflow);
void setData(Object data);
Object getData();
void reset();
}
| mit |
rayyang2000/goclipse | plugin_ide.core.tests/src-lang/melnorme/lang/ide/core/tests/CommonCoreTest.java | 6422 | /*******************************************************************************
* Copyright (c) 2008, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.lang.ide.core.tests;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertFail;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.osgi.service.datalocation.Location;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import melnorme.lang.ide.core.LangCore;
import melnorme.lang.ide.core.LangNature;
import melnorme.lang.ide.core.tests.utils.ErrorLogListener;
import melnorme.lang.ide.core.utils.EclipseUtils;
import melnorme.lang.ide.core.utils.ResourceUtils;
import melnorme.utilbox.misc.MiscUtil;
import melnorme.utilbox.misc.StreamUtil;
import melnorme.utilbox.misc.StringUtil;
import melnorme.utilbox.tests.CommonTest;
import melnorme.utilbox.tests.TestsWorkingDir;
/**
* Base core test class that adds an exception listener to the platform log.
* The ErrorLogListener was the only way I found to detect UI exceptions in SafeRunnable's
* when running as plugin test.
*/
public abstract class CommonCoreTest extends CommonTest {
static {
initializeWorkingDirToEclipseInstanceLocation();
disableAutoBuild();
LangCore.getInstance().initializeAfterUIStart();
}
protected static void disableAutoBuild() {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceDescription desc= workspace.getDescription();
desc.setAutoBuilding(false);
try {
workspace.setDescription(desc);
} catch (CoreException e) {
throw melnorme.utilbox.core.ExceptionAdapter.unchecked(e);
}
}
protected static ErrorLogListener logErrorListener;
@BeforeClass
public static void setUpExceptionListenerStatic() throws Exception {
logErrorListener = ErrorLogListener.createAndInstall();
}
@AfterClass
public static void checkLogErrorListenerStatic() throws Throwable {
logErrorListener.checkErrorsAndUninstall();
}
public static void checkLogErrors_() throws Throwable {
logErrorListener.checkErrors();
}
// the @Before and @After are not applied to the same method, so that better stack information can
// be obtained the if the method fails its check.
@Before
public void checkLogErrors_before() throws Throwable {
doCheckLogErrors();
}
@After
public void checkLogErrors_after() throws Throwable {
doCheckLogErrors();
}
protected void doCheckLogErrors() throws Throwable {
checkLogErrors_();
}
private static void initializeWorkingDirToEclipseInstanceLocation() {
Location instanceLocation = Platform.getInstanceLocation();
try {
URI uri = instanceLocation.getURL().toURI();
Path workingDirPath = new File(uri).toPath().toAbsolutePath().resolve("TestsWD");
TestsWorkingDir.initWorkingDir(workingDirPath.toString());
} catch (URISyntaxException e) {
throw assertFail();
}
}
/* ----------------- utilities ----------------- */
public static org.eclipse.core.runtime.Path epath(melnorme.utilbox.misc.Location loc) {
return ResourceUtils.epath(loc);
}
public static org.eclipse.core.runtime.Path epath(Path path) {
return ResourceUtils.epath(path);
}
public static Path path(IPath path) {
return MiscUtil.createValidPath(path.toOSString());
}
public static IProject createAndOpenProject(String name, boolean overwrite) throws CoreException {
return ResourceUtils.createAndOpenProject(name, overwrite);
}
public static void deleteProject(String projectName) throws CoreException {
ResourceUtils.tryDeleteProject(projectName);
}
public static IFolder createFolder(IFolder folder) throws CoreException {
folder.create(true, true, null);
return folder;
}
public static void deleteResource(IResource resource) throws CoreException {
resource.delete(false, new NullProgressMonitor());
}
/* ----------------- ----------------- */
public static IProject createLangProject(String projectName, boolean overwrite) throws CoreException {
IProject project = ResourceUtils.createAndOpenProject(projectName, overwrite);
setupLangProject(project, false);
return project;
}
public static void setupLangProject(IProject project) throws CoreException {
setupLangProject(project, true);
}
public static void setupLangProject(IProject project, boolean requireWsLock) throws CoreException {
assertTrue(project.exists());
if(requireWsLock) {
ISchedulingRule currentRule = Job.getJobManager().currentRule();
assertTrue(currentRule != null && currentRule.contains(project));
}
EclipseUtils.addNature(project, LangNature.NATURE_ID);
}
public static String readFileContents(IFile file) throws CoreException, IOException {
return StreamUtil.readStringFromReader(new InputStreamReader(file.getContents(), StringUtil.UTF8));
}
public static void writeStringToFile(IProject project, String filePath, String contents)
throws CoreException {
IFile file = project.getFile(filePath);
ResourceUtils.writeStringToFile(file, contents, null);
}
} | epl-1.0 |
jballanc/openmicroscopy | components/insight/SRC/org/openmicroscopy/shoola/svc/SvcDescriptor.java | 1979 | /*
* org.openmicroscopy.shoola.svc.SvcDescriptor
*
*------------------------------------------------------------------------------
* Copyright (C) 2006 University of Dundee. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
package org.openmicroscopy.shoola.svc;
//Java imports
//Third-party libraries
//Application-internal dependencies
/**
* A marker interface to denote classes that are used to describe a service
* during the lookup and creation phase.
* Implementing classes usually hold some service-specific parameters that
* have to be used to lookup and/or create the service.
*
*
* @author Jean-Marie Burel
* <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @author Donald MacDonald
* <a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a>
* @version 3.0
* <small>
* (<b>Internal version:</b> $Revision: $Date: $)
* </small>
* @since OME3.0
*/
public interface SvcDescriptor
{
/**
* Returns a human readable name for the service that this descriptor
* identifies.
*
* @return See above.
*/
public String getSvcName();
}
| gpl-2.0 |
ua-eas/ua-kfs-5.3 | work/src/org/kuali/kfs/gl/batch/DemergerStep.java | 2714 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.gl.batch;
import org.kuali.kfs.gl.service.ScrubberService;
import org.kuali.kfs.sys.batch.AbstractWrappedBatchStep;
import org.kuali.kfs.sys.batch.service.WrappedBatchExecutorService.CustomBatchExecutor;
import org.springframework.util.StopWatch;
/**
* A step to run the scrubber process.
*/
public class DemergerStep extends AbstractWrappedBatchStep {
private ScrubberService scrubberService;
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DemergerStep.class);
/**
* Overridden to run the scrubber demerger process.
* @see org.kuali.kfs.batch.Step#execute(java.lang.String)
*/
@Override
protected CustomBatchExecutor getCustomBatchExecutor() {
return new CustomBatchExecutor() {
public boolean execute() {
final String jobName = "demerger";
StopWatch stopWatch = new StopWatch();
stopWatch.start(jobName);
scrubberService.performDemerger();
stopWatch.stop();
LOG.info("scrubber step of " + jobName + " took " + (stopWatch.getTotalTimeSeconds() / 60.0) + " minutes to complete");
if (LOG.isDebugEnabled()) {
LOG.debug("scrubber step of " + jobName + " took " + (stopWatch.getTotalTimeSeconds() / 60.0) + " minutes to complete");
}
return true;
}
};
}
/**
* Sets the scrubberSerivce, allowing the injection of an implementation of that service
*
* @param scrubberService the scrubberServiceService implementation to set
* @see org.kuali.module.gl.service.ScrubberService
*/
public void setScrubberService(ScrubberService ss) {
scrubberService = ss;
}
}
| agpl-3.0 |
Jaeyo/lanterna | src/main/java/com/googlecode/lanterna/screen/AbstractScreen.java | 9225 | /*
* This file is part of lanterna (http://code.google.com/p/lanterna/).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2014 Martin
*/
package com.googlecode.lanterna.screen;
import com.googlecode.lanterna.CJKUtils;
import com.googlecode.lanterna.TerminalSize;
import com.googlecode.lanterna.TextCharacter;
import com.googlecode.lanterna.graphics.TextGraphics;
import com.googlecode.lanterna.TerminalPosition;
import com.googlecode.lanterna.graphics.TextImage;
import java.io.IOException;
/**
* This class implements some of the Screen logic that is not directly tied to the actual implementation of how the
* Screen translate to the terminal. It keeps data structures for the front- and back buffers, the cursor location and
* some other simpler states.
* @author martin
*/
public abstract class AbstractScreen implements Screen {
private TerminalPosition cursorPosition;
private ScreenBuffer backBuffer;
private ScreenBuffer frontBuffer;
private final TextCharacter defaultCharacter;
//How to deal with \t characters
private TabBehaviour tabBehaviour;
//Current size of the screen
private TerminalSize terminalSize;
//Pending resize of the screen
private TerminalSize latestResizeRequest;
public AbstractScreen(TerminalSize initialSize) {
this(initialSize, DEFAULT_CHARACTER);
}
/**
* Creates a new Screen on top of a supplied terminal, will query the terminal for its size. The screen is initially
* blank. You can specify which character you wish to be used to fill the screen initially; this will also be the
* character used if the terminal is enlarged and you don't set anything on the new areas.
*
* @param initialSize Size to initially create the Screen with (can be resized later)
* @param defaultCharacter What character to use for the initial state of the screen and expanded areas
*/
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public AbstractScreen(TerminalSize initialSize, TextCharacter defaultCharacter) {
this.frontBuffer = new ScreenBuffer(initialSize, defaultCharacter);
this.backBuffer = new ScreenBuffer(initialSize, defaultCharacter);
this.defaultCharacter = defaultCharacter;
this.cursorPosition = new TerminalPosition(0, 0);
this.tabBehaviour = TabBehaviour.ALIGN_TO_COLUMN_4;
this.terminalSize = initialSize;
this.latestResizeRequest = null;
}
/**
* @return Position where the cursor will be located after the screen has been refreshed or {@code null} if the
* cursor is not visible
*/
@Override
public TerminalPosition getCursorPosition() {
return cursorPosition;
}
/**
* Moves the current cursor position or hides it. If the cursor is hidden and given a new position, it will be
* visible after this method call.
*
* @param position 0-indexed column and row numbers of the new position, or if {@code null}, hides the cursor
*/
@Override
public void setCursorPosition(TerminalPosition position) {
if(position == null) {
//Skip any validation checks if we just want to hide the cursor
this.cursorPosition = null;
return;
}
if(position.getColumn() >= 0 && position.getColumn() < terminalSize.getColumns()
&& position.getRow() >= 0 && position.getRow() < terminalSize.getRows()) {
this.cursorPosition = position;
}
}
/**
* Sets the behaviour for what to do about tab characters.
*
* @param tabBehaviour Tab behaviour to use
* @see TabBehaviour
*/
@Override
public void setTabBehaviour(TabBehaviour tabBehaviour) {
if(tabBehaviour != null) {
this.tabBehaviour = tabBehaviour;
}
}
/**
* Gets the behaviour for what to do about tab characters.
*
* @return Tab behaviour that is used currently
* @see TabBehaviour
*/
@Override
public TabBehaviour getTabBehaviour() {
return tabBehaviour;
}
@Override
public void setCharacter(TerminalPosition position, TextCharacter screenCharacter) {
setCharacter(position.getColumn(), position.getRow(), screenCharacter);
}
@Override
public TextGraphics newTextGraphics() {
return new ScreenTextGraphics(this) {
@Override
public TextGraphics drawImage(TerminalPosition topLeft, TextImage image, TerminalPosition sourceImageTopLeft, TerminalSize sourceImageSize) {
backBuffer.copyFrom(image, sourceImageTopLeft.getRow(), sourceImageSize.getRows(), sourceImageTopLeft.getColumn(), sourceImageSize.getColumns(), topLeft.getRow(), topLeft.getColumn());
return this;
}
};
}
@Override
public synchronized void setCharacter(int column, int row, TextCharacter screenCharacter) {
//It would be nice if we didn't have to care about tabs at this level, but we have no such luxury
if(screenCharacter.getCharacter() == '\t') {
//Swap out the tab for a space
screenCharacter = screenCharacter.withCharacter(' ');
//Now see how many times we have to put spaces...
for(int i = 0; i < tabBehaviour.replaceTabs("\t", column).length(); i++) {
backBuffer.setCharacterAt(column + i, row, screenCharacter);
}
}
else {
//This is the normal case, no special character
backBuffer.setCharacterAt(column, row, screenCharacter);
}
//Pad CJK character with a trailing space
if(CJKUtils.isCharCJK(screenCharacter.getCharacter())) {
backBuffer.setCharacterAt(column + 1, row, screenCharacter.withCharacter(' '));
}
//If there's a CJK character immediately to our left, reset it
if(column > 0) {
TextCharacter cjkTest = backBuffer.getCharacterAt(column - 1, row);
if(cjkTest != null && CJKUtils.isCharCJK(cjkTest.getCharacter())) {
backBuffer.setCharacterAt(column - 1, row, backBuffer.getCharacterAt(column - 1, row).withCharacter(' '));
}
}
}
@Override
public synchronized TextCharacter getFrontCharacter(TerminalPosition position) {
return getFrontCharacter(position.getColumn(), position.getRow());
}
@Override
public TextCharacter getFrontCharacter(int column, int row) {
return getCharacterFromBuffer(frontBuffer, column, row);
}
@Override
public synchronized TextCharacter getBackCharacter(TerminalPosition position) {
return getBackCharacter(position.getColumn(), position.getRow());
}
@Override
public TextCharacter getBackCharacter(int column, int row) {
return getCharacterFromBuffer(backBuffer, column, row);
}
@Override
public void refresh() throws IOException {
refresh(RefreshType.AUTOMATIC);
}
@Override
public synchronized void clear() {
backBuffer.setAll(defaultCharacter);
}
@Override
public synchronized TerminalSize doResizeIfNecessary() {
TerminalSize pendingResize = getAndClearPendingResize();
if(pendingResize == null) {
return null;
}
backBuffer = backBuffer.resize(pendingResize, defaultCharacter);
frontBuffer = frontBuffer.resize(pendingResize, defaultCharacter);
return pendingResize;
}
@Override
public TerminalSize getTerminalSize() {
return terminalSize;
}
protected ScreenBuffer getFrontBuffer() {
return frontBuffer;
}
protected ScreenBuffer getBackBuffer() {
return backBuffer;
}
private synchronized TerminalSize getAndClearPendingResize() {
if(latestResizeRequest != null) {
terminalSize = latestResizeRequest;
latestResizeRequest = null;
return terminalSize;
}
return null;
}
protected void addResizeRequest(TerminalSize newSize) {
latestResizeRequest = newSize;
}
private TextCharacter getCharacterFromBuffer(ScreenBuffer buffer, int column, int row) {
//If we are picking the padding of a CJK character, pick the actual CJK character instead of the padding
if(column > 0 && CJKUtils.isCharCJK(buffer.getCharacterAt(column - 1, row).getCharacter())) {
return buffer.getCharacterAt(column - 1, row);
}
return buffer.getCharacterAt(column, row);
}
}
| lgpl-3.0 |
johnnywale/drill | exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/svremover/RemovingRecordBatch.java | 3864 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.physical.impl.svremover;
import org.apache.drill.exec.exception.OutOfMemoryException;
import org.apache.drill.exec.ops.FragmentContext;
import org.apache.drill.exec.physical.config.SelectionVectorRemover;
import org.apache.drill.exec.record.AbstractSingleRecordBatch;
import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
import org.apache.drill.exec.record.RecordBatch;
import org.apache.drill.exec.record.WritableBatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RemovingRecordBatch extends AbstractSingleRecordBatch<SelectionVectorRemover>{
private static final Logger logger = LoggerFactory.getLogger(RemovingRecordBatch.class);
private Copier copier;
public RemovingRecordBatch(SelectionVectorRemover popConfig, FragmentContext context,
RecordBatch incoming) throws OutOfMemoryException {
super(popConfig, context, incoming);
logger.debug("Created.");
}
@Override
public int getRecordCount() {
return container.getRecordCount();
}
@Override
protected boolean setupNewSchema() {
// Don't clear off container just because an OK_NEW_SCHEMA was received from
// upstream. For cases when there is just
// change in container type but no actual schema change, RemovingRecordBatch
// should consume OK_NEW_SCHEMA and
// send OK to downstream instead. Since the output of RemovingRecordBatch is
// always going to be a regular container
// change in incoming container type is not actual schema change.
container.zeroVectors();
copier = GenericCopierFactory.createAndSetupCopier(incoming, container, callBack);
// If there is an actual schema change then below condition will be true and
// it will send OK_NEW_SCHEMA
// downstream too
if (container.isSchemaChanged()) {
container.buildSchema(SelectionVectorMode.NONE);
return true;
}
return false;
}
@Override
protected IterOutcome doWork() {
try {
int rowCount = incoming.getRecordCount();
if (rowCount == 0) {
container.setEmpty();
} else {
copier.copyRecords(0, rowCount);
}
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
if (incoming.getSchema().getSelectionVectorMode() != SelectionVectorMode.FOUR_BYTE) {
incoming.getContainer().zeroVectors();
if (incoming.getSchema().getSelectionVectorMode() == SelectionVectorMode.TWO_BYTE) {
incoming.getSelectionVector2().clear();
}
}
}
logger.debug("doWork(): {} records copied out of {}, incoming schema {} ",
container.getRecordCount(), container.getRecordCount(), incoming.getSchema());
return getFinalOutcome(false);
}
@Override
public void close() {
super.close();
}
@Override
public WritableBatch getWritableBatch() {
return WritableBatch.get(this);
}
@Override
public void dump() {
logger.error("RemovingRecordBatch[container={}, state={}, copier={}]", container, state, copier);
}
}
| apache-2.0 |
DebalinaDey/AuraDevelopDeb | aura-util/src/main/java/org/auraframework/util/javascript/JavascriptProcessingError.java | 2755 | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.util.javascript;
import java.util.List;
import java.util.Map;
import org.auraframework.util.validation.ValidationError;
/**
* javascript ouchies
*/
public final class JavascriptProcessingError extends ValidationError {
public enum Level {
Warning, Error;
}
public JavascriptProcessingError() {
super("js/custom", Level.Error);
}
JavascriptProcessingError(String tool, String filename, Map<String, ?> error) {
super(tool, filename, error);
}
public JavascriptProcessingError(String message, int line, int character, String filename, String evidence,
Level level) {
super("js/custom", filename, line, character, message, evidence, level, null);
}
private static JavascriptProcessingError make(List<JavascriptProcessingError> errorsList, String message, int line,
int character, String filename, String evidence, Level level) {
JavascriptProcessingError msg = new JavascriptProcessingError(message, line, character, filename, evidence,
level);
errorsList.add(msg);
return msg;
}
public static JavascriptProcessingError makeWarning(List<JavascriptProcessingError> errorsList, String message,
int line, int character, String filename, String evidence) {
return make(errorsList, message, line, character, filename, evidence, Level.Warning);
}
public static JavascriptProcessingError makeError(List<JavascriptProcessingError> errorsList, String message,
int line, int character, String filename, String evidence) {
return make(errorsList, message, line, character, filename, evidence, Level.Error);
}
@Override
public String toString() {
String s = String.format("JS Processing %s: %s (line %s, char %s) : %s", getLevel(), getFilename(), getLine(),
getStartColumn(), getMessage());
String evidence = getEvidence();
if (evidence != null && evidence.length() > 0) {
s += String.format(" \n %s", evidence);
}
s += '\n';
return s;
}
}
| apache-2.0 |
amith01994/intellij-community | platform/util/src/com/intellij/icons/AllIcons.java | 107571 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.icons;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
/**
* NOTE THIS FILE IS AUTO-GENERATED
* DO NOT EDIT IT BY HAND, run build/scripts/icons.gant instead
*/
public class AllIcons {
public static class Actions {
public static final Icon AddFacesSupport = IconLoader.getIcon("/actions/addFacesSupport.png"); // 16x16
public static final Icon AddMulticaret = IconLoader.getIcon("/actions/AddMulticaret.png"); // 16x16
public static final Icon AllLeft = IconLoader.getIcon("/actions/allLeft.png"); // 16x16
public static final Icon AllRight = IconLoader.getIcon("/actions/allRight.png"); // 16x16
public static final Icon Annotate = IconLoader.getIcon("/actions/annotate.png"); // 16x16
public static final Icon Back = IconLoader.getIcon("/actions/back.png"); // 16x16
public static final Icon Browser_externalJavaDoc = IconLoader.getIcon("/actions/browser-externalJavaDoc.png"); // 16x16
public static final Icon Cancel = IconLoader.getIcon("/actions/cancel.png"); // 16x16
public static final Icon Checked = IconLoader.getIcon("/actions/checked.png"); // 12x12
public static final Icon Checked_selected = IconLoader.getIcon("/actions/checked_selected.png"); // 12x12
public static final Icon Checked_small = IconLoader.getIcon("/actions/checked_small.png"); // 11x11
public static final Icon Checked_small_selected = IconLoader.getIcon("/actions/checked_small_selected.png"); // 11x11
public static final Icon CheckedBlack = IconLoader.getIcon("/actions/checkedBlack.png"); // 12x12
public static final Icon CheckedGrey = IconLoader.getIcon("/actions/checkedGrey.png"); // 12x12
public static final Icon CheckMulticaret = IconLoader.getIcon("/actions/CheckMulticaret.png"); // 16x16
public static final Icon CheckOut = IconLoader.getIcon("/actions/checkOut.png"); // 16x16
public static final Icon Clean = IconLoader.getIcon("/actions/clean.png"); // 16x16
public static final Icon CleanLight = IconLoader.getIcon("/actions/cleanLight.png"); // 16x16
public static final Icon Close = IconLoader.getIcon("/actions/close.png"); // 16x16
public static final Icon CloseHovered = IconLoader.getIcon("/actions/closeHovered.png"); // 16x16
public static final Icon CloseNew = IconLoader.getIcon("/actions/closeNew.png"); // 16x16
public static final Icon CloseNewHovered = IconLoader.getIcon("/actions/closeNewHovered.png"); // 16x16
public static final Icon Collapseall = IconLoader.getIcon("/actions/collapseall.png"); // 16x16
public static final Icon Commit = IconLoader.getIcon("/actions/commit.png"); // 16x16
public static final Icon Compile = IconLoader.getIcon("/actions/compile.png"); // 16x16
public static final Icon Copy = IconLoader.getIcon("/actions/copy.png"); // 16x16
public static final Icon CreateFromUsage = IconLoader.getIcon("/actions/createFromUsage.png"); // 16x16
public static final Icon CreatePatch = IconLoader.getIcon("/actions/createPatch.png"); // 16x16
public static final Icon Cross = IconLoader.getIcon("/actions/cross.png"); // 12x12
public static final Icon Delete = IconLoader.getIcon("/actions/delete.png"); // 16x16
public static final Icon Diff = IconLoader.getIcon("/actions/diff.png"); // 16x16
public static final Icon DiffWithCurrent = IconLoader.getIcon("/actions/diffWithCurrent.png"); // 16x16
public static final Icon Down = IconLoader.getIcon("/actions/down.png"); // 16x16
public static final Icon Download = IconLoader.getIcon("/actions/download.png"); // 16x16
public static final Icon Dump = IconLoader.getIcon("/actions/dump.png"); // 16x16
public static final Icon Edit = IconLoader.getIcon("/actions/edit.png"); // 14x14
public static final Icon EditSource = IconLoader.getIcon("/actions/editSource.png"); // 16x16
public static final Icon ErDiagram = IconLoader.getIcon("/actions/erDiagram.png"); // 16x16
public static final Icon Exclude = IconLoader.getIcon("/actions/exclude.png"); // 14x14
public static final Icon Execute = IconLoader.getIcon("/actions/execute.png"); // 16x16
public static final Icon Exit = IconLoader.getIcon("/actions/exit.png"); // 16x16
public static final Icon Expandall = IconLoader.getIcon("/actions/expandall.png"); // 16x16
public static final Icon Export = IconLoader.getIcon("/actions/export.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon FileStatus = IconLoader.getIcon("/actions/fileStatus.png"); // 16x16
public static final Icon Filter_small = IconLoader.getIcon("/actions/filter_small.png"); // 16x16
public static final Icon Find = IconLoader.getIcon("/actions/find.png"); // 16x16
public static final Icon FindPlain = IconLoader.getIcon("/actions/findPlain.png"); // 16x16
public static final Icon FindWhite = IconLoader.getIcon("/actions/findWhite.png"); // 16x16
public static final Icon ForceRefresh = IconLoader.getIcon("/actions/forceRefresh.png"); // 16x16
public static final Icon Forward = IconLoader.getIcon("/actions/forward.png"); // 16x16
public static final Icon GC = IconLoader.getIcon("/actions/gc.png"); // 16x16
public static final Icon Get = IconLoader.getIcon("/actions/get.png"); // 16x16
public static final Icon GroupByClass = IconLoader.getIcon("/actions/GroupByClass.png"); // 16x16
public static final Icon GroupByFile = IconLoader.getIcon("/actions/GroupByFile.png"); // 16x16
public static final Icon GroupByMethod = IconLoader.getIcon("/actions/groupByMethod.png"); // 16x16
public static final Icon GroupByModule = IconLoader.getIcon("/actions/GroupByModule.png"); // 16x16
public static final Icon GroupByModuleGroup = IconLoader.getIcon("/actions/GroupByModuleGroup.png"); // 16x16
public static final Icon GroupByPackage = IconLoader.getIcon("/actions/GroupByPackage.png"); // 16x16
public static final Icon GroupByPrefix = IconLoader.getIcon("/actions/GroupByPrefix.png"); // 16x16
public static final Icon GroupByTestProduction = IconLoader.getIcon("/actions/groupByTestProduction.png"); // 16x16
public static final Icon Help = IconLoader.getIcon("/actions/help.png"); // 16x16
public static final Icon Install = IconLoader.getIcon("/actions/install.png"); // 16x16
public static final Icon IntentionBulb = IconLoader.getIcon("/actions/intentionBulb.png"); // 16x16
public static final Icon Left = IconLoader.getIcon("/actions/left.png"); // 16x16
public static final Icon Lightning = IconLoader.getIcon("/actions/lightning.png"); // 16x16
public static final Icon Menu_cut = IconLoader.getIcon("/actions/menu-cut.png"); // 16x16
public static final Icon Menu_find = IconLoader.getIcon("/actions/menu-find.png"); // 16x16
public static final Icon Menu_help = IconLoader.getIcon("/actions/menu-help.png"); // 16x16
public static final Icon Menu_open = IconLoader.getIcon("/actions/menu-open.png"); // 16x16
public static final Icon Menu_paste = IconLoader.getIcon("/actions/menu-paste.png"); // 16x16
public static final Icon Menu_replace = IconLoader.getIcon("/actions/menu-replace.png"); // 16x16
public static final Icon Menu_saveall = IconLoader.getIcon("/actions/menu-saveall.png"); // 16x16
public static final Icon Minimize = IconLoader.getIcon("/actions/minimize.png"); // 16x16
public static final Icon Module = IconLoader.getIcon("/actions/module.png"); // 16x16
public static final Icon Move_to_button_top = IconLoader.getIcon("/actions/move-to-button-top.png"); // 11x12
public static final Icon Move_to_button = IconLoader.getIcon("/actions/move-to-button.png"); // 11x10
public static final Icon MoveDown = IconLoader.getIcon("/actions/moveDown.png"); // 14x14
public static final Icon MoveTo2 = IconLoader.getIcon("/actions/MoveTo2.png"); // 16x16
public static final Icon MoveToAnotherChangelist = IconLoader.getIcon("/actions/moveToAnotherChangelist.png"); // 16x16
public static final Icon MoveToStandardPlace = IconLoader.getIcon("/actions/moveToStandardPlace.png"); // 16x16
public static final Icon MoveUp = IconLoader.getIcon("/actions/moveUp.png"); // 14x14
public static final Icon New = IconLoader.getIcon("/actions/new.png"); // 16x16
public static final Icon NewFolder = IconLoader.getIcon("/actions/newFolder.png"); // 16x16
public static final Icon Nextfile = IconLoader.getIcon("/actions/nextfile.png"); // 16x16
public static final Icon NextOccurence = IconLoader.getIcon("/actions/nextOccurence.png"); // 16x16
public static final Icon Pause = IconLoader.getIcon("/actions/pause.png"); // 16x16
public static final Icon PopFrame = IconLoader.getIcon("/actions/popFrame.png"); // 16x16
public static final Icon Prevfile = IconLoader.getIcon("/actions/prevfile.png"); // 16x16
public static final Icon Preview = IconLoader.getIcon("/actions/preview.png"); // 16x16
public static final Icon PreviewDetails = IconLoader.getIcon("/actions/previewDetails.png"); // 16x16
public static final Icon PreviousOccurence = IconLoader.getIcon("/actions/previousOccurence.png"); // 14x14
public static final Icon Profile = IconLoader.getIcon("/actions/profile.png"); // 16x16
public static final Icon ProfileCPU = IconLoader.getIcon("/actions/profileCPU.png"); // 16x16
public static final Icon ProfileMemory = IconLoader.getIcon("/actions/profileMemory.png"); // 16x16
public static final Icon Properties = IconLoader.getIcon("/actions/properties.png"); // 16x16
public static final Icon QuickfixBulb = IconLoader.getIcon("/actions/quickfixBulb.png"); // 16x16
public static final Icon QuickfixOffBulb = IconLoader.getIcon("/actions/quickfixOffBulb.png"); // 16x16
public static final Icon QuickList = IconLoader.getIcon("/actions/quickList.png"); // 16x16
public static final Icon RealIntentionBulb = IconLoader.getIcon("/actions/realIntentionBulb.png"); // 16x16
public static final Icon RealIntentionOffBulb = IconLoader.getIcon("/actions/realIntentionOffBulb.png"); // 16x16
public static final Icon Redo = IconLoader.getIcon("/actions/redo.png"); // 16x16
public static final Icon RefactoringBulb = IconLoader.getIcon("/actions/refactoringBulb.png"); // 16x16
public static final Icon Refresh = IconLoader.getIcon("/actions/refresh.png"); // 16x16
public static final Icon RemoveMulticaret = IconLoader.getIcon("/actions/RemoveMulticaret.png"); // 16x16
public static final Icon Replace = IconLoader.getIcon("/actions/replace.png"); // 16x16
public static final Icon Rerun = IconLoader.getIcon("/actions/rerun.png"); // 16x16
public static final Icon Reset_to_default = IconLoader.getIcon("/actions/reset-to-default.png"); // 16x16
public static final Icon Reset = IconLoader.getIcon("/actions/reset.png"); // 16x16
public static final Icon Reset_to_empty = IconLoader.getIcon("/actions/Reset_to_empty.png"); // 16x16
public static final Icon Restart = IconLoader.getIcon("/actions/restart.png"); // 16x16
public static final Icon Resume = IconLoader.getIcon("/actions/resume.png"); // 16x16
public static final Icon Right = IconLoader.getIcon("/actions/right.png"); // 16x16
public static final Icon Rollback = IconLoader.getIcon("/actions/rollback.png"); // 16x16
public static final Icon RunToCursor = IconLoader.getIcon("/actions/runToCursor.png"); // 16x16
public static final Icon Scratch = IconLoader.getIcon("/actions/scratch.png"); // 16x16
public static final Icon Search = IconLoader.getIcon("/actions/search.png"); // 16x16
public static final Icon Selectall = IconLoader.getIcon("/actions/selectall.png"); // 16x16
public static final Icon Share = IconLoader.getIcon("/actions/share.png"); // 14x14
public static final Icon ShortcutFilter = IconLoader.getIcon("/actions/shortcutFilter.png"); // 16x16
public static final Icon ShowAsTree = IconLoader.getIcon("/actions/showAsTree.png"); // 16x16
public static final Icon ShowChangesOnly = IconLoader.getIcon("/actions/showChangesOnly.png"); // 16x16
public static final Icon ShowHiddens = IconLoader.getIcon("/actions/showHiddens.png"); // 16x16
public static final Icon ShowImportStatements = IconLoader.getIcon("/actions/showImportStatements.png"); // 16x16
public static final Icon ShowReadAccess = IconLoader.getIcon("/actions/showReadAccess.png"); // 16x16
public static final Icon ShowViewer = IconLoader.getIcon("/actions/showViewer.png"); // 16x16
public static final Icon ShowWriteAccess = IconLoader.getIcon("/actions/showWriteAccess.png"); // 16x16
public static final Icon SortAsc = IconLoader.getIcon("/actions/sortAsc.png"); // 9x8
public static final Icon SortDesc = IconLoader.getIcon("/actions/sortDesc.png"); // 9x8
public static final Icon SplitHorizontally = IconLoader.getIcon("/actions/splitHorizontally.png"); // 16x16
public static final Icon SplitVertically = IconLoader.getIcon("/actions/splitVertically.png"); // 16x16
public static final Icon StartDebugger = IconLoader.getIcon("/actions/startDebugger.png"); // 16x16
public static final Icon StepOut = IconLoader.getIcon("/actions/stepOut.png"); // 16x16
public static final Icon Submit1 = IconLoader.getIcon("/actions/submit1.png"); // 11x11
public static final Icon Suspend = IconLoader.getIcon("/actions/suspend.png"); // 16x16
public static final Icon SwapPanels = IconLoader.getIcon("/actions/swapPanels.png"); // 16x16
public static final Icon SynchronizeScrolling = IconLoader.getIcon("/actions/synchronizeScrolling.png"); // 16x16
public static final Icon SyncPanels = IconLoader.getIcon("/actions/syncPanels.png"); // 16x16
public static final Icon ToggleSoftWrap = IconLoader.getIcon("/actions/toggleSoftWrap.png"); // 16x16
public static final Icon TraceInto = IconLoader.getIcon("/actions/traceInto.png"); // 16x16
public static final Icon TraceOver = IconLoader.getIcon("/actions/traceOver.png"); // 16x16
public static final Icon Undo = IconLoader.getIcon("/actions/undo.png"); // 16x16
public static final Icon Uninstall = IconLoader.getIcon("/actions/uninstall.png"); // 16x16
public static final Icon Unselectall = IconLoader.getIcon("/actions/unselectall.png"); // 16x16
public static final Icon Unshare = IconLoader.getIcon("/actions/unshare.png"); // 14x14
public static final Icon UP = IconLoader.getIcon("/actions/up.png"); // 16x16
}
public static class CodeStyle {
public static final Icon AddNewSectionRule = IconLoader.getIcon("/codeStyle/AddNewSectionRule.png"); // 16x16
public static final Icon Gear = IconLoader.getIcon("/codeStyle/Gear.png"); // 16x16
public static class Mac {
public static final Icon AddNewSectionRule = IconLoader.getIcon("/codeStyle/mac/AddNewSectionRule.png"); // 16x16
}
}
public static class Css {
public static final Icon Atrule = IconLoader.getIcon("/css/atrule.png"); // 16x16
public static final Icon Import = IconLoader.getIcon("/css/import.png"); // 16x16
public static final Icon Property = IconLoader.getIcon("/css/property.png"); // 16x16
public static final Icon Pseudo_class = IconLoader.getIcon("/css/pseudo-class.png"); // 16x16
public static final Icon Pseudo_element = IconLoader.getIcon("/css/pseudo-element.png"); // 16x16
public static final Icon Toolwindow = IconLoader.getIcon("/css/toolwindow.png"); // 13x13
}
public static class Darcula {
public static final Icon DoubleComboArrow = IconLoader.getIcon("/darcula/doubleComboArrow.png"); // 7x11
public static final Icon TreeNodeCollapsed = IconLoader.getIcon("/darcula/treeNodeCollapsed.png"); // 9x9
public static final Icon TreeNodeExpanded = IconLoader.getIcon("/darcula/treeNodeExpanded.png"); // 9x9
}
public static class Debugger {
public static class Actions {
public static final Icon Force_run_to_cursor = IconLoader.getIcon("/debugger/actions/force_run_to_cursor.png"); // 16x16
public static final Icon Force_step_into = IconLoader.getIcon("/debugger/actions/force_step_into.png"); // 16x16
public static final Icon Force_step_over = IconLoader.getIcon("/debugger/actions/force_step_over.png"); // 16x16
}
public static final Icon AddToWatch = IconLoader.getIcon("/debugger/addToWatch.png"); // 16x16
public static final Icon AutoVariablesMode = IconLoader.getIcon("/debugger/autoVariablesMode.png"); // 16x16
public static final Icon BreakpointAlert = IconLoader.getIcon("/debugger/breakpointAlert.png"); // 16x16
public static final Icon Class_filter = IconLoader.getIcon("/debugger/class_filter.png"); // 16x16
public static final Icon CommandLine = IconLoader.getIcon("/debugger/commandLine.png"); // 16x16
public static final Icon Console = IconLoader.getIcon("/debugger/console.png"); // 16x16
public static final Icon Console_log = IconLoader.getIcon("/debugger/console_log.png"); // 16x16
public static final Icon Db_array = IconLoader.getIcon("/debugger/db_array.png"); // 16x16
public static final Icon Db_db_object = IconLoader.getIcon("/debugger/db_db_object.png"); // 16x16
public static final Icon Db_dep_exception_breakpoint = IconLoader.getIcon("/debugger/db_dep_exception_breakpoint.png"); // 12x12
public static final Icon Db_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_dep_field_breakpoint.png"); // 12x12
public static final Icon Db_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_dep_line_breakpoint.png"); // 12x12
public static final Icon Db_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_dep_method_breakpoint.png"); // 12x12
public static final Icon Db_disabled_breakpoint = IconLoader.getIcon("/debugger/db_disabled_breakpoint.png"); // 12x12
public static final Icon Db_disabled_breakpoint_process = IconLoader.getIcon("/debugger/db_disabled_breakpoint_process.png"); // 16x16
public static final Icon Db_disabled_exception_breakpoint = IconLoader.getIcon("/debugger/db_disabled_exception_breakpoint.png"); // 12x12
public static final Icon Db_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_disabled_field_breakpoint.png"); // 12x12
public static final Icon Db_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_disabled_method_breakpoint.png"); // 12x12
public static final Icon Db_exception_breakpoint = IconLoader.getIcon("/debugger/db_exception_breakpoint.png"); // 12x12
public static final Icon Db_field_breakpoint = IconLoader.getIcon("/debugger/db_field_breakpoint.png"); // 12x12
public static final Icon Db_field_warning_breakpoint = IconLoader.getIcon("/debugger/db_field_warning_breakpoint.png"); // 16x16
public static final Icon Db_invalid_breakpoint = IconLoader.getIcon("/debugger/db_invalid_breakpoint.png"); // 12x12
public static final Icon Db_invalid_field_breakpoint = IconLoader.getIcon("/debugger/db_invalid_field_breakpoint.png"); // 12x12
public static final Icon Db_invalid_method_breakpoint = IconLoader.getIcon("/debugger/db_invalid_method_breakpoint.png"); // 12x12
public static final Icon Db_method_breakpoint = IconLoader.getIcon("/debugger/db_method_breakpoint.png"); // 12x12
public static final Icon Db_method_warning_breakpoint = IconLoader.getIcon("/debugger/db_method_warning_breakpoint.png"); // 16x16
public static final Icon Db_muted_breakpoint = IconLoader.getIcon("/debugger/db_muted_breakpoint.png"); // 12x12
public static final Icon Db_muted_dep_exception_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_exception_breakpoint.png"); // 12x12
public static final Icon Db_muted_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_line_breakpoint.png"); // 12x12
public static final Icon Db_muted_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_disabled_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_breakpoint.png"); // 12x12
public static final Icon Db_muted_disabled_breakpoint_process = IconLoader.getIcon("/debugger/db_muted_disabled_breakpoint_process.png"); // 16x16
public static final Icon Db_muted_disabled_exception_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_exception_breakpoint.png"); // 12x12
public static final Icon Db_muted_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_exception_breakpoint = IconLoader.getIcon("/debugger/db_muted_exception_breakpoint.png"); // 12x12
public static final Icon Db_muted_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_field_warning_breakpoint = IconLoader.getIcon("/debugger/db_muted_field_warning_breakpoint.png"); // 16x16
public static final Icon Db_muted_invalid_breakpoint = IconLoader.getIcon("/debugger/db_muted_invalid_breakpoint.png"); // 12x12
public static final Icon Db_muted_invalid_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_invalid_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_invalid_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_invalid_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_method_warning_breakpoint = IconLoader.getIcon("/debugger/db_muted_method_warning_breakpoint.png"); // 16x16
public static final Icon Db_muted_temporary_breakpoint = IconLoader.getIcon("/debugger/db_muted_temporary_breakpoint.png"); // 12x12
public static final Icon Db_muted_verified_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_breakpoint.png"); // 12x12
public static final Icon Db_muted_verified_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_verified_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_verified_warning_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_warning_breakpoint.png"); // 16x16
public static final Icon Db_obsolete = IconLoader.getIcon("/debugger/db_obsolete.png"); // 12x12
public static final Icon Db_primitive = IconLoader.getIcon("/debugger/db_primitive.png"); // 16x16
public static final Icon Db_set_breakpoint = IconLoader.getIcon("/debugger/db_set_breakpoint.png"); // 12x12
public static final Icon Db_temporary_breakpoint = IconLoader.getIcon("/debugger/db_temporary_breakpoint.png"); // 12x12
public static final Icon Db_verified_breakpoint = IconLoader.getIcon("/debugger/db_verified_breakpoint.png"); // 12x12
public static final Icon Db_verified_field_breakpoint = IconLoader.getIcon("/debugger/db_verified_field_breakpoint.png"); // 12x12
public static final Icon Db_verified_method_breakpoint = IconLoader.getIcon("/debugger/db_verified_method_breakpoint.png"); // 12x12
public static final Icon Db_verified_warning_breakpoint = IconLoader.getIcon("/debugger/db_verified_warning_breakpoint.png"); // 16x16
public static final Icon Disable_value_calculation = IconLoader.getIcon("/debugger/disable_value_calculation.png"); // 16x16
public static final Icon EvaluateExpression = IconLoader.getIcon("/debugger/evaluateExpression.png"); // 16x16
public static final Icon Frame = IconLoader.getIcon("/debugger/frame.png"); // 16x16
public static final Icon KillProcess = IconLoader.getIcon("/debugger/killProcess.png"); // 16x16
public static final Icon MuteBreakpoints = IconLoader.getIcon("/debugger/muteBreakpoints.png"); // 16x16
public static final Icon NewWatch = IconLoader.getIcon("/debugger/newWatch.png"); // 16x16
public static final Icon RestoreLayout = IconLoader.getIcon("/debugger/restoreLayout.png"); // 16x16
public static final Icon ShowCurrentFrame = IconLoader.getIcon("/debugger/showCurrentFrame.png"); // 16x16
public static final Icon SmartStepInto = IconLoader.getIcon("/debugger/smartStepInto.png"); // 16x16
public static final Icon StackFrame = IconLoader.getIcon("/debugger/stackFrame.png"); // 16x16
public static final Icon ThreadAtBreakpoint = IconLoader.getIcon("/debugger/threadAtBreakpoint.png"); // 16x16
public static final Icon ThreadCurrent = IconLoader.getIcon("/debugger/threadCurrent.png"); // 16x16
public static final Icon ThreadFrozen = IconLoader.getIcon("/debugger/threadFrozen.png"); // 16x16
public static final Icon ThreadGroup = IconLoader.getIcon("/debugger/threadGroup.png"); // 16x16
public static final Icon ThreadGroupCurrent = IconLoader.getIcon("/debugger/threadGroupCurrent.png"); // 16x16
public static final Icon ThreadRunning = IconLoader.getIcon("/debugger/threadRunning.png"); // 16x16
public static final Icon Threads = IconLoader.getIcon("/debugger/threads.png"); // 16x16
public static class ThreadStates {
public static final Icon Daemon_sign = IconLoader.getIcon("/debugger/threadStates/daemon_sign.png"); // 16x16
public static final Icon EdtBusy = IconLoader.getIcon("/debugger/threadStates/edtBusy.png"); // 16x16
public static final Icon Exception = IconLoader.getIcon("/debugger/threadStates/exception.png"); // 16x16
public static final Icon Idle = IconLoader.getIcon("/debugger/threadStates/idle.png"); // 16x16
public static final Icon IO = IconLoader.getIcon("/debugger/threadStates/io.png"); // 16x16
public static final Icon Locked = IconLoader.getIcon("/debugger/threadStates/locked.png"); // 16x16
public static final Icon Paused = IconLoader.getIcon("/debugger/threadStates/paused.png"); // 16x16
public static final Icon Running = IconLoader.getIcon("/debugger/threadStates/running.png"); // 16x16
public static final Icon Socket = IconLoader.getIcon("/debugger/threadStates/socket.png"); // 16x16
public static final Icon Threaddump = IconLoader.getIcon("/debugger/threadStates/threaddump.png"); // 16x16
}
public static final Icon ThreadSuspended = IconLoader.getIcon("/debugger/threadSuspended.png"); // 16x16
public static final Icon ToolConsole = IconLoader.getIcon("/debugger/toolConsole.png"); // 16x16
public static final Icon Value = IconLoader.getIcon("/debugger/value.png"); // 16x16
public static final Icon ViewBreakpoints = IconLoader.getIcon("/debugger/viewBreakpoints.png"); // 16x16
public static final Icon Watch = IconLoader.getIcon("/debugger/watch.png"); // 16x16
public static final Icon Watches = IconLoader.getIcon("/debugger/watches.png"); // 16x16
public static final Icon WatchLastReturnValue = IconLoader.getIcon("/debugger/watchLastReturnValue.png"); // 16x16
}
public static class Diff {
public static final Icon ApplyNotConflicts = IconLoader.getIcon("/diff/applyNotConflicts.png"); // 16x16
public static final Icon ApplyNotConflictsLeft = IconLoader.getIcon("/diff/applyNotConflictsLeft.png"); // 16x16
public static final Icon ApplyNotConflictsRight = IconLoader.getIcon("/diff/applyNotConflictsRight.png"); // 16x16
public static final Icon Arrow = IconLoader.getIcon("/diff/arrow.png"); // 11x11
public static final Icon ArrowLeftDown = IconLoader.getIcon("/diff/arrowLeftDown.png"); // 11x11
public static final Icon ArrowRight = IconLoader.getIcon("/diff/arrowRight.png"); // 11x11
public static final Icon ArrowRightDown = IconLoader.getIcon("/diff/arrowRightDown.png"); // 11x11
public static final Icon BranchDiff = IconLoader.getIcon("/diff/branchDiff.png"); // 16x16
public static final Icon CurrentLine = IconLoader.getIcon("/diff/currentLine.png"); // 16x16
public static final Icon Diff = IconLoader.getIcon("/diff/Diff.png"); // 16x16
public static final Icon LeftDiff = IconLoader.getIcon("/diff/leftDiff.png"); // 16x16
public static final Icon Remove = IconLoader.getIcon("/diff/remove.png"); // 11x11
public static final Icon RightDiff = IconLoader.getIcon("/diff/rightDiff.png"); // 16x16
}
public static class Duplicates {
public static final Icon SendToTheLeft = IconLoader.getIcon("/duplicates/sendToTheLeft.png"); // 16x16
public static final Icon SendToTheLeftGrayed = IconLoader.getIcon("/duplicates/sendToTheLeftGrayed.png"); // 16x16
public static final Icon SendToTheRight = IconLoader.getIcon("/duplicates/sendToTheRight.png"); // 16x16
public static final Icon SendToTheRightGrayed = IconLoader.getIcon("/duplicates/sendToTheRightGrayed.png"); // 16x16
}
public static class FileTypes {
public static final Icon Any_type = IconLoader.getIcon("/fileTypes/any_type.png"); // 16x16
public static final Icon Archive = IconLoader.getIcon("/fileTypes/archive.png"); // 16x16
public static final Icon AS = IconLoader.getIcon("/fileTypes/as.png"); // 16x16
public static final Icon Aspectj = IconLoader.getIcon("/fileTypes/aspectj.png"); // 16x16
public static final Icon Config = IconLoader.getIcon("/fileTypes/config.png"); // 16x16
public static final Icon Css = IconLoader.getIcon("/fileTypes/css.png"); // 16x16
public static final Icon Custom = IconLoader.getIcon("/fileTypes/custom.png"); // 16x16
public static final Icon Diagram = IconLoader.getIcon("/fileTypes/diagram.png"); // 16x16
public static final Icon Dtd = IconLoader.getIcon("/fileTypes/dtd.png"); // 16x16
public static final Icon Facelets = IconLoader.getIcon("/fileTypes/facelets.png"); // 16x16
public static final Icon FacesConfig = IconLoader.getIcon("/fileTypes/facesConfig.png"); // 16x16
public static final Icon Htaccess = IconLoader.getIcon("/fileTypes/htaccess.png"); // 16x16
public static final Icon Html = IconLoader.getIcon("/fileTypes/html.png"); // 16x16
public static final Icon Idl = IconLoader.getIcon("/fileTypes/idl.png"); // 16x16
public static final Icon Java = IconLoader.getIcon("/fileTypes/java.png"); // 16x16
public static final Icon JavaClass = IconLoader.getIcon("/fileTypes/javaClass.png"); // 16x16
public static final Icon JavaOutsideSource = IconLoader.getIcon("/fileTypes/javaOutsideSource.png"); // 16x16
public static final Icon JavaScript = IconLoader.getIcon("/fileTypes/javaScript.png"); // 16x16
public static final Icon Json = IconLoader.getIcon("/fileTypes/json.png"); // 16x16
public static final Icon Jsp = IconLoader.getIcon("/fileTypes/jsp.png"); // 16x16
public static final Icon Jspx = IconLoader.getIcon("/fileTypes/jspx.png"); // 16x16
public static final Icon Manifest = IconLoader.getIcon("/fileTypes/manifest.png"); // 16x16
public static final Icon Properties = IconLoader.getIcon("/fileTypes/properties.png"); // 16x16
public static final Icon Text = IconLoader.getIcon("/fileTypes/text.png"); // 16x16
public static final Icon TypeScript = IconLoader.getIcon("/fileTypes/typeScript.png"); // 16x16
public static final Icon UiForm = IconLoader.getIcon("/fileTypes/uiForm.png"); // 16x16
public static final Icon Unknown = IconLoader.getIcon("/fileTypes/unknown.png"); // 16x16
public static final Icon WsdlFile = IconLoader.getIcon("/fileTypes/wsdlFile.png"); // 16x16
public static final Icon Xhtml = IconLoader.getIcon("/fileTypes/xhtml.png"); // 16x16
public static final Icon Xml = IconLoader.getIcon("/fileTypes/xml.png"); // 16x16
public static final Icon XsdFile = IconLoader.getIcon("/fileTypes/xsdFile.png"); // 16x16
}
public static final Icon Frame_background = IconLoader.getIcon("/frame_background.png"); // 256x256
public static class General {
public static final Icon Add = IconLoader.getIcon("/general/add.png"); // 16x16
public static final Icon AddFavoritesList = IconLoader.getIcon("/general/addFavoritesList.png"); // 16x16
public static final Icon AddJdk = IconLoader.getIcon("/general/addJdk.png"); // 16x16
public static final Icon ArrowDown = IconLoader.getIcon("/general/arrowDown.png"); // 7x6
public static final Icon AutohideOff = IconLoader.getIcon("/general/autohideOff.png"); // 14x14
public static final Icon AutohideOffInactive = IconLoader.getIcon("/general/autohideOffInactive.png"); // 14x14
public static final Icon AutohideOffPressed = IconLoader.getIcon("/general/autohideOffPressed.png"); // 22x20
public static final Icon AutoscrollFromSource = IconLoader.getIcon("/general/autoscrollFromSource.png"); // 16x16
public static final Icon AutoscrollToSource = IconLoader.getIcon("/general/autoscrollToSource.png"); // 16x16
public static final Icon Balloon = IconLoader.getIcon("/general/balloon.png"); // 16x16
public static final Icon BalloonClose = IconLoader.getIcon("/general/balloonClose.png"); // 32x32
public static final Icon BalloonError = IconLoader.getIcon("/general/balloonError.png"); // 16x16
public static final Icon BalloonInformation = IconLoader.getIcon("/general/balloonInformation.png"); // 16x16
public static final Icon BalloonWarning = IconLoader.getIcon("/general/balloonWarning.png"); // 16x16
public static final Icon Bullet = IconLoader.getIcon("/general/bullet.png"); // 16x16
public static final Icon CollapseAll = IconLoader.getIcon("/general/collapseAll.png"); // 11x16
public static final Icon CollapseAllHover = IconLoader.getIcon("/general/collapseAllHover.png"); // 11x16
public static final Icon Combo = IconLoader.getIcon("/general/combo.png"); // 16x16
public static final Icon Combo2 = IconLoader.getIcon("/general/combo2.png"); // 16x16
public static final Icon Combo3 = IconLoader.getIcon("/general/combo3.png"); // 16x16
public static final Icon ComboArrow = IconLoader.getIcon("/general/comboArrow.png"); // 16x16
public static final Icon ComboArrowDown = IconLoader.getIcon("/general/comboArrowDown.png"); // 9x5
public static final Icon ComboArrowLeft = IconLoader.getIcon("/general/comboArrowLeft.png"); // 5x9
public static final Icon ComboArrowLeftPassive = IconLoader.getIcon("/general/comboArrowLeftPassive.png"); // 5x9
public static final Icon ComboArrowRight = IconLoader.getIcon("/general/comboArrowRight.png"); // 5x9
public static final Icon ComboArrowRightPassive = IconLoader.getIcon("/general/comboArrowRightPassive.png"); // 5x9
public static final Icon ComboBoxButtonArrow = IconLoader.getIcon("/general/comboBoxButtonArrow.png"); // 16x16
public static final Icon ComboUpPassive = IconLoader.getIcon("/general/comboUpPassive.png"); // 16x16
public static final Icon ConfigurableDefault = IconLoader.getIcon("/general/configurableDefault.png"); // 32x32
public static final Icon Configure = IconLoader.getIcon("/general/Configure.png"); // 32x32
public static final Icon CreateNewProject = IconLoader.getIcon("/general/createNewProject.png"); // 32x32
public static final Icon CreateNewProjectfromExistingFiles = IconLoader.getIcon("/general/CreateNewProjectfromExistingFiles.png"); // 32x32
public static final Icon Debug = IconLoader.getIcon("/general/debug.png"); // 16x16
public static final Icon DefaultKeymap = IconLoader.getIcon("/general/defaultKeymap.png"); // 32x32
public static final Icon Divider = IconLoader.getIcon("/general/divider.png"); // 2x19
public static final Icon DownloadPlugin = IconLoader.getIcon("/general/downloadPlugin.png"); // 16x16
public static final Icon Dropdown = IconLoader.getIcon("/general/dropdown.png"); // 16x16
public static final Icon EditColors = IconLoader.getIcon("/general/editColors.png"); // 16x16
public static final Icon EditItemInSection = IconLoader.getIcon("/general/editItemInSection.png"); // 16x16
public static final Icon Ellipsis = IconLoader.getIcon("/general/ellipsis.png"); // 9x9
public static final Icon Error = IconLoader.getIcon("/general/error.png"); // 16x16
public static final Icon ErrorDialog = IconLoader.getIcon("/general/errorDialog.png"); // 32x32
public static final Icon ErrorsInProgress = IconLoader.getIcon("/general/errorsInProgress.png"); // 12x12
public static final Icon ExclMark = IconLoader.getIcon("/general/exclMark.png"); // 16x16
public static final Icon ExpandAll = IconLoader.getIcon("/general/expandAll.png"); // 11x16
public static final Icon ExpandAllHover = IconLoader.getIcon("/general/expandAllHover.png"); // 11x16
public static final Icon ExportSettings = IconLoader.getIcon("/general/ExportSettings.png"); // 32x32
public static final Icon ExternalTools = IconLoader.getIcon("/general/externalTools.png"); // 32x32
public static final Icon ExternalToolsSmall = IconLoader.getIcon("/general/externalToolsSmall.png"); // 16x16
public static final Icon Filter = IconLoader.getIcon("/general/filter.png"); // 16x16
public static final Icon Floating = IconLoader.getIcon("/general/floating.png"); // 14x14
public static final Icon Gear = IconLoader.getIcon("/general/gear.png"); // 21x16
public static final Icon GearHover = IconLoader.getIcon("/general/gearHover.png"); // 21x16
public static final Icon GearPlain = IconLoader.getIcon("/general/gearPlain.png"); // 16x16
public static final Icon GetProjectfromVCS = IconLoader.getIcon("/general/getProjectfromVCS.png"); // 32x32
public static final Icon Help = IconLoader.getIcon("/general/help.png"); // 10x10
public static final Icon Help_small = IconLoader.getIcon("/general/help_small.png"); // 16x16
public static final Icon HideDown = IconLoader.getIcon("/general/hideDown.png"); // 16x16
public static final Icon HideDownHover = IconLoader.getIcon("/general/hideDownHover.png"); // 16x16
public static final Icon HideDownPart = IconLoader.getIcon("/general/hideDownPart.png"); // 16x16
public static final Icon HideDownPartHover = IconLoader.getIcon("/general/hideDownPartHover.png"); // 16x16
public static final Icon HideLeft = IconLoader.getIcon("/general/hideLeft.png"); // 16x16
public static final Icon HideLeftHover = IconLoader.getIcon("/general/hideLeftHover.png"); // 16x16
public static final Icon HideLeftPart = IconLoader.getIcon("/general/hideLeftPart.png"); // 16x16
public static final Icon HideLeftPartHover = IconLoader.getIcon("/general/hideLeftPartHover.png"); // 16x16
public static final Icon HideRight = IconLoader.getIcon("/general/hideRight.png"); // 16x16
public static final Icon HideRightHover = IconLoader.getIcon("/general/hideRightHover.png"); // 16x16
public static final Icon HideRightPart = IconLoader.getIcon("/general/hideRightPart.png"); // 16x16
public static final Icon HideRightPartHover = IconLoader.getIcon("/general/hideRightPartHover.png"); // 16x16
public static final Icon HideToolWindow = IconLoader.getIcon("/general/hideToolWindow.png"); // 14x14
public static final Icon HideToolWindowInactive = IconLoader.getIcon("/general/hideToolWindowInactive.png"); // 14x14
public static final Icon HideWarnings = IconLoader.getIcon("/general/hideWarnings.png"); // 16x16
public static final Icon IjLogo = IconLoader.getIcon("/general/ijLogo.png"); // 16x16
public static final Icon ImplementingMethod = IconLoader.getIcon("/general/implementingMethod.png"); // 10x14
public static final Icon ImportProject = IconLoader.getIcon("/general/importProject.png"); // 32x32
public static final Icon ImportSettings = IconLoader.getIcon("/general/ImportSettings.png"); // 32x32
public static final Icon Information = IconLoader.getIcon("/general/information.png"); // 16x16
public static final Icon InformationDialog = IconLoader.getIcon("/general/informationDialog.png"); // 32x32
public static final Icon InheritedMethod = IconLoader.getIcon("/general/inheritedMethod.png"); // 11x14
public static final Icon InspectionsError = IconLoader.getIcon("/general/inspectionsError.png"); // 14x14
public static final Icon InspectionsEye = IconLoader.getIcon("/general/inspectionsEye.png"); // 14x14
public static final Icon InspectionsOff = IconLoader.getIcon("/general/inspectionsOff.png"); // 16x16
public static final Icon InspectionsOK = IconLoader.getIcon("/general/inspectionsOK.png"); // 14x14
public static final Icon InspectionsPause = IconLoader.getIcon("/general/inspectionsPause.png"); // 14x14
public static final Icon InspectionsTrafficOff = IconLoader.getIcon("/general/inspectionsTrafficOff.png"); // 14x14
public static final Icon InspectionsTypos = IconLoader.getIcon("/general/inspectionsTypos.png"); // 14x14
public static final Icon Jdk = IconLoader.getIcon("/general/jdk.png"); // 16x16
public static final Icon KeyboardShortcut = IconLoader.getIcon("/general/keyboardShortcut.png"); // 13x13
public static final Icon Keymap = IconLoader.getIcon("/general/keymap.png"); // 32x32
public static final Icon Locate = IconLoader.getIcon("/general/locate.png"); // 14x16
public static final Icon LocateHover = IconLoader.getIcon("/general/locateHover.png"); // 14x16
public static final Icon MacCorner = IconLoader.getIcon("/general/macCorner.png"); // 16x16
public static final Icon Mdot_empty = IconLoader.getIcon("/general/mdot-empty.png"); // 8x8
public static final Icon Mdot_white = IconLoader.getIcon("/general/mdot-white.png"); // 8x8
public static final Icon Mdot = IconLoader.getIcon("/general/mdot.png"); // 8x8
public static final Icon MessageHistory = IconLoader.getIcon("/general/messageHistory.png"); // 16x16
public static final Icon Modified = IconLoader.getIcon("/general/modified.png"); // 24x16
public static final Icon MoreTabs = IconLoader.getIcon("/general/moreTabs.png"); // 16x16
public static final Icon Mouse = IconLoader.getIcon("/general/mouse.png"); // 32x32
public static final Icon MouseShortcut = IconLoader.getIcon("/general/mouseShortcut.png"); // 13x13
public static final Icon NotificationError = IconLoader.getIcon("/general/notificationError.png"); // 24x24
public static final Icon NotificationInfo = IconLoader.getIcon("/general/notificationInfo.png"); // 24x24
public static final Icon NotificationWarning = IconLoader.getIcon("/general/notificationWarning.png"); // 24x24
public static final Icon OpenProject = IconLoader.getIcon("/general/openProject.png"); // 32x32
public static final Icon OverridenMethod = IconLoader.getIcon("/general/overridenMethod.png"); // 10x14
public static final Icon OverridingMethod = IconLoader.getIcon("/general/overridingMethod.png"); // 10x14
public static final Icon PackagesTab = IconLoader.getIcon("/general/packagesTab.png"); // 16x16
public static final Icon PasswordLock = IconLoader.getIcon("/general/passwordLock.png"); // 64x64
public static final Icon PathVariables = IconLoader.getIcon("/general/pathVariables.png"); // 32x32
public static final Icon Pin_tab = IconLoader.getIcon("/general/pin_tab.png"); // 16x16
public static final Icon PluginManager = IconLoader.getIcon("/general/pluginManager.png"); // 32x32
public static final Icon Progress = IconLoader.getIcon("/general/progress.png"); // 8x10
public static final Icon ProjectConfigurable = IconLoader.getIcon("/general/projectConfigurable.png"); // 9x9
public static final Icon ProjectConfigurableBanner = IconLoader.getIcon("/general/projectConfigurableBanner.png"); // 9x9
public static final Icon ProjectConfigurableSelected = IconLoader.getIcon("/general/projectConfigurableSelected.png"); // 9x9
public static final Icon ProjectSettings = IconLoader.getIcon("/general/projectSettings.png"); // 16x16
public static final Icon ProjectStructure = IconLoader.getIcon("/general/projectStructure.png"); // 16x16
public static final Icon ProjectTab = IconLoader.getIcon("/general/projectTab.png"); // 16x16
public static final Icon QuestionDialog = IconLoader.getIcon("/general/questionDialog.png"); // 32x32
public static final Icon ReadHelp = IconLoader.getIcon("/general/readHelp.png"); // 32x32
public static final Icon Remove = IconLoader.getIcon("/general/remove.png"); // 16x16
public static final Icon Reset = IconLoader.getIcon("/general/reset.png"); // 16x16
public static final Icon Run = IconLoader.getIcon("/general/run.png"); // 7x10
public static final Icon RunWithCoverage = IconLoader.getIcon("/general/runWithCoverage.png"); // 16x16
public static final Icon SafeMode = IconLoader.getIcon("/general/safeMode.png"); // 13x13
public static final Icon SearchEverywhereGear = IconLoader.getIcon("/general/searchEverywhereGear.png"); // 16x16
public static final Icon SecondaryGroup = IconLoader.getIcon("/general/secondaryGroup.png"); // 16x16
public static final Icon SeparatorH = IconLoader.getIcon("/general/separatorH.png"); // 17x11
public static final Icon Settings = IconLoader.getIcon("/general/settings.png"); // 16x16
public static final Icon Show_to_implement = IconLoader.getIcon("/general/show_to_implement.png"); // 16x16
public static final Icon Show_to_override = IconLoader.getIcon("/general/show_to_override.png"); // 16x16
public static final Icon SmallConfigurableVcs = IconLoader.getIcon("/general/smallConfigurableVcs.png"); // 16x16
public static final Icon SplitCenterH = IconLoader.getIcon("/general/splitCenterH.png"); // 7x7
public static final Icon SplitCenterV = IconLoader.getIcon("/general/splitCenterV.png"); // 6x7
public static final Icon SplitDown = IconLoader.getIcon("/general/splitDown.png"); // 7x7
public static final Icon SplitGlueH = IconLoader.getIcon("/general/splitGlueH.png"); // 6x17
public static final Icon SplitGlueV = IconLoader.getIcon("/general/splitGlueV.png"); // 17x6
public static final Icon SplitLeft = IconLoader.getIcon("/general/splitLeft.png"); // 7x7
public static final Icon SplitRight = IconLoader.getIcon("/general/splitRight.png"); // 7x7
public static final Icon SplitUp = IconLoader.getIcon("/general/splitUp.png"); // 7x7
public static final Icon Tab_white_center = IconLoader.getIcon("/general/tab-white-center.png"); // 1x17
public static final Icon Tab_white_left = IconLoader.getIcon("/general/tab-white-left.png"); // 4x17
public static final Icon Tab_white_right = IconLoader.getIcon("/general/tab-white-right.png"); // 4x17
public static final Icon Tab_grey_bckgrnd = IconLoader.getIcon("/general/tab_grey_bckgrnd.png"); // 1x17
public static final Icon Tab_grey_left = IconLoader.getIcon("/general/tab_grey_left.png"); // 4x17
public static final Icon Tab_grey_left_inner = IconLoader.getIcon("/general/tab_grey_left_inner.png"); // 4x17
public static final Icon Tab_grey_right = IconLoader.getIcon("/general/tab_grey_right.png"); // 4x17
public static final Icon Tab_grey_right_inner = IconLoader.getIcon("/general/tab_grey_right_inner.png"); // 4x17
public static final Icon TbHidden = IconLoader.getIcon("/general/tbHidden.png"); // 16x16
public static final Icon TbShown = IconLoader.getIcon("/general/tbShown.png"); // 16x16
public static final Icon TemplateProjectSettings = IconLoader.getIcon("/general/TemplateProjectSettings.png"); // 32x32
public static final Icon TemplateProjectStructure = IconLoader.getIcon("/general/TemplateProjectStructure.png"); // 32x32
public static final Icon Tip = IconLoader.getIcon("/general/tip.png"); // 32x32
public static final Icon TodoDefault = IconLoader.getIcon("/general/todoDefault.png"); // 12x12
public static final Icon TodoImportant = IconLoader.getIcon("/general/todoImportant.png"); // 12x12
public static final Icon TodoQuestion = IconLoader.getIcon("/general/todoQuestion.png"); // 12x12
public static final Icon UninstallPlugin = IconLoader.getIcon("/general/uninstallPlugin.png"); // 16x16
public static final Icon Warning = IconLoader.getIcon("/general/warning.png"); // 16x16
public static final Icon WarningDecorator = IconLoader.getIcon("/general/warningDecorator.png"); // 16x16
public static final Icon WarningDialog = IconLoader.getIcon("/general/warningDialog.png"); // 32x32
public static final Icon Web = IconLoader.getIcon("/general/web.png"); // 13x13
public static final Icon WebSettings = IconLoader.getIcon("/general/webSettings.png"); // 16x16
}
public static class Graph {
public static final Icon ActualZoom = IconLoader.getIcon("/graph/actualZoom.png"); // 16x16
public static final Icon Export = IconLoader.getIcon("/graph/export.png"); // 16x16
public static final Icon FitContent = IconLoader.getIcon("/graph/fitContent.png"); // 16x16
public static final Icon Grid = IconLoader.getIcon("/graph/grid.png"); // 16x16
public static final Icon Layout = IconLoader.getIcon("/graph/layout.png"); // 16x16
public static final Icon NodeSelectionMode = IconLoader.getIcon("/graph/nodeSelectionMode.png"); // 16x16
public static final Icon Print = IconLoader.getIcon("/graph/print.png"); // 16x16
public static final Icon PrintPreview = IconLoader.getIcon("/graph/printPreview.png"); // 16x16
public static final Icon SnapToGrid = IconLoader.getIcon("/graph/snapToGrid.png"); // 16x16
public static final Icon ZoomIn = IconLoader.getIcon("/graph/zoomIn.png"); // 16x16
public static final Icon ZoomOut = IconLoader.getIcon("/graph/zoomOut.png"); // 16x16
}
public static class Gutter {
public static final Icon Colors = IconLoader.getIcon("/gutter/colors.png"); // 12x12
public static final Icon ExtAnnotation = IconLoader.getIcon("/gutter/extAnnotation.png"); // 12x12
public static final Icon ImplementedMethod = IconLoader.getIcon("/gutter/implementedMethod.png"); // 12x12
public static final Icon ImplementingMethod = IconLoader.getIcon("/gutter/implementingMethod.png"); // 12x12
public static final Icon OverridenMethod = IconLoader.getIcon("/gutter/overridenMethod.png"); // 12x12
public static final Icon OverridingMethod = IconLoader.getIcon("/gutter/overridingMethod.png"); // 12x12
public static final Icon RecursiveMethod = IconLoader.getIcon("/gutter/recursiveMethod.png"); // 12x12
public static final Icon Unique = IconLoader.getIcon("/gutter/unique.png"); // 8x8
}
public static class Hierarchy {
public static final Icon Base = IconLoader.getIcon("/hierarchy/base.png"); // 16x16
public static final Icon Callee = IconLoader.getIcon("/hierarchy/callee.png"); // 16x16
public static final Icon Caller = IconLoader.getIcon("/hierarchy/caller.png"); // 16x16
public static final Icon Class = IconLoader.getIcon("/hierarchy/class.png"); // 16x16
public static final Icon MethodDefined = IconLoader.getIcon("/hierarchy/methodDefined.png"); // 9x9
public static final Icon MethodNotDefined = IconLoader.getIcon("/hierarchy/methodNotDefined.png"); // 8x8
public static final Icon ShouldDefineMethod = IconLoader.getIcon("/hierarchy/shouldDefineMethod.png"); // 9x9
public static final Icon Subtypes = IconLoader.getIcon("/hierarchy/subtypes.png"); // 16x16
public static final Icon Supertypes = IconLoader.getIcon("/hierarchy/supertypes.png"); // 16x16
}
public static final Icon Icon = IconLoader.getIcon("/icon.png"); // 32x32
public static final Icon Icon_128 = IconLoader.getIcon("/icon_128.png"); // 128x128
public static final Icon Icon_CE = IconLoader.getIcon("/icon_CE.png"); // 32x32
public static final Icon Icon_CE_128 = IconLoader.getIcon("/icon_CE_128.png"); // 128x128
public static final Icon Icon_CEsmall = IconLoader.getIcon("/icon_CEsmall.png"); // 16x16
public static final Icon Icon_small = IconLoader.getIcon("/icon_small.png"); // 16x16
public static class Icons {
public static class Ide {
public static final Icon NextStep = IconLoader.getIcon("/icons/ide/nextStep.png"); // 12x12
public static final Icon NextStepGrayed = IconLoader.getIcon("/icons/ide/nextStepGrayed.png"); // 12x12
public static final Icon NextStepInverted = IconLoader.getIcon("/icons/ide/nextStepInverted.png"); // 12x12
public static final Icon SpeedSearchPrompt = IconLoader.getIcon("/icons/ide/speedSearchPrompt.png"); // 16x16
}
}
public static class Ide {
public static class Dnd {
public static final Icon Bottom = IconLoader.getIcon("/ide/dnd/bottom.png"); // 16x16
public static final Icon Left = IconLoader.getIcon("/ide/dnd/left.png"); // 16x16
public static final Icon Right = IconLoader.getIcon("/ide/dnd/right.png"); // 16x16
public static final Icon Top = IconLoader.getIcon("/ide/dnd/top.png"); // 16x16
}
public static final Icon EmptyFatalError = IconLoader.getIcon("/ide/emptyFatalError.png"); // 16x16
public static final Icon Error = IconLoader.getIcon("/ide/error.png"); // 16x16
public static final Icon Error_notifications = IconLoader.getIcon("/ide/error_notifications.png"); // 16x16
public static final Icon ErrorPoint = IconLoader.getIcon("/ide/errorPoint.png"); // 6x6
public static final Icon FatalError_read = IconLoader.getIcon("/ide/fatalError-read.png"); // 16x16
public static final Icon FatalError = IconLoader.getIcon("/ide/fatalError.png"); // 16x16
public static final Icon HectorNo = IconLoader.getIcon("/ide/hectorNo.png"); // 16x16
public static final Icon HectorOff = IconLoader.getIcon("/ide/hectorOff.png"); // 16x16
public static final Icon HectorOn = IconLoader.getIcon("/ide/hectorOn.png"); // 16x16
public static final Icon HectorSyntax = IconLoader.getIcon("/ide/hectorSyntax.png"); // 16x16
public static final Icon IncomingChangesOff = IconLoader.getIcon("/ide/incomingChangesOff.png"); // 16x16
public static final Icon IncomingChangesOn = IconLoader.getIcon("/ide/incomingChangesOn.png"); // 16x16
public static final Icon Info_notifications = IconLoader.getIcon("/ide/info_notifications.png"); // 16x16
public static final Icon Link = IconLoader.getIcon("/ide/link.png"); // 12x12
public static final Icon LocalScope = IconLoader.getIcon("/ide/localScope.png"); // 16x16
public static final Icon LookupAlphanumeric = IconLoader.getIcon("/ide/lookupAlphanumeric.png"); // 12x12
public static final Icon LookupRelevance = IconLoader.getIcon("/ide/lookupRelevance.png"); // 12x12
public static class Macro {
public static final Icon Recording_1 = IconLoader.getIcon("/ide/macro/recording_1.png"); // 16x16
public static final Icon Recording_2 = IconLoader.getIcon("/ide/macro/recording_2.png"); // 16x16
public static final Icon Recording_3 = IconLoader.getIcon("/ide/macro/recording_3.png"); // 16x16
public static final Icon Recording_4 = IconLoader.getIcon("/ide/macro/recording_4.png"); // 16x16
public static final Icon Recording_stop = IconLoader.getIcon("/ide/macro/recording_stop.png"); // 16x16
}
public static final Icon NoNotifications13 = IconLoader.getIcon("/ide/noNotifications13.png"); // 13x13
public static final Icon Notifications = IconLoader.getIcon("/ide/notifications.png"); // 16x16
public static final Icon OutgoingChangesOn = IconLoader.getIcon("/ide/outgoingChangesOn.png"); // 16x16
public static final Icon Pipette = IconLoader.getIcon("/ide/pipette.png"); // 16x16
public static final Icon Pipette_rollover = IconLoader.getIcon("/ide/pipette_rollover.png"); // 16x16
public static final Icon Rating = IconLoader.getIcon("/ide/rating.png"); // 11x11
public static final Icon Rating1 = IconLoader.getIcon("/ide/rating1.png"); // 11x11
public static final Icon Rating2 = IconLoader.getIcon("/ide/rating2.png"); // 11x11
public static final Icon Rating3 = IconLoader.getIcon("/ide/rating3.png"); // 11x11
public static final Icon Rating4 = IconLoader.getIcon("/ide/rating4.png"); // 11x11
public static final Icon Readonly = IconLoader.getIcon("/ide/readonly.png"); // 16x16
public static final Icon Readwrite = IconLoader.getIcon("/ide/readwrite.png"); // 16x16
public static class Shadow {
public static final Icon Bottom_left = IconLoader.getIcon("/ide/shadow/bottom-left.png"); // 70x70
public static final Icon Bottom_right = IconLoader.getIcon("/ide/shadow/bottom-right.png"); // 70x70
public static final Icon Bottom = IconLoader.getIcon("/ide/shadow/bottom.png"); // 1x49
public static final Icon Left = IconLoader.getIcon("/ide/shadow/left.png"); // 35x1
public static class Popup {
public static final Icon Bottom_left = IconLoader.getIcon("/ide/shadow/popup/bottom-left.png"); // 20x20
public static final Icon Bottom_right = IconLoader.getIcon("/ide/shadow/popup/bottom-right.png"); // 20x20
public static final Icon Bottom = IconLoader.getIcon("/ide/shadow/popup/bottom.png"); // 1x10
public static final Icon Left = IconLoader.getIcon("/ide/shadow/popup/left.png"); // 7x1
public static final Icon Right = IconLoader.getIcon("/ide/shadow/popup/right.png"); // 7x1
public static final Icon Top_left = IconLoader.getIcon("/ide/shadow/popup/top-left.png"); // 14x14
public static final Icon Top_right = IconLoader.getIcon("/ide/shadow/popup/top-right.png"); // 14x14
public static final Icon Top = IconLoader.getIcon("/ide/shadow/popup/top.png"); // 1x4
}
public static final Icon Right = IconLoader.getIcon("/ide/shadow/right.png"); // 35x1
public static final Icon Top_left = IconLoader.getIcon("/ide/shadow/top-left.png"); // 70x70
public static final Icon Top_right = IconLoader.getIcon("/ide/shadow/top-right.png"); // 70x70
public static final Icon Top = IconLoader.getIcon("/ide/shadow/top.png"); // 1x20
}
public static final Icon Statusbar_arrows = IconLoader.getIcon("/ide/statusbar_arrows.png"); // 7x10
public static final Icon UpDown = IconLoader.getIcon("/ide/upDown.png"); // 16x16
public static final Icon Warning_notifications = IconLoader.getIcon("/ide/warning_notifications.png"); // 16x16
}
public static final Icon Idea_logo_background = IconLoader.getIcon("/idea_logo_background.png"); // 500x500
public static final Icon Idea_logo_welcome = IconLoader.getIcon("/idea_logo_welcome.png"); // 100x100
public static class Javaee {
public static final Icon Application_xml = IconLoader.getIcon("/javaee/application_xml.png"); // 16x16
public static final Icon BuildOnFrameDeactivation = IconLoader.getIcon("/javaee/buildOnFrameDeactivation.png"); // 16x16
public static final Icon DataSourceImport = IconLoader.getIcon("/javaee/dataSourceImport.png"); // 16x16
public static final Icon DbSchemaImportBig = IconLoader.getIcon("/javaee/dbSchemaImportBig.png"); // 32x32
public static final Icon Ejb_jar_xml = IconLoader.getIcon("/javaee/ejb-jar_xml.png"); // 16x16
public static final Icon EjbClass = IconLoader.getIcon("/javaee/ejbClass.png"); // 16x16
public static final Icon EjbModule = IconLoader.getIcon("/javaee/ejbModule.png"); // 16x16
public static final Icon EmbeddedAttributeOverlay = IconLoader.getIcon("/javaee/embeddedAttributeOverlay.png"); // 16x16
public static final Icon EntityBean = IconLoader.getIcon("/javaee/entityBean.png"); // 16x16
public static final Icon EntityBeanBig = IconLoader.getIcon("/javaee/entityBeanBig.png"); // 24x24
public static final Icon Home = IconLoader.getIcon("/javaee/home.png"); // 16x16
public static final Icon InheritedAttributeOverlay = IconLoader.getIcon("/javaee/inheritedAttributeOverlay.png"); // 16x16
public static final Icon InterceptorClass = IconLoader.getIcon("/javaee/interceptorClass.png"); // 16x16
public static final Icon InterceptorMethod = IconLoader.getIcon("/javaee/interceptorMethod.png"); // 16x16
public static final Icon JavaeeAppModule = IconLoader.getIcon("/javaee/JavaeeAppModule.png"); // 16x16
public static final Icon JpaFacet = IconLoader.getIcon("/javaee/jpaFacet.png"); // 16x16
public static final Icon Local = IconLoader.getIcon("/javaee/local.png"); // 16x16
public static final Icon LocalHome = IconLoader.getIcon("/javaee/localHome.png"); // 16x16
public static final Icon MessageBean = IconLoader.getIcon("/javaee/messageBean.png"); // 16x16
public static final Icon PersistenceAttribute = IconLoader.getIcon("/javaee/persistenceAttribute.png"); // 16x16
public static final Icon PersistenceEmbeddable = IconLoader.getIcon("/javaee/persistenceEmbeddable.png"); // 16x16
public static final Icon PersistenceEntity = IconLoader.getIcon("/javaee/persistenceEntity.png"); // 16x16
public static final Icon PersistenceEntityListener = IconLoader.getIcon("/javaee/persistenceEntityListener.png"); // 16x16
public static final Icon PersistenceId = IconLoader.getIcon("/javaee/persistenceId.png"); // 16x16
public static final Icon PersistenceIdRelationship = IconLoader.getIcon("/javaee/persistenceIdRelationship.png"); // 16x16
public static final Icon PersistenceMappedSuperclass = IconLoader.getIcon("/javaee/persistenceMappedSuperclass.png"); // 16x16
public static final Icon PersistenceRelationship = IconLoader.getIcon("/javaee/persistenceRelationship.png"); // 16x16
public static final Icon PersistenceUnit = IconLoader.getIcon("/javaee/persistenceUnit.png"); // 16x16
public static final Icon Remote = IconLoader.getIcon("/javaee/remote.png"); // 16x16
public static final Icon SessionBean = IconLoader.getIcon("/javaee/sessionBean.png"); // 16x16
public static final Icon UpdateRunningApplication = IconLoader.getIcon("/javaee/updateRunningApplication.png"); // 16x16
public static final Icon Web_xml = IconLoader.getIcon("/javaee/web_xml.png"); // 16x16
public static final Icon WebModule = IconLoader.getIcon("/javaee/webModule.png"); // 16x16
public static final Icon WebModuleGroup = IconLoader.getIcon("/javaee/webModuleGroup.png"); // 16x16
public static final Icon WebService = IconLoader.getIcon("/javaee/WebService.png"); // 16x16
public static final Icon WebService2 = IconLoader.getIcon("/javaee/WebService2.png"); // 16x16
public static final Icon WebServiceClient = IconLoader.getIcon("/javaee/WebServiceClient.png"); // 16x16
public static final Icon WebServiceClient2 = IconLoader.getIcon("/javaee/WebServiceClient2.png"); // 16x16
}
public static class Json {
public static final Icon Array = IconLoader.getIcon("/json/array.png"); // 16x16
public static final Icon Object = IconLoader.getIcon("/json/object.png"); // 16x16
public static final Icon Property_braces = IconLoader.getIcon("/json/property_braces.png"); // 16x16
public static final Icon Property_brackets = IconLoader.getIcon("/json/property_brackets.png"); // 16x16
}
public static final Icon Logo_welcomeScreen = IconLoader.getIcon("/Logo_welcomeScreen.png"); // 80x80
public static class Mac {
public static final Icon AppIconOk512 = IconLoader.getIcon("/mac/appIconOk512.png"); // 55x55
public static final Icon Text = IconLoader.getIcon("/mac/text.gif"); // 32x32
public static final Icon Tree_white_down_arrow = IconLoader.getIcon("/mac/tree_white_down_arrow.png"); // 11x11
public static final Icon Tree_white_right_arrow = IconLoader.getIcon("/mac/tree_white_right_arrow.png"); // 11x11
public static final Icon YosemiteOptionButtonSelector = IconLoader.getIcon("/mac/yosemiteOptionButtonSelector.png"); // 8x12
}
public static class Modules {
public static final Icon AddContentEntry = IconLoader.getIcon("/modules/addContentEntry.png"); // 16x16
public static final Icon AddExcludedRoot = IconLoader.getIcon("/modules/addExcludedRoot.png"); // 16x16
public static final Icon Annotation = IconLoader.getIcon("/modules/annotation.png"); // 16x16
public static final Icon DeleteContentFolder = IconLoader.getIcon("/modules/deleteContentFolder.png"); // 9x9
public static final Icon DeleteContentFolderRollover = IconLoader.getIcon("/modules/deleteContentFolderRollover.png"); // 9x9
public static final Icon DeleteContentRoot = IconLoader.getIcon("/modules/deleteContentRoot.png"); // 9x9
public static final Icon DeleteContentRootRollover = IconLoader.getIcon("/modules/deleteContentRootRollover.png"); // 9x9
public static final Icon Edit = IconLoader.getIcon("/modules/edit.png"); // 14x14
public static final Icon EditFolder = IconLoader.getIcon("/modules/editFolder.png"); // 16x16
public static final Icon ExcludedGeneratedRoot = IconLoader.getIcon("/modules/excludedGeneratedRoot.png"); // 16x16
public static final Icon ExcludeRoot = IconLoader.getIcon("/modules/excludeRoot.png"); // 16x16
public static final Icon GeneratedFolder = IconLoader.getIcon("/modules/generatedFolder.png"); // 16x16
public static final Icon GeneratedSourceRoot = IconLoader.getIcon("/modules/generatedSourceRoot.png"); // 16x16
public static final Icon GeneratedTestRoot = IconLoader.getIcon("/modules/generatedTestRoot.png"); // 16x16
public static final Icon Library = IconLoader.getIcon("/modules/library.png"); // 16x16
public static final Icon Merge = IconLoader.getIcon("/modules/merge.png"); // 16x16
public static final Icon ModulesNode = IconLoader.getIcon("/modules/modulesNode.png"); // 16x16
public static final Icon Output = IconLoader.getIcon("/modules/output.png"); // 16x16
public static final Icon ResourcesRoot = IconLoader.getIcon("/modules/resourcesRoot.png"); // 16x16
public static final Icon SetPackagePrefix = IconLoader.getIcon("/modules/setPackagePrefix.png"); // 9x9
public static final Icon SetPackagePrefixRollover = IconLoader.getIcon("/modules/setPackagePrefixRollover.png"); // 9x9
public static final Icon SourceFolder = IconLoader.getIcon("/modules/sourceFolder.png"); // 16x16
public static final Icon SourceRoot = IconLoader.getIcon("/modules/sourceRoot.png"); // 16x16
public static final Icon Sources = IconLoader.getIcon("/modules/sources.png"); // 16x16
public static final Icon Split = IconLoader.getIcon("/modules/split.png"); // 16x16
public static final Icon TestResourcesRoot = IconLoader.getIcon("/modules/testResourcesRoot.png"); // 16x16
public static final Icon TestRoot = IconLoader.getIcon("/modules/testRoot.png"); // 16x16
public static final Icon TestSourceFolder = IconLoader.getIcon("/modules/testSourceFolder.png"); // 16x16
public static class Types {
public static final Icon EjbModule = IconLoader.getIcon("/modules/types/ejbModule.png"); // 24x24
public static final Icon EmptyProjectType = IconLoader.getIcon("/modules/types/emptyProjectType.png"); // 24x24
public static final Icon JavaeeAppModule = IconLoader.getIcon("/modules/types/JavaeeAppModule.png"); // 24x24
public static final Icon JavaModule = IconLoader.getIcon("/modules/types/javaModule.png"); // 24x24
public static final Icon PluginModule = IconLoader.getIcon("/modules/types/pluginModule.png"); // 24x24
public static final Icon UserDefined = IconLoader.getIcon("/modules/types/userDefined.png"); // 16x16
public static final Icon WebModule = IconLoader.getIcon("/modules/types/webModule.png"); // 24x24
}
public static final Icon UnmarkWebroot = IconLoader.getIcon("/modules/unmarkWebroot.png"); // 16x16
public static final Icon WebRoot = IconLoader.getIcon("/modules/webRoot.png"); // 16x16
}
public static class Nodes {
public static final Icon AbstractClass = IconLoader.getIcon("/nodes/abstractClass.png"); // 16x16
public static final Icon AbstractException = IconLoader.getIcon("/nodes/abstractException.png"); // 16x16
public static final Icon AbstractMethod = IconLoader.getIcon("/nodes/abstractMethod.png"); // 16x16
public static final Icon Advice = IconLoader.getIcon("/nodes/advice.png"); // 16x16
public static final Icon Annotationtype = IconLoader.getIcon("/nodes/annotationtype.png"); // 16x16
public static final Icon AnonymousClass = IconLoader.getIcon("/nodes/anonymousClass.png"); // 16x16
public static final Icon Artifact = IconLoader.getIcon("/nodes/artifact.png"); // 16x16
public static final Icon Aspect = IconLoader.getIcon("/nodes/aspect.png"); // 14x14
public static final Icon C_plocal = IconLoader.getIcon("/nodes/c_plocal.png"); // 16x16
public static final Icon C_private = IconLoader.getIcon("/nodes/c_private.png"); // 16x16
public static final Icon C_protected = IconLoader.getIcon("/nodes/c_protected.png"); // 16x16
public static final Icon C_public = IconLoader.getIcon("/nodes/c_public.png"); // 16x16
public static final Icon Class = IconLoader.getIcon("/nodes/class.png"); // 16x16
public static final Icon ClassInitializer = IconLoader.getIcon("/nodes/classInitializer.png"); // 16x16
public static final Icon CollapseNode = IconLoader.getIcon("/nodes/collapseNode.png"); // 9x9
public static final Icon CompiledClassesFolder = IconLoader.getIcon("/nodes/compiledClassesFolder.png"); // 16x16
public static final Icon CopyOfFolder = IconLoader.getIcon("/nodes/copyOfFolder.png"); // 16x16
public static final Icon CustomRegion = IconLoader.getIcon("/nodes/customRegion.png"); // 16x16
public static final Icon Cvs_global = IconLoader.getIcon("/nodes/cvs_global.png"); // 16x16
public static final Icon Cvs_roots = IconLoader.getIcon("/nodes/cvs_roots.png"); // 16x16
public static final Icon DataColumn = IconLoader.getIcon("/nodes/dataColumn.png"); // 16x16
public static final Icon DataSchema = IconLoader.getIcon("/nodes/dataSchema.png"); // 16x16
public static final Icon DataSource = IconLoader.getIcon("/nodes/DataSource.png"); // 16x16
public static final Icon DataTables = IconLoader.getIcon("/nodes/DataTables.png"); // 16x16
public static final Icon DataView = IconLoader.getIcon("/nodes/dataView.png"); // 16x16
public static final Icon Deploy = IconLoader.getIcon("/nodes/deploy.png"); // 16x16
public static final Icon Desktop = IconLoader.getIcon("/nodes/desktop.png"); // 16x16
public static final Icon Ejb = IconLoader.getIcon("/nodes/ejb.png"); // 16x16
public static final Icon EjbBusinessMethod = IconLoader.getIcon("/nodes/ejbBusinessMethod.png"); // 16x16
public static final Icon EjbCmpField = IconLoader.getIcon("/nodes/ejbCmpField.png"); // 16x16
public static final Icon EjbCmrField = IconLoader.getIcon("/nodes/ejbCmrField.png"); // 16x16
public static final Icon EjbCreateMethod = IconLoader.getIcon("/nodes/ejbCreateMethod.png"); // 16x16
public static final Icon EjbFinderMethod = IconLoader.getIcon("/nodes/ejbFinderMethod.png"); // 16x16
public static final Icon EjbPrimaryKeyClass = IconLoader.getIcon("/nodes/ejbPrimaryKeyClass.png"); // 16x16
public static final Icon EjbReference = IconLoader.getIcon("/nodes/ejbReference.png"); // 16x16
public static final Icon EmptyNode = IconLoader.getIcon("/nodes/emptyNode.png"); // 18x18
public static final Icon EnterpriseProject = IconLoader.getIcon("/nodes/enterpriseProject.png"); // 16x16
public static final Icon EntryPoints = IconLoader.getIcon("/nodes/entryPoints.png"); // 16x16
public static final Icon Enum = IconLoader.getIcon("/nodes/enum.png"); // 16x16
public static final Icon ErrorIntroduction = IconLoader.getIcon("/nodes/errorIntroduction.png"); // 16x16
public static final Icon ErrorMark = IconLoader.getIcon("/nodes/errorMark.png"); // 16x16
public static final Icon ExceptionClass = IconLoader.getIcon("/nodes/exceptionClass.png"); // 16x16
public static final Icon ExcludedFromCompile = IconLoader.getIcon("/nodes/excludedFromCompile.png"); // 16x16
public static final Icon ExpandNode = IconLoader.getIcon("/nodes/expandNode.png"); // 9x9
public static final Icon ExtractedFolder = IconLoader.getIcon("/nodes/extractedFolder.png"); // 16x16
public static final Icon Field = IconLoader.getIcon("/nodes/field.png"); // 16x16
public static final Icon FieldPK = IconLoader.getIcon("/nodes/fieldPK.png"); // 16x16
public static final Icon FinalMark = IconLoader.getIcon("/nodes/finalMark.png"); // 16x16
public static final Icon Folder = IconLoader.getIcon("/nodes/folder.png"); // 16x16
public static final Icon Function = IconLoader.getIcon("/nodes/function.png"); // 16x16
public static final Icon HomeFolder = IconLoader.getIcon("/nodes/homeFolder.png"); // 16x16
public static final Icon IdeaModule = IconLoader.getIcon("/nodes/ideaModule.png"); // 16x16
public static final Icon IdeaProject = IconLoader.getIcon("/nodes/ideaProject.png"); // 16x16
public static final Icon IdeaWorkspace = IconLoader.getIcon("/nodes/ideaWorkspace.png"); // 16x16
public static final Icon InspectionResults = IconLoader.getIcon("/nodes/inspectionResults.png"); // 16x16
public static final Icon Interface = IconLoader.getIcon("/nodes/interface.png"); // 16x16
public static final Icon J2eeParameter = IconLoader.getIcon("/nodes/j2eeParameter.png"); // 16x16
public static final Icon JarDirectory = IconLoader.getIcon("/nodes/jarDirectory.png"); // 16x16
public static final Icon JavaDocFolder = IconLoader.getIcon("/nodes/javaDocFolder.png"); // 16x16
public static class Jsf {
public static final Icon Component = IconLoader.getIcon("/nodes/jsf/component.png"); // 16x16
public static final Icon Converter = IconLoader.getIcon("/nodes/jsf/converter.png"); // 16x16
public static final Icon General = IconLoader.getIcon("/nodes/jsf/general.png"); // 16x16
public static final Icon GenericValue = IconLoader.getIcon("/nodes/jsf/genericValue.png"); // 18x18
public static final Icon ManagedBean = IconLoader.getIcon("/nodes/jsf/managedBean.png"); // 16x16
public static final Icon NavigationCase = IconLoader.getIcon("/nodes/jsf/navigationCase.png"); // 18x18
public static final Icon NavigationRule = IconLoader.getIcon("/nodes/jsf/navigationRule.png"); // 16x16
public static final Icon Renderer = IconLoader.getIcon("/nodes/jsf/renderer.png"); // 16x16
public static final Icon RenderKit = IconLoader.getIcon("/nodes/jsf/renderKit.png"); // 16x16
public static final Icon Validator = IconLoader.getIcon("/nodes/jsf/validator.png"); // 16x16
}
public static final Icon Jsr45 = IconLoader.getIcon("/nodes/jsr45.png"); // 16x16
public static final Icon JunitTestMark = IconLoader.getIcon("/nodes/junitTestMark.png"); // 16x16
public static final Icon KeymapAnt = IconLoader.getIcon("/nodes/keymapAnt.png"); // 16x16
public static final Icon KeymapEditor = IconLoader.getIcon("/nodes/keymapEditor.png"); // 16x16
public static final Icon KeymapMainMenu = IconLoader.getIcon("/nodes/keymapMainMenu.png"); // 16x16
public static final Icon KeymapOther = IconLoader.getIcon("/nodes/keymapOther.png"); // 16x16
public static final Icon KeymapTools = IconLoader.getIcon("/nodes/keymapTools.png"); // 16x16
public static final Icon Locked = IconLoader.getIcon("/nodes/locked.png"); // 16x16
public static final Icon Method = IconLoader.getIcon("/nodes/method.png"); // 16x16
public static final Icon MethodReference = IconLoader.getIcon("/nodes/methodReference.png"); // 16x16
public static final Icon Module = IconLoader.getIcon("/nodes/Module.png"); // 16x16
public static final Icon ModuleGroup = IconLoader.getIcon("/nodes/moduleGroup.png"); // 16x16
public static final Icon NativeLibrariesFolder = IconLoader.getIcon("/nodes/nativeLibrariesFolder.png"); // 16x16
public static final Icon NewException = IconLoader.getIcon("/nodes/newException.png"); // 14x14
public static final Icon NewFolder = IconLoader.getIcon("/nodes/newFolder.png"); // 16x16
public static final Icon NewParameter = IconLoader.getIcon("/nodes/newParameter.png"); // 14x14
public static final Icon NodePlaceholder = IconLoader.getIcon("/nodes/nodePlaceholder.png"); // 16x16
public static final Icon Package = IconLoader.getIcon("/nodes/package.png"); // 16x16
public static final Icon Padlock = IconLoader.getIcon("/nodes/padlock.png"); // 16x16
public static final Icon Parameter = IconLoader.getIcon("/nodes/parameter.png"); // 16x16
public static final Icon PinToolWindow = IconLoader.getIcon("/nodes/pinToolWindow.png"); // 13x13
public static final Icon Plugin = IconLoader.getIcon("/nodes/plugin.png"); // 16x16
public static final Icon PluginJB = IconLoader.getIcon("/nodes/pluginJB.png"); // 16x16
public static final Icon PluginLogo = IconLoader.getIcon("/nodes/pluginLogo.png"); // 32x32
public static final Icon Pluginnotinstalled = IconLoader.getIcon("/nodes/pluginnotinstalled.png"); // 16x16
public static final Icon Pluginobsolete = IconLoader.getIcon("/nodes/pluginobsolete.png"); // 16x16
public static final Icon PluginRestart = IconLoader.getIcon("/nodes/pluginRestart.png"); // 16x16
public static final Icon PluginUpdate = IconLoader.getIcon("/nodes/pluginUpdate.png"); // 16x16
public static final Icon Pointcut = IconLoader.getIcon("/nodes/pointcut.png"); // 16x16
public static final Icon PpFile = IconLoader.getIcon("/nodes/ppFile.png"); // 16x16
public static final Icon PpInvalid = IconLoader.getIcon("/nodes/ppInvalid.png"); // 16x16
public static final Icon PpJar = IconLoader.getIcon("/nodes/ppJar.png"); // 16x16
public static final Icon PpJdk = IconLoader.getIcon("/nodes/ppJdk.png"); // 16x16
public static final Icon PpLib = IconLoader.getIcon("/nodes/ppLib.png"); // 16x16
public static final Icon PpLibFolder = IconLoader.getIcon("/nodes/ppLibFolder.png"); // 16x16
public static final Icon PpWeb = IconLoader.getIcon("/nodes/ppWeb.png"); // 16x16
public static final Icon PpWebLogo = IconLoader.getIcon("/nodes/ppWebLogo.png"); // 32x32
public static final Icon Project = IconLoader.getIcon("/nodes/project.png"); // 16x16
public static final Icon Property = IconLoader.getIcon("/nodes/property.png"); // 16x16
public static final Icon PropertyRead = IconLoader.getIcon("/nodes/propertyRead.png"); // 16x16
public static final Icon PropertyReadStatic = IconLoader.getIcon("/nodes/propertyReadStatic.png"); // 16x16
public static final Icon PropertyReadWrite = IconLoader.getIcon("/nodes/propertyReadWrite.png"); // 16x16
public static final Icon PropertyReadWriteStatic = IconLoader.getIcon("/nodes/propertyReadWriteStatic.png"); // 16x16
public static final Icon PropertyWrite = IconLoader.getIcon("/nodes/propertyWrite.png"); // 16x16
public static final Icon PropertyWriteStatic = IconLoader.getIcon("/nodes/propertyWriteStatic.png"); // 16x16
public static final Icon Read_access = IconLoader.getIcon("/nodes/read-access.png"); // 13x9
public static final Icon ResourceBundle = IconLoader.getIcon("/nodes/resourceBundle.png"); // 16x16
public static final Icon RunnableMark = IconLoader.getIcon("/nodes/runnableMark.png"); // 16x16
public static final Icon Rw_access = IconLoader.getIcon("/nodes/rw-access.png"); // 13x9
public static final Icon SecurityRole = IconLoader.getIcon("/nodes/SecurityRole.png"); // 16x16
public static final Icon Servlet = IconLoader.getIcon("/nodes/servlet.png"); // 16x16
public static final Icon Shared = IconLoader.getIcon("/nodes/shared.png"); // 16x16
public static final Icon SortBySeverity = IconLoader.getIcon("/nodes/sortBySeverity.png"); // 16x16
public static final Icon SourceFolder = IconLoader.getIcon("/nodes/sourceFolder.png"); // 16x16
public static final Icon Static = IconLoader.getIcon("/nodes/static.png"); // 16x16
public static final Icon StaticMark = IconLoader.getIcon("/nodes/staticMark.png"); // 16x16
public static final Icon Symlink = IconLoader.getIcon("/nodes/symlink.png"); // 16x16
public static final Icon TabAlert = IconLoader.getIcon("/nodes/tabAlert.png"); // 16x16
public static final Icon TabPin = IconLoader.getIcon("/nodes/tabPin.png"); // 16x16
public static final Icon Tag = IconLoader.getIcon("/nodes/tag.png"); // 16x16
public static final Icon TestSourceFolder = IconLoader.getIcon("/nodes/testSourceFolder.png"); // 16x16
public static final Icon TreeClosed = IconLoader.getIcon("/nodes/TreeClosed.png"); // 16x16
public static final Icon TreeCollapseNode = IconLoader.getIcon("/nodes/treeCollapseNode.png"); // 16x16
public static final Icon TreeDownArrow = IconLoader.getIcon("/nodes/treeDownArrow.png"); // 11x11
public static final Icon TreeExpandNode = IconLoader.getIcon("/nodes/treeExpandNode.png"); // 16x16
public static final Icon TreeOpen = IconLoader.getIcon("/nodes/TreeOpen.png"); // 16x16
public static final Icon TreeRightArrow = IconLoader.getIcon("/nodes/treeRightArrow.png"); // 11x11
public static final Icon Undeploy = IconLoader.getIcon("/nodes/undeploy.png"); // 16x16
public static final Icon UnknownJdk = IconLoader.getIcon("/nodes/unknownJdk.png"); // 16x16
public static final Icon UpFolder = IconLoader.getIcon("/nodes/upFolder.png"); // 16x16
public static final Icon UpLevel = IconLoader.getIcon("/nodes/upLevel.png"); // 16x16
public static final Icon Variable = IconLoader.getIcon("/nodes/variable.png"); // 16x16
public static final Icon WarningIntroduction = IconLoader.getIcon("/nodes/warningIntroduction.png"); // 16x16
public static final Icon WebFolder = IconLoader.getIcon("/nodes/webFolder.png"); // 16x16
public static final Icon Weblistener = IconLoader.getIcon("/nodes/weblistener.png"); // 16x16
public static final Icon Write_access = IconLoader.getIcon("/nodes/write-access.png"); // 13x9
}
public static class ObjectBrowser {
public static final Icon AbbreviatePackageNames = IconLoader.getIcon("/objectBrowser/abbreviatePackageNames.png"); // 16x16
public static final Icon CompactEmptyPackages = IconLoader.getIcon("/objectBrowser/compactEmptyPackages.png"); // 16x16
public static final Icon FlattenPackages = IconLoader.getIcon("/objectBrowser/flattenPackages.png"); // 16x16
public static final Icon ShowEditorHighlighting = IconLoader.getIcon("/objectBrowser/showEditorHighlighting.png"); // 16x16
public static final Icon ShowLibraryContents = IconLoader.getIcon("/objectBrowser/showLibraryContents.png"); // 16x16
public static final Icon ShowMembers = IconLoader.getIcon("/objectBrowser/showMembers.png"); // 16x16
public static final Icon ShowModules = IconLoader.getIcon("/objectBrowser/showModules.png"); // 16x16
public static final Icon SortByType = IconLoader.getIcon("/objectBrowser/sortByType.png"); // 16x16
public static final Icon Sorted = IconLoader.getIcon("/objectBrowser/sorted.png"); // 16x16
public static final Icon SortedByUsage = IconLoader.getIcon("/objectBrowser/sortedByUsage.png"); // 16x16
public static final Icon VisibilitySort = IconLoader.getIcon("/objectBrowser/visibilitySort.png"); // 16x16
}
public static class Preferences {
public static final Icon Appearance = IconLoader.getIcon("/preferences/Appearance.png"); // 32x32
public static final Icon CodeStyle = IconLoader.getIcon("/preferences/CodeStyle.png"); // 32x32
public static final Icon Compiler = IconLoader.getIcon("/preferences/Compiler.png"); // 32x32
public static final Icon Editor = IconLoader.getIcon("/preferences/Editor.png"); // 32x32
public static final Icon FileColors = IconLoader.getIcon("/preferences/FileColors.png"); // 32x32
public static final Icon FileTypes = IconLoader.getIcon("/preferences/FileTypes.png"); // 32x32
public static final Icon General = IconLoader.getIcon("/preferences/General.png"); // 32x32
public static final Icon Keymap = IconLoader.getIcon("/preferences/Keymap.png"); // 32x32
public static final Icon Plugins = IconLoader.getIcon("/preferences/Plugins.png"); // 32x32
public static final Icon Updates = IconLoader.getIcon("/preferences/Updates.png"); // 32x32
public static final Icon VersionControl = IconLoader.getIcon("/preferences/VersionControl.png"); // 32x32
}
public static class Process {
public static class Big {
public static final Icon Step_1 = IconLoader.getIcon("/process/big/step_1.png"); // 32x32
public static final Icon Step_10 = IconLoader.getIcon("/process/big/step_10.png"); // 32x32
public static final Icon Step_11 = IconLoader.getIcon("/process/big/step_11.png"); // 32x32
public static final Icon Step_12 = IconLoader.getIcon("/process/big/step_12.png"); // 32x32
public static final Icon Step_2 = IconLoader.getIcon("/process/big/step_2.png"); // 32x32
public static final Icon Step_3 = IconLoader.getIcon("/process/big/step_3.png"); // 32x32
public static final Icon Step_4 = IconLoader.getIcon("/process/big/step_4.png"); // 32x32
public static final Icon Step_5 = IconLoader.getIcon("/process/big/step_5.png"); // 32x32
public static final Icon Step_6 = IconLoader.getIcon("/process/big/step_6.png"); // 32x32
public static final Icon Step_7 = IconLoader.getIcon("/process/big/step_7.png"); // 32x32
public static final Icon Step_8 = IconLoader.getIcon("/process/big/step_8.png"); // 32x32
public static final Icon Step_9 = IconLoader.getIcon("/process/big/step_9.png"); // 32x32
public static final Icon Step_passive = IconLoader.getIcon("/process/big/step_passive.png"); // 32x32
}
public static final Icon DisabledDebug = IconLoader.getIcon("/process/disabledDebug.png"); // 13x13
public static final Icon DisabledRun = IconLoader.getIcon("/process/disabledRun.png"); // 13x13
public static class FS {
public static final Icon Step_1 = IconLoader.getIcon("/process/fs/step_1.png"); // 16x16
public static final Icon Step_10 = IconLoader.getIcon("/process/fs/step_10.png"); // 16x16
public static final Icon Step_11 = IconLoader.getIcon("/process/fs/step_11.png"); // 16x16
public static final Icon Step_12 = IconLoader.getIcon("/process/fs/step_12.png"); // 16x16
public static final Icon Step_13 = IconLoader.getIcon("/process/fs/step_13.png"); // 16x16
public static final Icon Step_14 = IconLoader.getIcon("/process/fs/step_14.png"); // 16x16
public static final Icon Step_15 = IconLoader.getIcon("/process/fs/step_15.png"); // 16x16
public static final Icon Step_16 = IconLoader.getIcon("/process/fs/step_16.png"); // 16x16
public static final Icon Step_17 = IconLoader.getIcon("/process/fs/step_17.png"); // 16x16
public static final Icon Step_18 = IconLoader.getIcon("/process/fs/step_18.png"); // 16x16
public static final Icon Step_2 = IconLoader.getIcon("/process/fs/step_2.png"); // 16x16
public static final Icon Step_3 = IconLoader.getIcon("/process/fs/step_3.png"); // 16x16
public static final Icon Step_4 = IconLoader.getIcon("/process/fs/step_4.png"); // 16x16
public static final Icon Step_5 = IconLoader.getIcon("/process/fs/step_5.png"); // 16x16
public static final Icon Step_6 = IconLoader.getIcon("/process/fs/step_6.png"); // 16x16
public static final Icon Step_7 = IconLoader.getIcon("/process/fs/step_7.png"); // 16x16
public static final Icon Step_8 = IconLoader.getIcon("/process/fs/step_8.png"); // 16x16
public static final Icon Step_9 = IconLoader.getIcon("/process/fs/step_9.png"); // 16x16
public static final Icon Step_mask = IconLoader.getIcon("/process/fs/step_mask.png"); // 16x16
public static final Icon Step_passive = IconLoader.getIcon("/process/fs/step_passive.png"); // 16x16
}
public static final Icon Step_1 = IconLoader.getIcon("/process/step_1.png"); // 16x16
public static final Icon Step_10 = IconLoader.getIcon("/process/step_10.png"); // 16x16
public static final Icon Step_11 = IconLoader.getIcon("/process/step_11.png"); // 16x16
public static final Icon Step_12 = IconLoader.getIcon("/process/step_12.png"); // 16x16
public static final Icon Step_2 = IconLoader.getIcon("/process/step_2.png"); // 16x16
public static final Icon Step_3 = IconLoader.getIcon("/process/step_3.png"); // 16x16
public static final Icon Step_4 = IconLoader.getIcon("/process/step_4.png"); // 16x16
public static final Icon Step_5 = IconLoader.getIcon("/process/step_5.png"); // 16x16
public static final Icon Step_6 = IconLoader.getIcon("/process/step_6.png"); // 16x16
public static final Icon Step_7 = IconLoader.getIcon("/process/step_7.png"); // 16x16
public static final Icon Step_8 = IconLoader.getIcon("/process/step_8.png"); // 16x16
public static final Icon Step_9 = IconLoader.getIcon("/process/step_9.png"); // 16x16
public static final Icon Step_mask = IconLoader.getIcon("/process/step_mask.png"); // 16x16
public static final Icon Step_passive = IconLoader.getIcon("/process/step_passive.png"); // 16x16
public static final Icon Stop = IconLoader.getIcon("/process/stop.png"); // 16x16
public static final Icon StopHovered = IconLoader.getIcon("/process/stopHovered.png"); // 16x16
}
public static class Providers {
public static final Icon Apache = IconLoader.getIcon("/providers/apache.png"); // 16x16
public static final Icon Bea = IconLoader.getIcon("/providers/bea.png"); // 16x16
public static final Icon Cvs = IconLoader.getIcon("/providers/cvs.png"); // 16x16
public static final Icon Eclipse = IconLoader.getIcon("/providers/eclipse.png"); // 16x16
public static final Icon H2 = IconLoader.getIcon("/providers/h2.png"); // 16x16
public static final Icon Hibernate = IconLoader.getIcon("/providers/hibernate.png"); // 16x16
public static final Icon Hsqldb = IconLoader.getIcon("/providers/hsqldb.png"); // 16x16
public static final Icon Ibm = IconLoader.getIcon("/providers/ibm.png"); // 16x16
public static final Icon Microsoft = IconLoader.getIcon("/providers/microsoft.png"); // 16x16
public static final Icon Mysql = IconLoader.getIcon("/providers/mysql.png"); // 16x16
public static final Icon Oracle = IconLoader.getIcon("/providers/oracle.png"); // 16x16
public static final Icon Postgresql = IconLoader.getIcon("/providers/postgresql.png"); // 16x16
public static final Icon Sqlite = IconLoader.getIcon("/providers/sqlite.png"); // 16x16
public static final Icon SqlServer = IconLoader.getIcon("/providers/sqlServer.png"); // 16x16
public static final Icon Sun = IconLoader.getIcon("/providers/sun.png"); // 16x16
public static final Icon Sybase = IconLoader.getIcon("/providers/sybase.png"); // 16x16
}
public static class RunConfigurations {
public static final Icon Applet = IconLoader.getIcon("/runConfigurations/applet.png"); // 16x16
public static final Icon Application = IconLoader.getIcon("/runConfigurations/application.png"); // 16x16
public static final Icon ConfigurationWarning = IconLoader.getIcon("/runConfigurations/configurationWarning.png"); // 16x16
public static final Icon HideIgnored = IconLoader.getIcon("/runConfigurations/hideIgnored.png"); // 16x16
public static final Icon HidePassed = IconLoader.getIcon("/runConfigurations/hidePassed.png"); // 16x16
public static final Icon IgnoredTest = IconLoader.getIcon("/runConfigurations/ignoredTest.png"); // 16x16
public static final Icon IncludeNonStartedTests_Rerun = IconLoader.getIcon("/runConfigurations/includeNonStartedTests_Rerun.png"); // 16x16
public static final Icon InvalidConfigurationLayer = IconLoader.getIcon("/runConfigurations/invalidConfigurationLayer.png"); // 16x16
public static final Icon Junit = IconLoader.getIcon("/runConfigurations/junit.png"); // 16x16
public static final Icon LoadingTree = IconLoader.getIcon("/runConfigurations/loadingTree.png"); // 16x16
public static final Icon Ql_console = IconLoader.getIcon("/runConfigurations/ql_console.png"); // 16x16
public static final Icon Remote = IconLoader.getIcon("/runConfigurations/remote.png"); // 16x16
public static final Icon RerunFailedTests = IconLoader.getIcon("/runConfigurations/rerunFailedTests.png"); // 16x16
public static final Icon SaveTempConfig = IconLoader.getIcon("/runConfigurations/saveTempConfig.png"); // 16x16
public static final Icon Scroll_down = IconLoader.getIcon("/runConfigurations/scroll_down.png"); // 16x16
public static final Icon ScrollToStackTrace = IconLoader.getIcon("/runConfigurations/scrollToStackTrace.png"); // 16x16
public static final Icon SelectFirstDefect = IconLoader.getIcon("/runConfigurations/selectFirstDefect.png"); // 16x16
public static final Icon SortbyDuration = IconLoader.getIcon("/runConfigurations/sortbyDuration.png"); // 16x16
public static final Icon SourceAtException = IconLoader.getIcon("/runConfigurations/sourceAtException.png"); // 16x16
public static final Icon TestError = IconLoader.getIcon("/runConfigurations/testError.png"); // 16x16
public static final Icon TestFailed = IconLoader.getIcon("/runConfigurations/testFailed.png"); // 16x16
public static final Icon TestIgnored = IconLoader.getIcon("/runConfigurations/testIgnored.png"); // 16x16
public static final Icon TestInProgress1 = IconLoader.getIcon("/runConfigurations/testInProgress1.png"); // 16x16
public static final Icon TestInProgress2 = IconLoader.getIcon("/runConfigurations/testInProgress2.png"); // 16x16
public static final Icon TestInProgress3 = IconLoader.getIcon("/runConfigurations/testInProgress3.png"); // 16x16
public static final Icon TestInProgress4 = IconLoader.getIcon("/runConfigurations/testInProgress4.png"); // 16x16
public static final Icon TestInProgress5 = IconLoader.getIcon("/runConfigurations/testInProgress5.png"); // 16x16
public static final Icon TestInProgress6 = IconLoader.getIcon("/runConfigurations/testInProgress6.png"); // 16x16
public static final Icon TestInProgress7 = IconLoader.getIcon("/runConfigurations/testInProgress7.png"); // 16x16
public static final Icon TestInProgress8 = IconLoader.getIcon("/runConfigurations/testInProgress8.png"); // 16x16
public static final Icon TestMark = IconLoader.getIcon("/runConfigurations/testMark.png"); // 16x16
public static final Icon TestNotRan = IconLoader.getIcon("/runConfigurations/testNotRan.png"); // 16x16
public static final Icon TestPassed = IconLoader.getIcon("/runConfigurations/testPassed.png"); // 16x16
public static final Icon TestPaused = IconLoader.getIcon("/runConfigurations/testPaused.png"); // 16x16
public static final Icon TestSkipped = IconLoader.getIcon("/runConfigurations/testSkipped.png"); // 16x16
public static final Icon TestTerminated = IconLoader.getIcon("/runConfigurations/testTerminated.png"); // 16x16
public static final Icon Tomcat = IconLoader.getIcon("/runConfigurations/tomcat.png"); // 16x16
public static final Icon TrackCoverage = IconLoader.getIcon("/runConfigurations/trackCoverage.png"); // 16x16
public static final Icon TrackTests = IconLoader.getIcon("/runConfigurations/trackTests.png"); // 16x16
public static final Icon Unknown = IconLoader.getIcon("/runConfigurations/unknown.png"); // 16x16
public static final Icon Variables = IconLoader.getIcon("/runConfigurations/variables.png"); // 16x16
public static final Icon Web_app = IconLoader.getIcon("/runConfigurations/web_app.png"); // 16x16
public static final Icon WithCoverageLayer = IconLoader.getIcon("/runConfigurations/withCoverageLayer.png"); // 16x16
}
public static class Toolbar {
public static final Icon Filterdups = IconLoader.getIcon("/toolbar/filterdups.png"); // 16x16
public static final Icon Folders = IconLoader.getIcon("/toolbar/folders.png"); // 16x16
public static final Icon Unknown = IconLoader.getIcon("/toolbar/unknown.png"); // 16x16
}
public static class ToolbarDecorator {
public static final Icon Add = IconLoader.getIcon("/toolbarDecorator/add.png"); // 14x14
public static final Icon AddBlankLine = IconLoader.getIcon("/toolbarDecorator/addBlankLine.png"); // 16x16
public static final Icon AddClass = IconLoader.getIcon("/toolbarDecorator/addClass.png"); // 16x16
public static final Icon AddFolder = IconLoader.getIcon("/toolbarDecorator/addFolder.png"); // 16x16
public static final Icon AddIcon = IconLoader.getIcon("/toolbarDecorator/addIcon.png"); // 16x16
public static final Icon AddJira = IconLoader.getIcon("/toolbarDecorator/addJira.png"); // 16x16
public static final Icon AddLink = IconLoader.getIcon("/toolbarDecorator/addLink.png"); // 16x16
public static final Icon AddPackage = IconLoader.getIcon("/toolbarDecorator/addPackage.png"); // 16x16
public static final Icon AddPattern = IconLoader.getIcon("/toolbarDecorator/addPattern.png"); // 16x16
public static final Icon AddRemoteDatasource = IconLoader.getIcon("/toolbarDecorator/addRemoteDatasource.png"); // 16x16
public static final Icon AddYouTrack = IconLoader.getIcon("/toolbarDecorator/addYouTrack.png"); // 16x16
public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/analyze.png"); // 14x14
public static final Icon Edit = IconLoader.getIcon("/toolbarDecorator/edit.png"); // 14x14
public static final Icon Export = IconLoader.getIcon("/toolbarDecorator/export.png"); // 16x16
public static final Icon Import = IconLoader.getIcon("/toolbarDecorator/import.png"); // 16x16
public static class Mac {
public static final Icon Add = IconLoader.getIcon("/toolbarDecorator/mac/add.png"); // 14x14
public static final Icon AddBlankLine = IconLoader.getIcon("/toolbarDecorator/mac/addBlankLine.png"); // 16x16
public static final Icon AddClass = IconLoader.getIcon("/toolbarDecorator/mac/addClass.png"); // 16x16
public static final Icon AddFolder = IconLoader.getIcon("/toolbarDecorator/mac/addFolder.png"); // 16x16
public static final Icon AddIcon = IconLoader.getIcon("/toolbarDecorator/mac/addIcon.png"); // 16x16
public static final Icon AddJira = IconLoader.getIcon("/toolbarDecorator/mac/addJira.png"); // 16x16
public static final Icon AddLink = IconLoader.getIcon("/toolbarDecorator/mac/addLink.png"); // 16x16
public static final Icon AddPackage = IconLoader.getIcon("/toolbarDecorator/mac/addPackage.png"); // 16x16
public static final Icon AddPattern = IconLoader.getIcon("/toolbarDecorator/mac/addPattern.png"); // 16x16
public static final Icon AddRemoteDatasource = IconLoader.getIcon("/toolbarDecorator/mac/addRemoteDatasource.png"); // 16x16
public static final Icon AddYouTrack = IconLoader.getIcon("/toolbarDecorator/mac/addYouTrack.png"); // 16x16
public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/mac/analyze.png"); // 14x14
public static final Icon Edit = IconLoader.getIcon("/toolbarDecorator/mac/edit.png"); // 14x14
public static final Icon MoveDown = IconLoader.getIcon("/toolbarDecorator/mac/moveDown.png"); // 14x14
public static final Icon MoveUp = IconLoader.getIcon("/toolbarDecorator/mac/moveUp.png"); // 14x14
public static final Icon Remove = IconLoader.getIcon("/toolbarDecorator/mac/remove.png"); // 14x14
}
public static final Icon MoveDown = IconLoader.getIcon("/toolbarDecorator/moveDown.png"); // 14x14
public static final Icon MoveUp = IconLoader.getIcon("/toolbarDecorator/moveUp.png"); // 14x14
public static final Icon Remove = IconLoader.getIcon("/toolbarDecorator/remove.png"); // 14x14
}
public static class Toolwindows {
public static final Icon Documentation = IconLoader.getIcon("/toolwindows/documentation.png"); // 13x13
public static final Icon Problems = IconLoader.getIcon("/toolwindows/problems.png"); // 13x13
public static final Icon ToolWindowAnt = IconLoader.getIcon("/toolwindows/toolWindowAnt.png"); // 13x13
public static final Icon ToolWindowChanges = IconLoader.getIcon("/toolwindows/toolWindowChanges.png"); // 13x13
public static final Icon ToolWindowCommander = IconLoader.getIcon("/toolwindows/toolWindowCommander.png"); // 13x13
public static final Icon ToolWindowCoverage = IconLoader.getIcon("/toolwindows/toolWindowCoverage.png"); // 13x13
public static final Icon ToolWindowCvs = IconLoader.getIcon("/toolwindows/toolWindowCvs.png"); // 13x13
public static final Icon ToolWindowDebugger = IconLoader.getIcon("/toolwindows/toolWindowDebugger.png"); // 13x13
public static final Icon ToolWindowFavorites = IconLoader.getIcon("/toolwindows/toolWindowFavorites.png"); // 13x13
public static final Icon ToolWindowFind = IconLoader.getIcon("/toolwindows/toolWindowFind.png"); // 13x13
public static final Icon ToolWindowHierarchy = IconLoader.getIcon("/toolwindows/toolWindowHierarchy.png"); // 13x13
public static final Icon ToolWindowInspection = IconLoader.getIcon("/toolwindows/toolWindowInspection.png"); // 13x13
public static final Icon ToolWindowMessages = IconLoader.getIcon("/toolwindows/toolWindowMessages.png"); // 13x13
public static final Icon ToolWindowModuleDependencies = IconLoader.getIcon("/toolwindows/toolWindowModuleDependencies.png"); // 13x13
public static final Icon ToolWindowPalette = IconLoader.getIcon("/toolwindows/toolWindowPalette.png"); // 13x13
public static final Icon ToolWindowPreview = IconLoader.getIcon("/toolwindows/toolWindowPreview.png"); // 13x13
public static final Icon ToolWindowProject = IconLoader.getIcon("/toolwindows/toolWindowProject.png"); // 13x13
public static final Icon ToolWindowRun = IconLoader.getIcon("/toolwindows/toolWindowRun.png"); // 13x13
public static final Icon ToolWindowStructure = IconLoader.getIcon("/toolwindows/toolWindowStructure.png"); // 13x13
public static final Icon ToolWindowTodo = IconLoader.getIcon("/toolwindows/toolWindowTodo.png"); // 13x13
public static final Icon VcsSmallTab = IconLoader.getIcon("/toolwindows/vcsSmallTab.png"); // 13x13
public static final Icon WebToolWindow = IconLoader.getIcon("/toolwindows/webToolWindow.png"); // 13x13
}
public static class Vcs {
public static final Icon AllRevisions = IconLoader.getIcon("/vcs/allRevisions.png"); // 16x16
public static final Icon Arrow_left = IconLoader.getIcon("/vcs/arrow_left.png"); // 16x16
public static final Icon Arrow_right = IconLoader.getIcon("/vcs/arrow_right.png"); // 16x16
public static final Icon CheckSpelling = IconLoader.getIcon("/vcs/checkSpelling.png"); // 16x16
public static final Icon Equal = IconLoader.getIcon("/vcs/equal.png"); // 16x16
public static final Icon History = IconLoader.getIcon("/vcs/history.png"); // 16x16
public static final Icon MapBase = IconLoader.getIcon("/vcs/mapBase.png"); // 16x16
public static final Icon Merge = IconLoader.getIcon("/vcs/merge.png"); // 12x12
public static final Icon MergeSourcesTree = IconLoader.getIcon("/vcs/mergeSourcesTree.png"); // 16x16
public static final Icon Not_equal = IconLoader.getIcon("/vcs/not_equal.png"); // 16x16
public static final Icon Remove = IconLoader.getIcon("/vcs/remove.png"); // 16x16
public static final Icon ResetStrip = IconLoader.getIcon("/vcs/resetStrip.png"); // 16x16
public static final Icon StripDown = IconLoader.getIcon("/vcs/stripDown.png"); // 16x16
public static final Icon StripNull = IconLoader.getIcon("/vcs/stripNull.png"); // 16x16
public static final Icon StripUp = IconLoader.getIcon("/vcs/stripUp.png"); // 16x16
}
public static class Webreferences {
public static final Icon Server = IconLoader.getIcon("/webreferences/server.png"); // 16x16
}
public static class Welcome {
public static final Icon CreateDesktopEntry = IconLoader.getIcon("/welcome/createDesktopEntry.png"); // 32x32
public static final Icon CreateNewProject = IconLoader.getIcon("/welcome/createNewProject.png"); // 16x16
public static final Icon CreateNewProjectfromExistingFiles = IconLoader.getIcon("/welcome/CreateNewProjectfromExistingFiles.png"); // 16x16
public static final Icon FromVCS = IconLoader.getIcon("/welcome/fromVCS.png"); // 16x16
public static final Icon ImportProject = IconLoader.getIcon("/welcome/importProject.png"); // 16x16
public static final Icon OpenProject = IconLoader.getIcon("/welcome/openProject.png"); // 16x16
public static class Project {
public static final Icon Remove_hover = IconLoader.getIcon("/welcome/project/remove-hover.png"); // 10x10
public static final Icon Remove = IconLoader.getIcon("/welcome/project/remove.png"); // 10x10
}
public static final Icon Register = IconLoader.getIcon("/welcome/register.png"); // 32x32
}
public static class Windows {
public static final Icon Close = IconLoader.getIcon("/windows/close.png"); // 16x16
public static final Icon Iconify = IconLoader.getIcon("/windows/iconify.png"); // 16x16
public static final Icon Maximize = IconLoader.getIcon("/windows/maximize.png"); // 16x16
public static final Icon Minimize = IconLoader.getIcon("/windows/minimize.png"); // 16x16
}
public static class Xml {
public static class Browsers {
public static final Icon Canary16 = IconLoader.getIcon("/xml/browsers/canary16.png"); // 16x16
public static final Icon Chrome16 = IconLoader.getIcon("/xml/browsers/chrome16.png"); // 16x16
public static final Icon Chromium16 = IconLoader.getIcon("/xml/browsers/chromium16.png"); // 16x16
public static final Icon Explorer16 = IconLoader.getIcon("/xml/browsers/explorer16.png"); // 16x16
public static final Icon Firefox16 = IconLoader.getIcon("/xml/browsers/firefox16.png"); // 16x16
public static final Icon Nwjs16 = IconLoader.getIcon("/xml/browsers/nwjs16.png"); // 16x16
public static final Icon Opera16 = IconLoader.getIcon("/xml/browsers/opera16.png"); // 16x16
public static final Icon Safari16 = IconLoader.getIcon("/xml/browsers/safari16.png"); // 16x16
public static final Icon Yandex16 = IconLoader.getIcon("/xml/browsers/yandex16.png"); // 16x16
}
public static final Icon Css_class = IconLoader.getIcon("/xml/css_class.png"); // 16x16
public static final Icon Html5 = IconLoader.getIcon("/xml/html5.png"); // 16x16
public static final Icon Html_id = IconLoader.getIcon("/xml/html_id.png"); // 16x16
}
}
| apache-2.0 |
vvv1559/intellij-community | java/idea-ui/src/com/intellij/ide/RecentProjectsManagerImpl.java | 2466 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.openapi.components.RoamingType;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.platform.PlatformProjectOpenProcessor;
import com.intellij.util.PathUtil;
import com.intellij.util.messages.MessageBus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.SystemIndependent;
import java.io.File;
@State(
name = "RecentProjectsManager",
storages = {
@Storage(value = "recentProjects.xml", roamingType = RoamingType.DISABLED),
@Storage(value = "other.xml", deprecated = true)
}
)
public class RecentProjectsManagerImpl extends RecentProjectsManagerBase {
public RecentProjectsManagerImpl(MessageBus messageBus) {
super(messageBus);
}
@Override
@SystemIndependent
protected String getProjectPath(@NotNull Project project) {
return PathUtil.toSystemIndependentName(project.getPresentableUrl());
}
@Override
protected void doOpenProject(@NotNull String projectPath, Project projectToClose, boolean forceOpenInNewFrame) {
File projectFile = new File(projectPath);
if (projectFile.isDirectory() && !new File(projectFile, Project.DIRECTORY_STORE_FOLDER).exists()) {
VirtualFile projectDir = LocalFileSystem.getInstance().findFileByIoFile(projectFile);
PlatformProjectOpenProcessor processor = PlatformProjectOpenProcessor.getInstanceIfItExists();
if (projectDir != null && processor != null) {
processor.doOpenProject(projectDir, projectToClose, forceOpenInNewFrame);
return;
}
}
ProjectUtil.openProject(projectPath, projectToClose, forceOpenInNewFrame);
}
}
| apache-2.0 |
asedunov/intellij-community | java/debugger/impl/src/com/intellij/debugger/jdi/DecompiledLocalVariable.java | 2572 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.jdi;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* @author Eugene Zhuravlev
* Date: 10/7/13
*/
public class DecompiledLocalVariable{
public static final String PARAM_PREFIX = "param_";
public static final String SLOT_PREFIX = "slot_";
private final int mySlot;
private final String mySignature;
private final boolean myIsParam;
private final Collection<String> myMatchedNames;
public DecompiledLocalVariable(int slot, boolean isParam, @Nullable String signature, @NotNull Collection<String> names) {
mySlot = slot;
myIsParam = isParam;
mySignature = signature;
myMatchedNames = names;
}
public int getSlot() {
return mySlot;
}
@Nullable
public String getSignature() {
return mySignature;
}
public boolean isParam() {
return myIsParam;
}
@NotNull
public String getDefaultName() {
return (myIsParam ? PARAM_PREFIX : SLOT_PREFIX) + mySlot;
}
public String getDisplayName() {
String nameString = StringUtil.join(myMatchedNames, " | ");
if (myIsParam && myMatchedNames.size() == 1) {
return nameString;
}
else if (!myMatchedNames.isEmpty()) {
return nameString + " (" + getDefaultName() + ")";
}
return getDefaultName();
}
@NotNull
public Collection<String> getMatchedNames() {
return myMatchedNames;
}
@Override
public String toString() {
return getDisplayName() + " (slot " + mySlot + ", " + mySignature + ")";
}
public static int getParamId(@Nullable String name) {
if (!StringUtil.isEmpty(name)) {
String idString = StringUtil.substringAfter(name, PARAM_PREFIX);
if (idString != null) {
try {
return Integer.parseInt(idString);
}
catch (NumberFormatException ignored) {
}
}
}
return -1;
}
}
| apache-2.0 |
kyleolivo/gocd | jetty9/test/com/thoughtworks/go/server/util/Jetty9ServletHelperTest.java | 1534 | /*
* Copyright 2016 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.server.util;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
public class Jetty9ServletHelperTest {
@Test
public void shouldGetInstanceOfServletHelper(){
ServletHelper.init();
assertThat(ServletHelper.getInstance() instanceof Jetty9ServletHelper, is(true));
}
@Test
public void shouldGetJetty9Request() {
ServletRequest request = new Jetty9ServletHelper().getRequest(mock(Request.class));
assertThat(request instanceof Jetty9Request, is(true));
}
@Test
public void shouldGetJetty9Response() {
ServletResponse response = new Jetty9ServletHelper().getResponse(mock(Response.class));
assertThat(response instanceof Jetty9Response, is(true));
}
}
| apache-2.0 |
GabrielNicolasAvellaneda/jolokia | agent/jvm-spring/src/main/java/org/jolokia/jvmagent/spring/config/MBeanServerBeanDefinitionParser.java | 1231 | package org.jolokia.jvmagent.spring.config;
/*
* Copyright 2009-2013 Roland Huss
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.jolokia.jvmagent.spring.SpringJolokiaMBeanServerFactory;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.w3c.dom.Element;
/**
* Definition parser for "mbean-server"
*
* @author roland
* @since 11.02.13
*/
public class MBeanServerBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
@Override
protected Class<?> getBeanClass(Element element) {
return SpringJolokiaMBeanServerFactory.class;
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
}
| apache-2.0 |
JingchengDu/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestLease.java | 15850 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.anyShort;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.client.impl.LeaseRenewer;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.Time;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
public class TestLease {
static boolean hasLease(MiniDFSCluster cluster, Path src) {
return NameNodeAdapter.getLeaseForPath(cluster.getNameNode(),
src.toString()) != null;
}
static int leaseCount(MiniDFSCluster cluster) {
return NameNodeAdapter.getLeaseManager(cluster.getNamesystem()).countLease();
}
static final String dirString = "/test/lease";
final Path dir = new Path(dirString);
static final Logger LOG = LoggerFactory.getLogger(TestLease.class);
final Configuration conf = new HdfsConfiguration();
@Test
public void testLeaseAbort() throws Exception {
MiniDFSCluster cluster =
new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
cluster.waitActive();
NamenodeProtocols preSpyNN = cluster.getNameNodeRpc();
NamenodeProtocols spyNN = spy(preSpyNN);
DFSClient dfs = new DFSClient(null, spyNN, conf, null);
byte[] buf = new byte[1024];
FSDataOutputStream c_out = createFsOut(dfs, dirString + "c");
c_out.write(buf, 0, 1024);
c_out.close();
DFSInputStream c_in = dfs.open(dirString + "c");
FSDataOutputStream d_out = createFsOut(dfs, dirString + "d");
// stub the renew method.
doThrow(new RemoteException(InvalidToken.class.getName(),
"Your token is worthless")).when(spyNN).renewLease(anyString());
// We don't need to wait the lease renewer thread to act.
// call renewLease() manually.
// make it look like the soft limit has been exceeded.
LeaseRenewer originalRenewer = dfs.getLeaseRenewer();
dfs.lastLeaseRenewal = Time.monotonicNow() -
HdfsConstants.LEASE_SOFTLIMIT_PERIOD - 1000;
try {
dfs.renewLease();
} catch (IOException e) {}
// Things should continue to work it passes hard limit without
// renewing.
try {
d_out.write(buf, 0, 1024);
LOG.info("Write worked beyond the soft limit as expected.");
} catch (IOException e) {
Assert.fail("Write failed.");
}
long hardlimit = conf.getLong(DFSConfigKeys.DFS_LEASE_HARDLIMIT_KEY,
DFSConfigKeys.DFS_LEASE_HARDLIMIT_DEFAULT) * 1000;
// make it look like the hard limit has been exceeded.
dfs.lastLeaseRenewal = Time.monotonicNow() - hardlimit - 1000;
dfs.renewLease();
// this should not work.
try {
d_out.write(buf, 0, 1024);
d_out.close();
Assert.fail("Write did not fail even after the fatal lease renewal failure");
} catch (IOException e) {
LOG.info("Write failed as expected. ", e);
}
// If aborted, the renewer should be empty. (no reference to clients)
Thread.sleep(1000);
Assert.assertTrue(originalRenewer.isEmpty());
// unstub
doNothing().when(spyNN).renewLease(anyString());
// existing input streams should work
try {
int num = c_in.read(buf, 0, 1);
if (num != 1) {
Assert.fail("Failed to read 1 byte");
}
c_in.close();
} catch (IOException e) {
LOG.error("Read failed with ", e);
Assert.fail("Read after lease renewal failure failed");
}
// new file writes should work.
try {
c_out = createFsOut(dfs, dirString + "c");
c_out.write(buf, 0, 1024);
c_out.close();
} catch (IOException e) {
LOG.error("Write failed with ", e);
Assert.fail("Write failed");
}
} finally {
cluster.shutdown();
}
}
@Test
public void testLeaseAfterRename() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
Path p = new Path("/test-file");
Path d = new Path("/test-d");
Path d2 = new Path("/test-d-other");
// open a file to get a lease
FileSystem fs = cluster.getFileSystem();
FSDataOutputStream out = fs.create(p);
out.writeBytes("something");
//out.hsync();
Assert.assertTrue(hasLease(cluster, p));
Assert.assertEquals(1, leaseCount(cluster));
// just to ensure first fs doesn't have any logic to twiddle leases
DistributedFileSystem fs2 = (DistributedFileSystem) FileSystem.newInstance(fs.getUri(), fs.getConf());
// rename the file into an existing dir
LOG.info("DMS: rename file into dir");
Path pRenamed = new Path(d, p.getName());
fs2.mkdirs(d);
fs2.rename(p, pRenamed);
Assert.assertFalse(p+" exists", fs2.exists(p));
Assert.assertTrue(pRenamed+" not found", fs2.exists(pRenamed));
Assert.assertFalse("has lease for "+p, hasLease(cluster, p));
Assert.assertTrue("no lease for "+pRenamed, hasLease(cluster, pRenamed));
Assert.assertEquals(1, leaseCount(cluster));
// rename the parent dir to a new non-existent dir
LOG.info("DMS: rename parent dir");
Path pRenamedAgain = new Path(d2, pRenamed.getName());
fs2.rename(d, d2);
// src gone
Assert.assertFalse(d+" exists", fs2.exists(d));
Assert.assertFalse("has lease for "+pRenamed, hasLease(cluster, pRenamed));
// dst checks
Assert.assertTrue(d2+" not found", fs2.exists(d2));
Assert.assertTrue(pRenamedAgain+" not found", fs2.exists(pRenamedAgain));
Assert.assertTrue("no lease for "+pRenamedAgain, hasLease(cluster, pRenamedAgain));
Assert.assertEquals(1, leaseCount(cluster));
// rename the parent dir to existing dir
// NOTE: rename w/o options moves paths into existing dir
LOG.info("DMS: rename parent again");
pRenamed = pRenamedAgain;
pRenamedAgain = new Path(new Path(d, d2.getName()), p.getName());
fs2.mkdirs(d);
fs2.rename(d2, d);
// src gone
Assert.assertFalse(d2+" exists", fs2.exists(d2));
Assert.assertFalse("no lease for "+pRenamed, hasLease(cluster, pRenamed));
// dst checks
Assert.assertTrue(d+" not found", fs2.exists(d));
Assert.assertTrue(pRenamedAgain +" not found", fs2.exists(pRenamedAgain));
Assert.assertTrue("no lease for "+pRenamedAgain, hasLease(cluster, pRenamedAgain));
Assert.assertEquals(1, leaseCount(cluster));
// rename with opts to non-existent dir
pRenamed = pRenamedAgain;
pRenamedAgain = new Path(d2, p.getName());
fs2.rename(pRenamed.getParent(), d2, Options.Rename.OVERWRITE);
// src gone
Assert.assertFalse(pRenamed.getParent() +" not found", fs2.exists(pRenamed.getParent()));
Assert.assertFalse("has lease for "+pRenamed, hasLease(cluster, pRenamed));
// dst checks
Assert.assertTrue(d2+" not found", fs2.exists(d2));
Assert.assertTrue(pRenamedAgain+" not found", fs2.exists(pRenamedAgain));
Assert.assertTrue("no lease for "+pRenamedAgain, hasLease(cluster, pRenamedAgain));
Assert.assertEquals(1, leaseCount(cluster));
// rename with opts to existing dir
// NOTE: rename with options will not move paths into the existing dir
pRenamed = pRenamedAgain;
pRenamedAgain = new Path(d, p.getName());
fs2.rename(pRenamed.getParent(), d, Options.Rename.OVERWRITE);
// src gone
Assert.assertFalse(pRenamed.getParent() +" not found", fs2.exists(pRenamed.getParent()));
Assert.assertFalse("has lease for "+pRenamed, hasLease(cluster, pRenamed));
// dst checks
Assert.assertTrue(d+" not found", fs2.exists(d));
Assert.assertTrue(pRenamedAgain+" not found", fs2.exists(pRenamedAgain));
Assert.assertTrue("no lease for "+pRenamedAgain, hasLease(cluster, pRenamedAgain));
Assert.assertEquals(1, leaseCount(cluster));
out.close();
} finally {
cluster.shutdown();
}
}
/**
* Test that we can open up a file for write, move it to another location,
* and then create a new file in the previous location, without causing any
* lease conflicts. This is possible because we now use unique inode IDs
* to identify files to the NameNode.
*/
@Test
public void testLeaseAfterRenameAndRecreate() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
final Path path1 = new Path("/test-file");
final String contents1 = "contents1";
final Path path2 = new Path("/test-file-new-location");
final String contents2 = "contents2";
// open a file to get a lease
FileSystem fs = cluster.getFileSystem();
FSDataOutputStream out1 = fs.create(path1);
out1.writeBytes(contents1);
Assert.assertTrue(hasLease(cluster, path1));
Assert.assertEquals(1, leaseCount(cluster));
DistributedFileSystem fs2 = (DistributedFileSystem)
FileSystem.newInstance(fs.getUri(), fs.getConf());
fs2.rename(path1, path2);
FSDataOutputStream out2 = fs2.create(path1);
out2.writeBytes(contents2);
out2.close();
// The first file should still be open and valid
Assert.assertTrue(hasLease(cluster, path2));
out1.close();
// Contents should be as expected
DistributedFileSystem fs3 = (DistributedFileSystem)
FileSystem.newInstance(fs.getUri(), fs.getConf());
Assert.assertEquals(contents1, DFSTestUtil.readFile(fs3, path2));
Assert.assertEquals(contents2, DFSTestUtil.readFile(fs3, path1));
} finally {
cluster.shutdown();
}
}
@Test
public void testLease() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
try {
FileSystem fs = cluster.getFileSystem();
Assert.assertTrue(fs.mkdirs(dir));
Path a = new Path(dir, "a");
Path b = new Path(dir, "b");
DataOutputStream a_out = fs.create(a);
a_out.writeBytes("something");
Assert.assertTrue(hasLease(cluster, a));
Assert.assertTrue(!hasLease(cluster, b));
DataOutputStream b_out = fs.create(b);
b_out.writeBytes("something");
Assert.assertTrue(hasLease(cluster, a));
Assert.assertTrue(hasLease(cluster, b));
a_out.close();
b_out.close();
Assert.assertTrue(!hasLease(cluster, a));
Assert.assertTrue(!hasLease(cluster, b));
Path fileA = new Path(dir, "fileA");
FSDataOutputStream fileA_out = fs.create(fileA);
fileA_out.writeBytes("something");
Assert.assertTrue("Failed to get the lease!", hasLease(cluster, fileA));
fs.delete(dir, true);
try {
fileA_out.hflush();
Assert.fail("Should validate file existence!");
} catch (FileNotFoundException e) {
// expected
GenericTestUtils.assertExceptionContains("File does not exist", e);
}
} finally {
if (cluster != null) {cluster.shutdown();}
}
}
@SuppressWarnings("unchecked")
@Test
public void testFactory() throws Exception {
final String[] groups = new String[]{"supergroup"};
final UserGroupInformation[] ugi = new UserGroupInformation[3];
for(int i = 0; i < ugi.length; i++) {
ugi[i] = UserGroupInformation.createUserForTesting("user" + i, groups);
}
Mockito.doReturn(new HdfsFileStatus.Builder()
.replication(1)
.blocksize(1024)
.perm(new FsPermission((short) 777))
.owner("owner")
.group("group")
.symlink(new byte[0])
.path(new byte[0])
.fileId(1010)
.build())
.when(mcp)
.getFileInfo(anyString());
Mockito.doReturn(new HdfsFileStatus.Builder()
.replication(1)
.blocksize(1024)
.perm(new FsPermission((short) 777))
.owner("owner")
.group("group")
.symlink(new byte[0])
.path(new byte[0])
.fileId(1010)
.build())
.when(mcp)
.create(anyString(), any(), anyString(),
any(), anyBoolean(), anyShort(), anyLong(), any(), any(), any());
final Configuration conf = new Configuration();
final DFSClient c1 = createDFSClientAs(ugi[0], conf);
FSDataOutputStream out1 = createFsOut(c1, "/out1");
final DFSClient c2 = createDFSClientAs(ugi[0], conf);
FSDataOutputStream out2 = createFsOut(c2, "/out2");
Assert.assertEquals(c1.getLeaseRenewer(), c2.getLeaseRenewer());
final DFSClient c3 = createDFSClientAs(ugi[1], conf);
FSDataOutputStream out3 = createFsOut(c3, "/out3");
Assert.assertTrue(c1.getLeaseRenewer() != c3.getLeaseRenewer());
final DFSClient c4 = createDFSClientAs(ugi[1], conf);
FSDataOutputStream out4 = createFsOut(c4, "/out4");
Assert.assertEquals(c3.getLeaseRenewer(), c4.getLeaseRenewer());
final DFSClient c5 = createDFSClientAs(ugi[2], conf);
FSDataOutputStream out5 = createFsOut(c5, "/out5");
Assert.assertTrue(c1.getLeaseRenewer() != c5.getLeaseRenewer());
Assert.assertTrue(c3.getLeaseRenewer() != c5.getLeaseRenewer());
}
private FSDataOutputStream createFsOut(DFSClient dfs, String path)
throws IOException {
return new FSDataOutputStream(dfs.create(path, true), null);
}
static final ClientProtocol mcp = Mockito.mock(ClientProtocol.class);
static public DFSClient createDFSClientAs(UserGroupInformation ugi,
final Configuration conf) throws Exception {
return ugi.doAs(new PrivilegedExceptionAction<DFSClient>() {
@Override
public DFSClient run() throws Exception {
return new DFSClient(null, mcp, conf, null);
}
});
}
}
| apache-2.0 |
ice-coffee/EIM | src/org/jivesoftware/smackx/workgroup/QueueUser.java | 2596 | /**
* $Revision$
* $Date$
*
* Copyright 2003-2007 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.workgroup;
import java.util.Date;
/**
* An immutable class which wraps up customer-in-queue data return from the server; depending on
* the type of information dispatched from the server, not all information will be available in
* any given instance.
*
* @author loki der quaeler
*/
public class QueueUser {
private String userID;
private int queuePosition;
private int estimatedTime;
private Date joinDate;
/**
* @param uid the user jid of the customer in the queue
* @param position the position customer sits in the queue
* @param time the estimate of how much longer the customer will be in the queue in seconds
* @param joinedAt the timestamp of when the customer entered the queue
*/
public QueueUser (String uid, int position, int time, Date joinedAt) {
super();
this.userID = uid;
this.queuePosition = position;
this.estimatedTime = time;
this.joinDate = joinedAt;
}
/**
* @return the user jid of the customer in the queue
*/
public String getUserID () {
return this.userID;
}
/**
* @return the position in the queue at which the customer sits, or -1 if the update which
* this instance embodies is only a time update instead
*/
public int getQueuePosition () {
return this.queuePosition;
}
/**
* @return the estimated time remaining of the customer in the queue in seconds, or -1 if
* if the update which this instance embodies is only a position update instead
*/
public int getEstimatedRemainingTime () {
return this.estimatedTime;
}
/**
* @return the timestamp of when this customer entered the queue, or null if the server did not
* provide this information
*/
public Date getQueueJoinTimestamp () {
return this.joinDate;
}
}
| apache-2.0 |
nwnpallewela/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/commands/RouterMediatorContainerCreateCommand.java | 2872 | package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.gmf.runtime.notation.View;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.RouterMediator;
import org.wso2.developerstudio.eclipse.gmf.esb.RouterMediatorContainer;
/**
* @generated
*/
public class RouterMediatorContainerCreateCommand extends EditElementCommand {
/**
* @generated
*/
public RouterMediatorContainerCreateCommand(CreateElementRequest req) {
super(req.getLabel(), null, req);
}
/**
* FIXME: replace with setElementToEdit()
* @generated
*/
protected EObject getElementToEdit() {
EObject container = ((CreateElementRequest) getRequest()).getContainer();
if (container instanceof View) {
container = ((View) container).getElement();
}
return container;
}
/**
* @generated
*/
public boolean canExecute() {
RouterMediator container = (RouterMediator) getElementToEdit();
if (container.getRouterContainer() != null) {
return false;
}
return true;
}
/**
* @generated
*/
protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
RouterMediatorContainer newElement = EsbFactory.eINSTANCE.createRouterMediatorContainer();
RouterMediator owner = (RouterMediator) getElementToEdit();
owner.setRouterContainer(newElement);
doConfigure(newElement, monitor, info);
((CreateElementRequest) getRequest()).setNewElement(newElement);
return CommandResult.newOKCommandResult(newElement);
}
/**
* @generated
*/
protected void doConfigure(RouterMediatorContainer newElement, IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
IElementType elementType = ((CreateElementRequest) getRequest()).getElementType();
ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType);
configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext());
configureRequest.addParameters(getRequest().getParameters());
ICommand configureCommand = elementType.getEditCommand(configureRequest);
if (configureCommand != null && configureCommand.canExecute()) {
configureCommand.execute(monitor, info);
}
}
}
| apache-2.0 |
phillips1021/uPortal | uPortal-events/src/main/java/org/apereo/portal/events/aggr/PortalEventPurgerImpl.java | 6131 | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* 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 the
* following location:
*
* <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 org.apereo.portal.events.aggr;
import org.apereo.portal.IPortalInfoProvider;
import org.apereo.portal.concurrency.locking.IClusterLockService;
import org.apereo.portal.events.aggr.dao.IEventAggregationManagementDao;
import org.apereo.portal.events.handlers.db.IPortalEventDao;
import org.apereo.portal.jpa.BaseAggrEventsJpaDao.AggrEventsTransactional;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.ReadablePeriod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class PortalEventPurgerImpl implements PortalEventPurger {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private IEventAggregationManagementDao eventAggregationManagementDao;
private IPortalInfoProvider portalInfoProvider;
private IPortalEventDao portalEventDao;
private IClusterLockService clusterLockService;
private ReadablePeriod purgeDelay = Period.days(1);
@Autowired
public void setClusterLockService(IClusterLockService clusterLockService) {
this.clusterLockService = clusterLockService;
}
@Autowired
public void setEventAggregationManagementDao(
IEventAggregationManagementDao eventAggregationManagementDao) {
this.eventAggregationManagementDao = eventAggregationManagementDao;
}
@Autowired
public void setPortalInfoProvider(IPortalInfoProvider portalInfoProvider) {
this.portalInfoProvider = portalInfoProvider;
}
@Autowired
public void setPortalEventDao(IPortalEventDao portalEventDao) {
this.portalEventDao = portalEventDao;
}
@Value("${org.apereo.portal.events.aggr.PortalEventPurgerImpl.purgeDelay:PT1H}")
public void setPurgeDelay(ReadablePeriod purgeDelay) {
this.purgeDelay = purgeDelay;
}
@Override
@AggrEventsTransactional
public EventProcessingResult doPurgeRawEvents() {
if (!this.clusterLockService.isLockOwner(PURGE_RAW_EVENTS_LOCK_NAME)) {
throw new IllegalStateException(
"The cluster lock "
+ PURGE_RAW_EVENTS_LOCK_NAME
+ " must be owned by the current thread and server");
}
final IEventAggregatorStatus eventPurgerStatus =
eventAggregationManagementDao.getEventAggregatorStatus(
IEventAggregatorStatus.ProcessingType.PURGING, true);
// Update status with current server name
final String serverName = this.portalInfoProvider.getUniqueServerName();
eventPurgerStatus.setServerName(serverName);
eventPurgerStatus.setLastStart(new DateTime());
// Determine date of most recently aggregated data
final IEventAggregatorStatus eventAggregatorStatus =
eventAggregationManagementDao.getEventAggregatorStatus(
IEventAggregatorStatus.ProcessingType.AGGREGATION, false);
if (eventAggregatorStatus == null || eventAggregatorStatus.getLastEventDate() == null) {
// Nothing has been aggregated, skip purging
eventPurgerStatus.setLastEnd(new DateTime());
eventAggregationManagementDao.updateEventAggregatorStatus(eventPurgerStatus);
return new EventProcessingResult(0, null, null, true);
}
boolean complete = true;
// Calculate purge end date from most recent aggregation minus the purge delay
final DateTime lastAggregated = eventAggregatorStatus.getLastEventDate();
DateTime purgeEnd = lastAggregated.minus(this.purgeDelay);
// Determine the DateTime of the oldest event
DateTime oldestEventDate = eventPurgerStatus.getLastEventDate();
if (oldestEventDate == null) {
oldestEventDate = this.portalEventDao.getOldestPortalEventTimestamp();
}
// Make sure purgeEnd is no more than 1 hour after the oldest event date to limit delete
// scope
final DateTime purgeEndLimit = oldestEventDate.plusHours(1);
if (purgeEndLimit.isBefore(purgeEnd)) {
purgeEnd = purgeEndLimit;
complete = false;
}
final Thread currentThread = Thread.currentThread();
final String currentName = currentThread.getName();
final int events;
try {
currentThread.setName(currentName + "-" + purgeEnd);
// Purge events
logger.debug("Starting purge of events before {}", purgeEnd);
events = portalEventDao.deletePortalEventsBefore(purgeEnd);
} finally {
currentThread.setName(currentName);
}
// Update the status object and store it
purgeEnd =
purgeEnd.minusMillis(
100); // decrement by 100ms since deletePortalEventsBefore uses lessThan and
// not lessThanEqualTo
eventPurgerStatus.setLastEventDate(purgeEnd);
eventPurgerStatus.setLastEnd(new DateTime());
eventAggregationManagementDao.updateEventAggregatorStatus(eventPurgerStatus);
return new EventProcessingResult(events, oldestEventDate, purgeEnd, complete);
}
}
| apache-2.0 |
nwnpallewela/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/policies/APIResourceEndpointItemSemanticEditPolicy.java | 4985 | package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies;
import java.util.Iterator;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.common.core.command.ICompositeCommand;
import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand;
import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
import org.eclipse.gmf.runtime.notation.Edge;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands.APIResourceEndpointInputConnectorCreateCommand;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands.APIResourceEndpointOutputConnectorCreateCommand;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceEndpointInputConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.APIResourceEndpointOutputConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EsbLinkEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes;
/**
* @generated
*/
public class APIResourceEndpointItemSemanticEditPolicy extends EsbBaseItemSemanticEditPolicy {
/**
* @generated
*/
public APIResourceEndpointItemSemanticEditPolicy() {
super(EsbElementTypes.APIResourceEndpoint_3674);
}
/**
* @generated
*/
protected Command getCreateCommand(CreateElementRequest req) {
if (EsbElementTypes.APIResourceEndpointInputConnector_3675 == req.getElementType()) {
return getGEFWrapper(new APIResourceEndpointInputConnectorCreateCommand(req));
}
if (EsbElementTypes.APIResourceEndpointOutputConnector_3676 == req.getElementType()) {
return getGEFWrapper(new APIResourceEndpointOutputConnectorCreateCommand(req));
}
return super.getCreateCommand(req);
}
/**
* @generated
*/
protected Command getDestroyElementCommand(DestroyElementRequest req) {
View view = (View) getHost().getModel();
CompositeTransactionalCommand cmd = new CompositeTransactionalCommand(getEditingDomain(), null);
cmd.setTransactionNestingEnabled(false);
EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$
if (annotation == null) {
// there are indirectly referenced children, need extra commands: false
addDestroyChildNodesCommand(cmd);
addDestroyShortcutsCommand(cmd, view);
// delete host element
cmd.add(new DestroyElementCommand(req));
} else {
cmd.add(new DeleteCommand(getEditingDomain(), view));
}
return getGEFWrapper(cmd.reduce());
}
/**
* @generated
*/
private void addDestroyChildNodesCommand(ICompositeCommand cmd) {
View view = (View) getHost().getModel();
for (Iterator<?> nit = view.getChildren().iterator(); nit.hasNext();) {
Node node = (Node) nit.next();
switch (EsbVisualIDRegistry.getVisualID(node)) {
case APIResourceEndpointInputConnectorEditPart.VISUAL_ID:
for (Iterator<?> it = node.getTargetEdges().iterator(); it.hasNext();) {
Edge incomingLink = (Edge) it.next();
if (EsbVisualIDRegistry.getVisualID(incomingLink) == EsbLinkEditPart.VISUAL_ID) {
DestroyElementRequest r = new DestroyElementRequest(incomingLink.getElement(), false);
cmd.add(new DestroyElementCommand(r));
cmd.add(new DeleteCommand(getEditingDomain(), incomingLink));
continue;
}
}
cmd.add(new DestroyElementCommand(new DestroyElementRequest(getEditingDomain(), node.getElement(),
false))); // directlyOwned: true
// don't need explicit deletion of node as parent's view deletion would clean child views as well
// cmd.add(new org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand(getEditingDomain(), node));
break;
case APIResourceEndpointOutputConnectorEditPart.VISUAL_ID:
for (Iterator<?> it = node.getSourceEdges().iterator(); it.hasNext();) {
Edge outgoingLink = (Edge) it.next();
if (EsbVisualIDRegistry.getVisualID(outgoingLink) == EsbLinkEditPart.VISUAL_ID) {
DestroyElementRequest r = new DestroyElementRequest(outgoingLink.getElement(), false);
cmd.add(new DestroyElementCommand(r));
cmd.add(new DeleteCommand(getEditingDomain(), outgoingLink));
continue;
}
}
cmd.add(new DestroyElementCommand(new DestroyElementRequest(getEditingDomain(), node.getElement(),
false))); // directlyOwned: true
// don't need explicit deletion of node as parent's view deletion would clean child views as well
// cmd.add(new org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand(getEditingDomain(), node));
break;
}
}
}
}
| apache-2.0 |
ric2b/Vivaldi-browser | chromium/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashContentProvider.java | 7522 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.webapk.shell_apk.h2o;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import org.chromium.webapk.lib.common.WebApkCommonUtils;
import org.chromium.webapk.shell_apk.WebApkSharedPreferences;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicReference;
/** ContentProvider for screenshot of splash screen. */
public class SplashContentProvider
extends ContentProvider implements ContentProvider.PipeDataWriter<Void> {
/** Holds value which gets cleared after {@link ExpiringData#CLEAR_DATA_INTERVAL_MS}. */
private static class ExpiringData {
/** Time in milliseconds after constructing the object to clear the cached data. */
private static final int CLEAR_CACHED_DATA_INTERVAL_MS = 10000;
private byte[] mCachedData;
private Handler mHandler;
public ExpiringData(byte[] cachedData, Runnable expiryTask) {
mCachedData = cachedData;
mHandler = new Handler();
mHandler.postDelayed(expiryTask, CLEAR_CACHED_DATA_INTERVAL_MS);
}
public byte[] getCachedData() {
return mCachedData;
}
public void removeCallbacks() {
mHandler.removeCallbacksAndMessages(null);
}
}
/**
* Maximum size in bytes of screenshot to transfer to browser. The screenshot should be
* downsampled to fit. Capping the maximum size of the screenshot decreases bitmap encoding
* time and image transfer time.
*/
public static final int MAX_TRANSFER_SIZE_BYTES = 1024 * 1024 * 12;
/**
* The encoding type of the last image vended by the ContentProvider.
*/
private static Bitmap.CompressFormat sEncodingFormat;
private static AtomicReference<ExpiringData> sCachedSplashBytes = new AtomicReference<>();
/** The URI handled by this content provider. */
private String mContentProviderUri;
/**
* Temporarily caches the passed-in splash screen screenshot. To preserve memory, the cached
* data is cleared after a delay.
*/
public static void cache(Context context, byte[] splashBytes,
Bitmap.CompressFormat encodingFormat, int splashWidth, int splashHeight) {
SharedPreferences.Editor editor = WebApkSharedPreferences.getPrefs(context).edit();
editor.putInt(WebApkSharedPreferences.PREF_SPLASH_WIDTH, splashWidth);
editor.putInt(WebApkSharedPreferences.PREF_SPLASH_HEIGHT, splashHeight);
editor.apply();
sEncodingFormat = encodingFormat;
getAndSetCachedData(splashBytes);
}
public static void clearCache() {
getAndSetCachedData(null);
}
/**
* Sets the cached splash screen screenshot and returns the old one.
* Thread safety: Can be called from any thread.
*/
private static byte[] getAndSetCachedData(byte[] newSplashBytes) {
ExpiringData newData = null;
if (newSplashBytes != null) {
newData = new ExpiringData(newSplashBytes, SplashContentProvider::clearCache);
}
ExpiringData oldCachedData = sCachedSplashBytes.getAndSet(newData);
if (oldCachedData == null) return null;
oldCachedData.removeCallbacks();
return oldCachedData.getCachedData();
}
@Override
public boolean onCreate() {
mContentProviderUri =
WebApkCommonUtils.generateSplashContentProviderUri(getContext().getPackageName());
return true;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
if (uri != null && uri.toString().equals(mContentProviderUri)) {
return openPipeHelper(null, null, null, null, this);
}
return null;
}
@Override
public void writeDataToPipe(
ParcelFileDescriptor output, Uri uri, String mimeType, Bundle opts, Void unused) {
try (OutputStream out = new FileOutputStream(output.getFileDescriptor())) {
byte[] cachedSplashBytes = getAndSetCachedData(null);
if (cachedSplashBytes != null) {
out.write(cachedSplashBytes);
} else {
// One way that this case gets hit is when the WebAPK is brought to the foreground
// via Android Recents after the Android OOM killer has killed the host browser but
// not SplashActivity.
Bitmap splashScreenshot = recreateAndScreenshotSplash();
if (splashScreenshot != null) {
sEncodingFormat = SplashUtils.selectBitmapEncoding(
splashScreenshot.getWidth(), splashScreenshot.getHeight());
splashScreenshot.compress(sEncodingFormat, 100, out);
}
}
out.flush();
} catch (Exception e) {
}
}
@Override
public String getType(Uri uri) {
if (uri != null && uri.toString().equals(mContentProviderUri)) {
if (sEncodingFormat == null) {
Context context = getContext().getApplicationContext();
SharedPreferences prefs = WebApkSharedPreferences.getPrefs(context);
int splashWidth = prefs.getInt(WebApkSharedPreferences.PREF_SPLASH_WIDTH, -1);
int splashHeight = prefs.getInt(WebApkSharedPreferences.PREF_SPLASH_HEIGHT, -1);
sEncodingFormat = SplashUtils.selectBitmapEncoding(splashWidth, splashHeight);
}
if (sEncodingFormat == Bitmap.CompressFormat.PNG) {
return "image/png";
} else if (sEncodingFormat == Bitmap.CompressFormat.JPEG) {
return "image/jpeg";
}
}
return null;
}
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
throw new UnsupportedOperationException();
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
throw new UnsupportedOperationException();
}
/** Builds splashscreen at size that it was last displayed and screenshots it. */
private Bitmap recreateAndScreenshotSplash() {
Context context = getContext().getApplicationContext();
SharedPreferences prefs = WebApkSharedPreferences.getPrefs(context);
int splashWidth = prefs.getInt(WebApkSharedPreferences.PREF_SPLASH_WIDTH, -1);
int splashHeight = prefs.getInt(WebApkSharedPreferences.PREF_SPLASH_HEIGHT, -1);
return SplashUtils.createAndImmediatelyScreenshotSplashView(
context, splashWidth, splashHeight, MAX_TRANSFER_SIZE_BYTES);
}
}
| bsd-3-clause |
rokn/Count_Words_2015 | testing/spring-boot-master/spring-boot-cli/src/it/java/org/springframework/boot/cli/WarCommandIT.java | 2276 | /*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli;
import java.io.File;
import org.junit.Test;
import org.springframework.boot.cli.command.archive.WarCommand;
import org.springframework.boot.cli.infrastructure.CommandLineInvoker;
import org.springframework.boot.cli.infrastructure.CommandLineInvoker.Invocation;
import org.springframework.boot.loader.tools.JavaExecutable;
import org.springframework.util.SocketUtils;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Integration test for {@link WarCommand}.
*
* @author Andrey Stolyarov
*/
public class WarCommandIT {
private final CommandLineInvoker cli = new CommandLineInvoker(
new File("src/it/resources/war-command"));
@Test
public void warCreation() throws Exception {
int port = SocketUtils.findAvailableTcpPort();
File war = new File("target/test-app.war");
Invocation invocation = this.cli.invoke("war", war.getAbsolutePath(),
"war.groovy");
invocation.await();
assertTrue(war.exists());
Process process = new JavaExecutable()
.processBuilder("-jar", war.getAbsolutePath(), "--server.port=" + port)
.start();
invocation = new Invocation(process);
invocation.await();
assertThat(invocation.getErrorOutput(), containsString("onStart error"));
assertThat(invocation.getStandardOutput(), containsString("Tomcat started"));
assertThat(invocation.getStandardOutput(),
containsString("/WEB-INF/lib-provided/tomcat-embed-core"));
assertThat(invocation.getStandardOutput(),
containsString("/WEB-INF/lib-provided/tomcat-embed-core"));
process.destroy();
}
}
| mit |
yy1300326388/iBooks | src/org/ebookdroid/core/curl/PageAnimator.java | 621 | package org.ebookdroid.core.curl;
import org.ebookdroid.common.touch.IGestureDetector;
import org.ebookdroid.core.EventDraw;
import org.ebookdroid.core.Page;
import org.ebookdroid.core.ViewState;
public interface PageAnimator extends IGestureDetector {
PageAnimationType getType();
void init();
void resetPageIndexes(final int currentIndex);
void draw(EventDraw event);
void setViewDrawn(boolean b);
void flipAnimationStep();
boolean isPageVisible(final Page page, final ViewState viewState);
void pageUpdated(ViewState viewState, Page page);
void animate(int direction);
}
| mit |
anushabala/sempre | src/edu/stanford/nlp/sempre/test/ParserTest.java | 5780 | package edu.stanford.nlp.sempre.test;
import edu.stanford.nlp.sempre.*;
import fig.basic.LogInfo;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
import static org.testng.AssertJUnit.assertEquals;
/**
* Test parsers.
*
* @author Roy Frostig
* @author Percy Liang
*/
public class ParserTest {
// Collects a grammar, and some input/output test pairs
public abstract static class ParseTest {
public Grammar grammar;
ParseTest(Grammar g) {
this.grammar = g;
}
public Parser.Spec getParserSpec() {
Executor executor = new JavaExecutor();
FeatureExtractor extractor = new FeatureExtractor(executor);
FeatureExtractor.opts.featureDomains.add("rule");
ValueEvaluator valueEvaluator = new ExactValueEvaluator();
return new Parser.Spec(grammar, extractor, executor, valueEvaluator);
}
public abstract void test(Parser parser);
}
private static void checkNumDerivations(Parser parser, Params params, String utterance, String targetValue, int numExpected) {
Parser.opts.verbose = 5;
Example ex = TestUtils.makeSimpleExample(utterance, targetValue != null ? Value.fromString(targetValue) : null);
ParserState state = parser.parse(params, ex, targetValue != null);
// Debug information
for (Derivation deriv : state.predDerivations) {
LogInfo.dbg(deriv.getAllFeatureVector());
LogInfo.dbg(params.getWeights());
LogInfo.dbgs("Score %f", deriv.computeScore(params));
}
// parser.extractor.extractLocal();
assertEquals(numExpected, ex.getPredDerivations().size());
if (numExpected > 0 && targetValue != null)
assertEquals(targetValue, ex.getPredDerivations().get(0).value.toString());
}
private static void checkNumDerivations(Parser parser, String utterance, String targetValue, int numExpected) {
checkNumDerivations(parser, new Params(), utterance, targetValue, numExpected);
}
static ParseTest ABCTest() {
return new ParseTest(TestUtils.makeAbcGrammar()) {
@Override
public void test(Parser parser) {
checkNumDerivations(parser, "a +", null, 0);
checkNumDerivations(parser, "a", "(string a)", 1);
checkNumDerivations(parser, "a b", "(string a,b)", 1);
checkNumDerivations(parser, "a b c", "(string a,b,c)", 2);
checkNumDerivations(parser, "a b c a b c", "(string a,b,c,a,b,c)", 42);
}
};
}
static ParseTest ArithmeticTest() {
return new ParseTest(TestUtils.makeArithmeticGrammar()) {
@Override
public void test(Parser parser) {
checkNumDerivations(parser, "1 + ", null, 0);
checkNumDerivations(parser, "1 plus 2", "(number 3)", 1);
checkNumDerivations(parser, "2 times 3", "(number 6)", 1);
checkNumDerivations(parser, "1 plus times 3", null, 0);
checkNumDerivations(parser, "times", null, 0);
}
};
};
// Create parsers
@Test public void checkBeamNumDerivationsForABCGrammar() {
Parser.opts.coarsePrune = false;
ParseTest p;
p = ABCTest();
p.test(new BeamParser(p.getParserSpec()));
p = ArithmeticTest();
p.test(new BeamParser(p.getParserSpec()));
}
@Test public void checkCoarseBeamNumDerivations() {
Parser.opts.coarsePrune = true;
ParseTest p;
p = ABCTest();
p.test(new BeamParser(p.getParserSpec()));
p = ArithmeticTest();
p.test(new BeamParser(p.getParserSpec()));
}
@Test(groups = "reinforcement") public void checkReinforcementNumDerivations() {
ParseTest p;
p = ABCTest();
p.test(new ReinforcementParser(p.getParserSpec()));
p = ArithmeticTest();
p.test(new ReinforcementParser(p.getParserSpec()));
// TODO(chaganty): test more thoroughly
}
@Test public void checkFloatingNumDerivations() {
// Make it behave like the BeamParser
FloatingParser.opts.defaultIsFloating = false;
ParseTest p;
p = ABCTest();
p.test(new FloatingParser(p.getParserSpec()));
p = ArithmeticTest();
p.test(new FloatingParser(p.getParserSpec()));
// If floating, should get more hypotheses
FloatingParser.opts.defaultIsFloating = true;
Parser parser = new FloatingParser(ABCTest().getParserSpec());
FloatingParser.opts.maxDepth = 2;
checkNumDerivations(parser, "ignore", null, 3);
FloatingParser.opts.maxDepth = 3;
checkNumDerivations(parser, "ignore", null, 3 + 3 * 3);
}
// TODO(chaganty): verify that things are ranked appropriately
public void checkRankingArithmetic(Parser parser) {
Params params = new Params();
Map<String, Double> features = new HashMap<>();
features.put("rule :: $Operator -> and (ConstantFn (lambda y (lambda x (call + (var x) (var y)))))", 1.0);
features.put("rule :: $Operator -> and (ConstantFn (lambda y (lambda x (call * (var x) (var y)))))", -1.0);
params.update(features);
checkNumDerivations(parser, params, "2 and 3", "(number 5)", 2);
params = new Params();
features.put("rule :: $Operator -> and (ConstantFn (lambda y (lambda x (call + (var x) (var y)))))", -1.0);
features.put("rule :: $Operator -> and (ConstantFn (lambda y (lambda x (call * (var x) (var y)))))", 1.0);
params.update(features);
checkNumDerivations(parser, params, "2 and 3", "(number 6)", 2);
}
@Test void checkRankingSimple() {
checkRankingArithmetic(new BeamParser(ArithmeticTest().getParserSpec()));
}
@Test void checkRankingReinforcement() {
checkRankingArithmetic(new ReinforcementParser(ArithmeticTest().getParserSpec()));
}
@Test void checkRankingFloating() {
FloatingParser.opts.defaultIsFloating = false;
checkRankingArithmetic(new FloatingParser(ArithmeticTest().getParserSpec()));
}
// TODO(chaganty): verify the parser gradients
}
| gpl-2.0 |
jvanz/core | qadevOOo/tests/java/ifc/sheet/_XDataPilotFieldGrouping.java | 2417 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package ifc.sheet;
import com.sun.star.container.XNameAccess;
import com.sun.star.sheet.DataPilotFieldGroupBy;
import com.sun.star.sheet.DataPilotFieldGroupInfo;
import com.sun.star.sheet.XDataPilotField;
import com.sun.star.sheet.XDataPilotFieldGrouping;
import com.sun.star.uno.UnoRuntime;
import lib.MultiMethodTest;
public class _XDataPilotFieldGrouping extends MultiMethodTest
{
public XDataPilotFieldGrouping oObj = null;
public void _createNameGroup() {
boolean result = true;
try {
XDataPilotField xDataPilotField = UnoRuntime.queryInterface(XDataPilotField.class, oObj);
XNameAccess xNameAccess = UnoRuntime.queryInterface(XNameAccess.class, xDataPilotField.getItems ());
String[] elements = xNameAccess.getElementNames ();
oObj.createNameGroup(elements);
} catch (com.sun.star.lang.IllegalArgumentException e) {
log.println("Exception while checking createNameGroup"+e);
result = false;
}
tRes.tested ("createNameGroup()",result);
}
public void _createDateGroup() {
boolean result = true;
try {
DataPilotFieldGroupInfo aInfo = new DataPilotFieldGroupInfo();
aInfo.GroupBy = DataPilotFieldGroupBy.MONTHS;
aInfo.HasDateValues = true;
oObj.createDateGroup(aInfo);
} catch (com.sun.star.lang.IllegalArgumentException e) {
log.println("Exception while checking createDateGroup"+e);
result = false;
}
tRes.tested ("createDateGroup()",result);
}
}
| gpl-3.0 |
andy32323/inspectIT | inspectIT/src/info/novatec/inspectit/rcp/validation/InputValidatorControlDecoration.java | 2842 | package info.novatec.inspectit.rcp.validation;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IMessageManager;
/**
* {@link ValidationControlDecoration} that uses {@link InputValidatorControlDecoration} for
* determining if input is valid and for setting the correct error message.
*
* @author Ivan Senic
*
*/
public class InputValidatorControlDecoration extends ValidationControlDecoration<Text> {
/**
* {@link IInputValidator} that performs validation.
*/
private final IInputValidator inputValidator;
/**
* Default constructor. Uses message manager if supplied to handle messages.
*
* @param control
* Control to decorate.
* @param messageManager
* Message manager to report to. Can be <code>null</code>
* @param inputValidator
* {@link IInputValidator} that performs validation.
* @see ControlDecoration
*/
public InputValidatorControlDecoration(Text control, IMessageManager messageManager, IInputValidator inputValidator) {
this(control, messageManager, null, inputValidator);
}
/**
* Alternative constructor. Does not use message manager to report messages. Registers listener
* to the list of validation listeners.
*
* @param control
* Control to decorate.
* @param listener
* {@link IControlValidationListener}.
* @param inputValidator
* {@link IInputValidator} that performs validation.
*/
public InputValidatorControlDecoration(Text control, IControlValidationListener listener, IInputValidator inputValidator) {
this(control, null, listener, inputValidator);
}
/**
* Constructor allowing to set all properties. Registers listener to the list of validation
* listeners.
*
* @param control
* Control to decorate.
* @param messageManager
* Message manager to report to. Can be <code>null</code>
* @param listener
* {@link IControlValidationListener}.
* @param inputValidator
* {@link IInputValidator} that performs validation.
*/
public InputValidatorControlDecoration(Text control, IMessageManager messageManager, IControlValidationListener listener, IInputValidator inputValidator) {
super(control, messageManager, listener);
Assert.isNotNull(inputValidator);
this.inputValidator = inputValidator;
startupValidation();
}
/**
* {@inheritDoc}
*/
@Override
protected boolean validate(Text control) {
if (null == inputValidator) {
return true;
}
String errorMessage = inputValidator.isValid(control.getText());
if (null != errorMessage) {
setDescriptionText(errorMessage);
return false;
} else {
return true;
}
}
}
| agpl-3.0 |
f24-ag/tigase | src/test/java/tigase/cluster/api/ClusterElementTest.java | 2508 | /*
* ClusterElementTest.java
*
* Tigase Jabber/XMPP Server
* Copyright (C) 2004-2012 "Artur Hefczyc" <artur.hefczyc@tigase.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tigase.cluster.api;
//~--- non-JDK imports --------------------------------------------------------
import junit.framework.TestCase;
import org.junit.Test;
import tigase.xml.DomBuilderHandler;
import tigase.xml.Element;
import tigase.xml.SimpleParser;
/**
*
* @author andrzej
*/
public class ClusterElementTest
extends TestCase {
/**
* Method description
*
*/
@Test
@SuppressWarnings("deprecation")
public void testGetMethodName() {
SimpleParser parser = new SimpleParser();
DomBuilderHandler handler = new DomBuilderHandler();
char[] data =
"<cluster to=\"sess-man@blue\" type=\"set\" id=\"cl-6627\" xmlns=\"tigase:cluster\" from=\"sess-man@green\"><control><visited-nodes><node-id>sess-man@green</node-id></visited-nodes><method-call name=\"packet-forward-sm-cmd\"/><first-node>sess-man@green</first-node></control><data><presence to=\"test2@test\" xmlns=\"jabber:client\" from=\"test1@test/test\"><status/><priority>5</priority></presence></data></cluster>".toCharArray();
parser.parse(handler, data, 0, data.length);
Element elem = handler.getParsedElements().poll();
assertEquals(
"packet-forward-sm-cmd",
elem.findChild("/cluster/control/method-call").getAttributeStaticStr("name"));
// assertEquals("cluster/control/method-call".split("/"),
// ClusterElement.CLUSTER_METHOD_PATH);
ClusterElement clElem = new ClusterElement(elem);
assertEquals("packet-forward-sm-cmd", clElem.getMethodName());
}
}
//~ Formatted in Tigase Code Convention on 13/02/20
| agpl-3.0 |
cgvarela/tigase-server | src/main/izpack/java/TigaseConfigLoadPanel.java | 14160 | /*
* Tigase Jabber/XMPP Server
* Copyright (C) 2004-2012 "Artur Hefczyc" <artur.hefczyc@tigase.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
* $Rev$
* Last modified by $Author$
* $Date$
*/
package com.izforge.izpack.panels;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import com.izforge.izpack.gui.IzPanelLayout;
import com.izforge.izpack.gui.LabelFactory;
import com.izforge.izpack.installer.AutomatedInstallData;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.InstallerFrame;
import com.izforge.izpack.installer.IzPanel;
import com.izforge.izpack.util.Debug;
/**
* The Hello panel class.
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class TigaseConfigLoadPanel extends IzPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextArea textArea = null;
/**
* The constructor.
*
* @param parent The parent.
* @param idata The installation data.
*/
public TigaseConfigLoadPanel(InstallerFrame parent, InstallData idata) {
super(parent, TigaseInstallerCommon.init(idata), new IzPanelLayout());
// The config label.
add(LabelFactory.create(parent.langpack.getString("TigaseConfigLoadPanel.info"),
parent.icons.getImageIcon("edit"), LEADING), NEXT_LINE);
// The text area which shows the info.
textArea = new JTextArea("");
textArea.setCaretPosition(0);
textArea.setEditable(false);
JScrollPane scroller = new JScrollPane(textArea);
add(scroller, NEXT_LINE);
// At end of layouting we should call the completeLayout method also they do nothing.
getLayoutHelper().completeLayout();
}
public void panelActivate() {
super.panelActivate();
// Existing configuration loading
Debug.trace("panelActivate called for load pael");
String config = new TigaseConfigLoadHelper().loadConfig(idata);
textArea.setText(config);
}
/**
* Indicates whether the panel has been validated or not.
*
* @return Always true.
*/
public boolean isValidated() {
return true;
}
}
class TigaseConfigLoadHelper {
String loadConfig(AutomatedInstallData idata) {
// Try to read the config file.
File configPath = null;
StringBuilder config = new StringBuilder();
try {
if (idata.getVariable("searchTigaseHome") == null
|| idata.getVariable("searchTigaseHome").isEmpty()) {
configPath = new File(idata.getVariable("INSTALL_PATH"),
"etc/init.properties");
} else {
configPath = new File(idata.getVariable("searchTigaseHome"),
"etc/init.properties");
}
if (configPath.exists()) {
Properties props = new Properties();
props.load(new FileReader(configPath));
Debug.trace("Loading init.properties file...");
for (String name: props.stringPropertyNames()) {
config.append(name + " = " + props.getProperty(name) + "\n");
}
Debug.trace(config);
Debug.trace("Done.");
Debug.trace("Loading variables....");
for (String name: TigaseConfigConst.tigaseIzPackMap.keySet()) {
String varName = TigaseConfigConst.tigaseIzPackMap.get(name);
if (varName != null) {
Debug.trace("Loading: " + varName + " = " + props.getProperty(name));
if (varName.equals(TigaseConfigConst.DEBUG)) {
if (props.getProperty(name) != null) {
parseDebugs(props.getProperty(name), idata);
Debug.trace("Loaded: " + varName + " = " + props.getProperty(name));
} else {
Debug.trace("Missing configuration for " + varName);
}
continue;
}
if (varName.equals(TigaseConfigConst.PLUGINS)) {
if (props.getProperty(name) != null) {
parsePlugins(props.getProperty(name), idata);
Debug.trace("Loaded: " + varName + " = " + props.getProperty(name));
} else {
Debug.trace("Missing configuration for " + varName);
}
continue;
}
if (varName.equals(TigaseConfigConst.USER_DB_URI)) {
if (props.getProperty(name) != null) {
parseUserDbUri(props.getProperty(name), idata);
Debug.trace("Loaded: " + varName + " = " + props.getProperty(name));
} else {
Debug.trace("Missing configuration for " + varName);
}
continue;
}
if (varName.equals(TigaseConfigConst.DB_TYPE)) {
if (props.getProperty(name) != null) {
String dbType =
TigaseConfigConst.userDBUriMap.get(props.getProperty(name));
if (dbType == null) {
dbType = "Other";
}
idata.setVariable(TigaseConfigConst.DB_TYPE, dbType);
Debug.trace("Loaded: " + varName + " = " + dbType);
} else {
Debug.trace("Missing configuration for " + varName);
}
continue;
}
if (varName.equals(TigaseConfigConst.AUTH_HANDLE)) {
if (props.getProperty(name) != null) {
idata.setVariable(TigaseConfigConst.AUTH_HANDLE,
props.getProperty(name));
Debug.trace("Loaded: " + varName + " = " + props.getProperty(name));
} else {
Debug.trace("Missing configuration for " + varName);
}
continue;
}
if (varName.equals(TigaseConfigConst.MUC_COMP)) {
for (int i = 1 ; i <= 10 ; i++ ) {
if ((props.getProperty("--comp-name-" + i) != null
&& props.getProperty("--comp-name-" + i).equals("muc"))) {
idata.setVariable(TigaseConfigConst.MUC_COMP, "on");
}}
Debug.trace("Loaded: " + varName + " = " +
idata.getVariable(TigaseConfigConst.MUC_COMP));
continue;
}
if (varName.equals(TigaseConfigConst.PUBSUB_COMP)) {
for (int i = 1 ; i <= 10 ; i++ ) {
if ((props.getProperty("--comp-name-" + i) != null
&& props.getProperty("--comp-name-" + i).equals("pubsub"))) {
idata.setVariable(TigaseConfigConst.PUBSUB_COMP, "on");
}}
Debug.trace("Loaded: " + varName + " = " +
idata.getVariable(TigaseConfigConst.PUBSUB_COMP));
continue;
}
if (varName.equals(TigaseConfigConst.SOCKS5_COMP)) {
for (int i = 1 ; i <= 10 ; i++ ) {
if ((props.getProperty("--comp-name-" + i) != null
&& props.getProperty("--comp-name-" + i).equals("proxy"))) {
idata.setVariable(TigaseConfigConst.SOCKS5_COMP, "on");
}}
Debug.trace("Loaded: " + varName + " = " +
idata.getVariable(TigaseConfigConst.SOCKS5_COMP));
continue;
}
if (varName.equals(TigaseConfigConst.STUN_COMP)) {
for (int i = 1 ; i <= 10 ; i++ ) {
if ((props.getProperty("--comp-name-" + i) != null
&& props.getProperty("--comp-name-" + i).equals("stun"))) {
idata.setVariable(TigaseConfigConst.STUN_COMP, "on");
}}
Debug.trace("Loaded: " + varName + " = " +
idata.getVariable(TigaseConfigConst.STUN_COMP));
continue;
}
if (varName.equals(TigaseConfigConst.HTTP_COMP)) {
for (int i = 1 ; i <= 10 ; i++ ) {
if ((props.getProperty("--comp-name-" + i) != null
&& props.getProperty("--comp-name-" + i).equals("rest"))) {
idata.setVariable(TigaseConfigConst.HTTP_COMP, "on");
}}
Debug.trace("Loaded: " + varName + " = " +
idata.getVariable(TigaseConfigConst.HTTP_COMP));
continue;
}
if (varName.equals(TigaseConfigConst.ARCHIVE_COMP)) {
for (int i = 1 ; i <= 10 ; i++ ) {
if ((props.getProperty("--comp-name-" + i) != null
&& props.getProperty("--comp-name-" + i).equals("message-archive"))) {
idata.setVariable(TigaseConfigConst.ARCHIVE_COMP, "on");
}}
Debug.trace("Loaded: " + varName + " = " +
idata.getVariable(TigaseConfigConst.ARCHIVE_COMP));
continue;
}
if (varName.equals(TigaseConfigConst.AUTH_DB_URI)) {
if (props.getProperty(name) != null) {
parseAuthDbUri(props.getProperty(name), idata);
Debug.trace("Loaded: " + varName + " = " + props.getProperty(name));
} else {
Debug.trace("Missing configuration for " + varName);
}
continue;
}
if (varName.equals(TigaseConfigConst.ACS_MUC_COMP)) {
for (int i = 1 ; i <= 10 ; i++ ) {
if ((props.getProperty("--comp-name-" + i) != null
&& props.getProperty("--comp-class-" + i).equals(TigaseConfigConst.ACS_MUC_COMP_CLASS))) {
idata.setVariable(TigaseConfigConst.ACS_MUC_COMP, "acs");
}
}
Debug.trace("Loaded: " + varName + " = " +
idata.getVariable(TigaseConfigConst.MUC_COMP));
continue;
}
if (varName.equals(TigaseConfigConst.ACS_PUBSUB_COMP)) {
for (int i = 1 ; i <= 10 ; i++ ) {
if ((props.getProperty("--comp-name-" + i) != null
&& props.getProperty("--comp-class-" + i).equals(TigaseConfigConst.ACS_PUBSUB_COMP_CLASS))) {
idata.setVariable(TigaseConfigConst.ACS_PUBSUB_COMP, "acs");
}
}
Debug.trace("Loaded: " + varName + " = " +
idata.getVariable(TigaseConfigConst.PUBSUB_COMP));
continue;
}
if (varName.equals(TigaseConfigConst.ACS_COMP)) {
if ((props.getProperty("--sm-cluster-strategy-class") != null
&& props.getProperty("--sm-cluster-strategy-class").equals(TigaseConfigConst.ACS_COMP_CLASS))) {
idata.setVariable(TigaseConfigConst.ACS_COMP, "on");
} else {
idata.setVariable(TigaseConfigConst.ACS_COMP, "off");
}
Debug.trace("Loaded: " + varName + " = " +
idata.getVariable(TigaseConfigConst.ACS_COMP));
continue;
}
if (props.getProperty(name) != null) {
idata.setVariable(varName, props.getProperty(name));
}
}
}
Debug.trace("Done.");
} else {
config.append("The config file: " + configPath + " seems to not exist...");
}
} catch (Exception err) {
StringBuilder errorConfig = new StringBuilder();
errorConfig.append("Error : could not load the config file: " + configPath + "\n");
errorConfig.append(err.toString() + "\n");
for (StackTraceElement ste: err.getStackTrace()) {
errorConfig.append(ste.toString() + "\n");
}
return errorConfig.toString();
}
return config.toString();
}
private void parseDebugs(String debugs, AutomatedInstallData idata) {
String[] ardebugs = debugs.split(",");
Set<String> knownDebugs = TigaseConfigConst.debugMap.keySet();
for (String debug: ardebugs) {
if (knownDebugs.contains(debug)) {
idata.setVariable(TigaseConfigConst.debugMap.get(debug), debug);
}
}
}
private void parsePlugins(String plugins, AutomatedInstallData idata) {
String[] arplugins = plugins.split(",");
Set<String> knownPlugins = TigaseConfigConst.pluginsMap.keySet();
for (String plugin: arplugins) {
if (knownPlugins.contains(plugin)) {
idata.setVariable(TigaseConfigConst.pluginsMap.get(plugin), plugin);
}
}
}
private static Pattern dbUriPattern =
Pattern.compile(
"jdbc:([^:]+(:[^:]+)?):(//([^/]+))?/?([0-9.a-zA-Z_/-]+)[;\\?]?(user=([^;&]+))?[;&]?(password=([^;&]+))?[;&]?(.*)");
private void parseUserDbUri(String dbUri, AutomatedInstallData idata) {
Matcher m = dbUriPattern.matcher(dbUri);
if (m.matches()) {
String jdbcDriver = m.group(1);
String host = m.group(4);
String dbName = m.group(5);
String userName = m.group(7);
String userPass = m.group(9);
String otherPars = m.group(10);
// idata.setVariable(TigaseConfigConst.DB_TYPE,
// TigaseConfigConst.userDBUriMap.get(jdbcDriver));
if (jdbcDriver.equals("mysql")) {
idata.setVariable("dbSuperuser", "root");
}
if (jdbcDriver.equals("postgresql")) {
idata.setVariable("dbSuperuser", "postgres");
}
if (jdbcDriver.equals("sqlserver")) {
idata.setVariable("dbSuperuser", "root");
}
if (host != null) {
idata.setVariable("dbHost", host);
}
if (dbName != null) {
if (jdbcDriver.equals("derby")) {
idata.setVariable("DerbyDBPath", "/" + dbName);
Debug.trace("DerbyDBPath set to /" + dbName);
} else {
idata.setVariable("dbName", dbName);
Debug.trace("dbName read: " + dbName);
}
}
if (userName != null) {
idata.setVariable("dbUser", userName);
}
if (userPass != null) {
idata.setVariable("dbPass", userPass);
}
if (otherPars != null) {
idata.setVariable("dbParams", otherPars);
}
} else {
Debug.trace("Hm, the dbUri doesn't match regex: " + dbUri);
}
}
private void parseAuthDbUri(String dbUri, AutomatedInstallData idata) {
Matcher m = dbUriPattern.matcher(dbUri);
if (m.matches()) {
String jdbcDriver = m.group(1);
String host = m.group(4);
String dbName = m.group(5);
String userName = m.group(7);
String userPass = m.group(9);
String otherPars = m.group(10);
if (jdbcDriver != null) {
idata.setVariable("dbAuthType", jdbcDriver);
}
if (host != null) {
idata.setVariable("dbAuthHost", host);
}
if (dbName != null) {
idata.setVariable("dbAuthName", dbName);
}
if (userName != null) {
idata.setVariable("dbAuthUser", userName);
}
if (userPass != null) {
idata.setVariable("dbAuthPass", userPass);
}
if (otherPars != null) {
idata.setVariable("dbAuthParams", otherPars);
}
} else {
Debug.trace("Hm, the dbAuthUri doesn't match regex: " + dbUri);
}
}
}
| agpl-3.0 |
xasx/wildfly | testsuite/integration/legacy-ejb-client/src/test/java/org/jboss/as/test/integration/legacy/ejb/remote/client/api/EchoRemote.java | 1393 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.legacy.ejb.remote.client.api;
import java.util.concurrent.Future;
/**
* User: jpai
*/
public interface EchoRemote {
String echo(String message);
Future<String> asyncEcho(String message, long delayInMilliSec);
EchoRemote getBusinessObject();
boolean testRequestScopeActive();
ValueWrapper getValue();
}
| lgpl-2.1 |
yersan/wildfly-core | core-model-test/framework/src/main/java/org/jboss/as/core/model/test/KernelServicesBuilder.java | 7143 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.core.model.test;
import java.io.IOException;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.ModelVersion;
import org.jboss.as.model.test.ModelTestControllerVersion;
import org.jboss.dmr.ModelNode;
/**
* A builder to create a controller and initialize it with the passed in subsystem xml or boot operations.
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
*/
public interface KernelServicesBuilder {
/**
* The default is to validate the operations sent in to the model controller. Turn it off call this method
*
* @return this builder
*/
KernelServicesBuilder setDontValidateOperations();
/**
* By default the description is not validated. Call this to validates the full model description minus what is set up by {@link KnownIssuesValidationConfiguration}
*
* @return this builder
*/
KernelServicesBuilder validateDescription();
/**
* Register an arbitrary descriptor for description validation.
*
* @return this builder
*/
KernelServicesBuilder registerAttributeArbitraryDescriptor(ModelNode address, String attribute, String descriptor);
/**
* Register an arbitrary descriptor for description validation.
*
* @return this builder
*/
KernelServicesBuilder registerArbitraryDescriptorForOperationParameter(ModelNode address, String operation, String parameter, String descriptor);
/**
* Sets the subsystem xml resource containing the xml to be parsed to create the boot operations used to initialize the controller. The resource is loaded using similar
* semantics to {@link Class#getResource(String)}
* @param resource the resource with subsystem xml
* @return this builder
* @throws IllegalStateException if {@link #setBootOperations(List)}, {@link #setXml(String)} (String)} or {@link #setXmlResource(String)} (String)} have
* already been called
* @throws IllegalStateException if {@link #build()} has already been called
* @throws IOException if there were problems reading the resource
* @throws XMLStreamException if there were problems parsing the xml
*/
KernelServicesBuilder setXmlResource(String resource) throws IOException, XMLStreamException;
/**
* Sets the subsystem xml to be parsed to create the boot operations used to initialize the controller
* @param subsystemXml the subsystem xml
* @return this builder
* @throws IllegalStateException if {@link #setBootOperations(List)}, {@link #setSubsystemXml(String)} or {@link #setSubsystemXmlResource(String)} have
* already been called
* @throws IllegalStateException if {@link #build()} has already been called
* @throws XMLStreamException if there were problems parsing the xml
*/
KernelServicesBuilder setXml(String subsystemXml) throws XMLStreamException;
/**
* Sets the boot operations to be used to initialize the controller
* @param bootOperations the boot operations
* @return this builder
* @throws IllegalStateException if {@link #setBootOperations(List)}, {@link #setSubsystemXml(String)} or {@link #setSubsystemXmlResource(String)} have
* @throws IllegalStateException if {@link #build()} has already been called
* already been called
*/
KernelServicesBuilder setBootOperations(List<ModelNode> bootOperations);
/**
* Adds a model initializer which can be used to initialize the model before executing the boot operations, and a model write sanitizer
* which can be used to remove resources from the model for the xml comparison tests.
*
* @param modelInitializer the model initilizer
* @param modelWriteSanitizer the model write sanitizer
* @return this builder
* @throws IllegalStateException if the model initializer was already set or if {@link #build()} has already been called
*/
KernelServicesBuilder setModelInitializer(ModelInitializer modelInitializer, ModelWriteSanitizer modelWriteSanitizer);
KernelServicesBuilder createContentRepositoryContent(String hash);
/**
* Creates a new legacy kernel services initializer used to configure a new controller containing an older version of the subsystem being tested.
* When {@link #build()} is called any legacy controllers will be created as well.
*
* @param modelVersion The model version of the legacy subsystem
* @param testControllerVersion the version of the legacy controller to load up
* @return the legacy kernel services initializer
* @throws IllegalStateException if {@link #build()} has already been called
*/
LegacyKernelServicesInitializer createLegacyKernelServicesBuilder(ModelVersion modelVersion, ModelTestControllerVersion testControllerVersion);
/**
* Creates the controller and initializes it with the passed in configuration options.
* If {@link #createLegacyKernelServicesBuilder(org.jboss.as.controller.ModelVersion, org.jboss.as.core.model.test.LegacyKernelServicesInitializer.TestControllerVersion)} (ModelVersion)} was called kernel services will be created for the legacy subsystem
* controllers as well, accessible from {@link KernelServices#getLegacyServices(ModelVersion)} on the created {@link KernelServices}
*
* @return the kernel services wrapping the controller
*/
KernelServices build() throws Exception;
/**
* Parses the given xml into operations. This may be called after {@link #build()} has been called.
*
* @param xml a string containing the xml
* @return the parsed operations
*/
List<ModelNode> parseXml(String xml) throws Exception;
/**
* Parses the given xml into operations. The resource is loaded using similar semantics to {@link Class#getResource(String)}.
* This may be called after {@link #build()} has been called.
*
* @param xml a string containing the xml resource
* @return the parsed operations
*/
List<ModelNode> parseXmlResource(String xmlResource) throws Exception;
}
| lgpl-2.1 |
xasx/wildfly | testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/interceptor/method/ClassifiedBean.java | 1633 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ejb.interceptor.method;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
/**
* @author Stuart Douglas
*/
@Stateless
@Interceptors(SecretInterceptor.class)
public class ClassifiedBean {
public String secretMethod() {
return "Secret";
}
@Interceptors(TopSecretInterceptor.class)
public String topSecretMethod() {
return "TopSecret";
}
public String overloadedMethod(Integer i) {
return "ArgInt:" + i.toString();
}
public String overloadedMethod(String str) {
return "ArgStr:" + str;
}
}
| lgpl-2.1 |
xasx/wildfly | appclient/src/main/java/org/jboss/as/appclient/subsystem/AppClientServerConfiguration.java | 3558 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.appclient.subsystem;
import java.util.ArrayList;
import java.util.List;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.dmr.ModelNode;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
/**
* Class that contains the static application client server configuration
*
* @author Stuart Douglas
*/
class AppClientServerConfiguration {
private AppClientServerConfiguration() {
}
public static List<ModelNode> serverConfiguration(final String filePath, final String deploymentName, final String hostUrl, final String propertiesFileUrl, final List<String> parameters, List<ModelNode> xmlNodes) {
List<ModelNode> ret = new ArrayList<ModelNode>();
for (final ModelNode node : xmlNodes) {
ret.add(node);
}
appclient(ret, filePath, deploymentName, hostUrl, propertiesFileUrl, parameters);
return ret;
}
private static void appclient(List<ModelNode> nodes, final String filePath, final String deploymentName, final String hostUrl, final String propertiesFileUrl, final List<String> parameters) {
loadExtension(nodes, "org.jboss.as.appclient");
ModelNode add = Util.createAddOperation(PathAddress.pathAddress(AppClientExtension.SUBSYSTEM_PATH));
add.get(Constants.FILE).set(filePath);
if (deploymentName != null) {
add.get(Constants.DEPLOYMENT).set(deploymentName);
}
if (parameters.isEmpty()) {
add.get(Constants.PARAMETERS).setEmptyList();
} else {
for (String param : parameters) {
add.get(Constants.PARAMETERS).add(param);
}
}
if(hostUrl != null) {
add.get(Constants.HOST_URL).set(hostUrl);
}
if(propertiesFileUrl != null) {
add.get(Constants.CONNECTION_PROPERTIES_URL).set(propertiesFileUrl);
}
nodes.add(add);
}
private static void loadExtension(List<ModelNode> nodes, String moduleName) {
final ModelNode add = new ModelNode();
add.get(OP_ADDR).set(new ModelNode().setEmptyList()).add(EXTENSION, moduleName);
add.get(OP).set(ADD);
nodes.add(add);
}
}
| lgpl-2.1 |
xasx/wildfly | testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/ejb/security/authorization/AnnOnlyCheckSLSBForInjection.java | 2117 | /*
* JBoss, Home of Professional Open Source.
* Copyright (c) 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.ejb.security.authorization;
import org.jboss.ejb3.annotation.SecurityDomain;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
/**
* This is a no-interface session bean which is to be injected.
*
* @author <a href="mailto:jlanik@redhat.com">Jan Lanik</a>.
*/
@Stateless
@SecurityDomain("other")
public class AnnOnlyCheckSLSBForInjection {
public String defaultAccess(String message) {
return message;
}
@RolesAllowed("Role1")
public String roleBasedAccessOne(String message) {
return message;
}
@RolesAllowed({"Role2", "Negative", "No-role"})
public String roleBasedAccessMore(String message) {
return message;
}
@PermitAll
public String permitAll(String message) {
return message;
}
@DenyAll
public String denyAll(String message) {
return message;
}
@RolesAllowed("**")
public String starRoleAllowed(String message) {
return message;
}
}
| lgpl-2.1 |
laki88/carbon-identity | components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/cache/SessionContextCache.java | 5115 | /*
* Copyright (c) 2013, 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.authentication.framework.cache;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore;
import org.wso2.carbon.identity.application.common.cache.BaseCache;
import org.wso2.carbon.identity.application.common.cache.CacheEntry;
import org.wso2.carbon.identity.application.common.cache.CacheKey;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.idp.mgt.util.IdPManagementUtil;
import java.sql.Timestamp;
public class SessionContextCache extends BaseCache<String, CacheEntry> {
private static final String SESSION_CONTEXT_CACHE_NAME = "AppAuthFrameworkSessionContextCache";
private static final Log log = LogFactory.getLog(SessionContextCache.class);
private static volatile SessionContextCache instance;
private boolean useCache = true;
private SessionContextCache(String cacheName, int timeout, int capacity) {
super(cacheName, timeout, capacity);
useCache = !Boolean.parseBoolean(IdentityUtil.getProperty(
"JDBCPersistenceManager.SessionDataPersist.Only"));
if (IdentityUtil.getProperty("SessionContextCache.Enable") != null) {
useCache = Boolean.parseBoolean(IdentityUtil.getProperty("SessionContextCache.Enable"));
}
}
public static SessionContextCache getInstance(int timeout) {
if (instance == null) {
synchronized (SessionContextCache.class) {
if (instance == null) {
int capacity = 2000;
try {
String capacityConfigValue = IdentityUtil.getProperty("SessionContextCache.Capacity");
if (StringUtils.isNotBlank(capacityConfigValue)) {
capacity = Integer.parseInt(capacityConfigValue);
}
} catch (NumberFormatException e) {
if (log.isDebugEnabled()) {
log.debug("Ignoring Exception.", e);
}
log.warn("Session context cache capacity size is not configured. Using default value.");
}
instance = new SessionContextCache(SESSION_CONTEXT_CACHE_NAME, timeout, capacity);
}
}
}
return instance;
}
public void addToCache(CacheKey key, CacheEntry entry) {
if (useCache) {
super.addToCache(((SessionContextCacheKey) key).getContextId(), entry);
}
String keyValue = ((SessionContextCacheKey) key).getContextId();
SessionDataStore.getInstance().storeSessionData(keyValue, SESSION_CONTEXT_CACHE_NAME, entry);
}
public CacheEntry getValueFromCache(CacheKey key) {
CacheEntry cacheEntry = null;
if (useCache) {
cacheEntry = super.getValueFromCache(((SessionContextCacheKey) key).getContextId());
}
if (cacheEntry == null) {
String keyValue = ((SessionContextCacheKey) key).getContextId();
SessionContextCacheEntry sessionEntry = (SessionContextCacheEntry) SessionDataStore.getInstance().
getSessionData(keyValue, SESSION_CONTEXT_CACHE_NAME);
Timestamp currentTimestamp = new java.sql.Timestamp(new java.util.Date().getTime());
if (sessionEntry != null && sessionEntry.getContext().isRememberMe() &&
(currentTimestamp.getTime() - SessionDataStore.getInstance().getTimeStamp(keyValue,
SESSION_CONTEXT_CACHE_NAME)
.getTime() <=
IdPManagementUtil.getRememberMeTimeout(CarbonContext.getThreadLocalCarbonContext()
.getTenantDomain())*60*1000)) {
cacheEntry = sessionEntry;
}
}
return cacheEntry;
}
public void clearCacheEntry(CacheKey key) {
if (useCache) {
super.clearCacheEntry(((SessionContextCacheKey) key).getContextId());
}
String keyValue = ((SessionContextCacheKey) key).getContextId();
SessionDataStore.getInstance().clearSessionData(keyValue, SESSION_CONTEXT_CACHE_NAME);
}
}
| apache-2.0 |
bebo/libjitsi | src/org/jitsi/service/configuration/ConfigVetoableChangeListener.java | 653 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jitsi.service.configuration;
import java.beans.*;
import java.util.*;
/**
* This interface uses SC's own ProperteyVetoException.
*/
public interface ConfigVetoableChangeListener extends EventListener
{
/**
* Fired before a Bean's property changes.
*
* @param e the change (containing the old and new values)
* @throws ConfigPropertyVetoException if the change is vetoed by the listener
*/
void vetoableChange(PropertyChangeEvent e) throws ConfigPropertyVetoException;
}
| apache-2.0 |
davidegiannella/jackrabbit-oak | oak-store-document/src/main/java/org/apache/jackrabbit/oak/plugins/document/FailedWithConflictException.java | 1822 | /*
* 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.jackrabbit.oak.plugins.document;
import javax.annotation.Nonnull;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set;
/**
* A {@link CommitFailedException} with a conflict revision.
*/
class FailedWithConflictException extends CommitFailedException {
private static final long serialVersionUID = 2716279884065949789L;
private final Set<Revision> conflictRevisions;
FailedWithConflictException(@Nonnull Set<Revision> conflictRevisions,
@Nonnull String message,
@Nonnull Throwable cause) {
super(OAK, MERGE, 4, checkNotNull(message), checkNotNull(cause));
this.conflictRevisions = checkNotNull(conflictRevisions);
}
/**
* @return the revision of another commit which caused a conflict.
*/
@Nonnull
Set<Revision> getConflictRevisions() {
return conflictRevisions;
}
} | apache-2.0 |
apache/flink | flink-end-to-end-tests/flink-quickstart-test/src/main/java/org/apache/flink/quickstarts/test/Elasticsearch7SinkExample.java | 3254 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.quickstarts.test;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.connector.elasticsearch.sink.Elasticsearch7SinkBuilder;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;
import java.util.HashMap;
import java.util.Map;
/** End to end test for Elasticsearch7Sink. */
public class Elasticsearch7SinkExample {
public static void main(String[] args) throws Exception {
final ParameterTool parameterTool = ParameterTool.fromArgs(args);
if (parameterTool.getNumberOfParameters() < 3) {
System.out.println(
"Missing parameters!\n"
+ "Usage: --numRecords <numRecords> --index <index> --type <type>");
return;
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(5000);
DataStream<String> source =
env.fromSequence(0, parameterTool.getInt("numRecords") - 1)
.map((MapFunction<Long, String>) value -> "message #" + value);
source.sinkTo(
new Elasticsearch7SinkBuilder<String>()
// This instructs the sink to emit after every element, otherwise they would
// be buffered
.setBulkFlushMaxActions(1)
.setHosts(new HttpHost("127.0.0.1", 9200, "http"))
.setEmitter(
(element, context, indexer) ->
indexer.add(createIndexRequest(element, parameterTool)))
.build());
env.execute("Elasticsearch7.x end to end sink test example");
}
private static IndexRequest createIndexRequest(String element, ParameterTool parameterTool) {
Map<String, Object> json = new HashMap<>();
json.put("data", element);
return Requests.indexRequest()
.index(parameterTool.getRequired("index"))
.type(parameterTool.getRequired("type"))
.id(element)
.source(json);
}
}
| apache-2.0 |
Drifftr/devstudio-tooling-bps | plugins/org.eclipse.bpel.ui/src/org/eclipse/bpel/ui/editparts/PartnerLinksEditPart.java | 3748 | /*******************************************************************************
* Copyright (c) 2005, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.bpel.ui.editparts;
import java.util.List;
import org.eclipse.bpel.model.BPELPackage;
import org.eclipse.bpel.model.PartnerLink;
import org.eclipse.bpel.model.PartnerLinks;
import org.eclipse.bpel.ui.BPELEditor;
import org.eclipse.bpel.ui.Messages;
import org.eclipse.bpel.ui.factories.UIObjectFactoryProvider;
import org.eclipse.bpel.ui.util.BatchedMultiObjectAdapter;
import org.eclipse.bpel.ui.util.ModelHelper;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gef.requests.CreationFactory;
/**
* Interface Partners.
*/
public class PartnerLinksEditPart extends BPELTrayCategoryEditPart {
/**
* Only add inbound partners.
*/
@Override
protected List<PartnerLink> getModelChildren() {
return getPartnerLinks().getChildren();
//
// List result = new ArrayList();
// for (Iterator iter = getPartnerLinks().getChildren().iterator(); iter.hasNext();) {
// PartnerLink partner = (PartnerLink) iter.next();
// if (ModelHelper.isInterfacePartnerLink(partner)) {
// result.add(partner);
// }
// }
// return result;
}
// protected Object addEntry() {
// CompoundCommand compound = new CompoundCommand();
// EObject parent = getPartnerLinks();
// final PartnerLink partner = (PartnerLink) getCreationFactory().getNewObject();
// compound.add(new InsertInContainerCommand(parent, partner, null));
// Definition artifactsDefinition = getBPELEditor().getArtifactsDefinition();
// PartnerLinkType plt = PartnerlinktypeFactory.eINSTANCE.createPartnerLinkType();
// Process process = ModelHelper.getProcess(parent);
// compound.add(ModelHelper.getCreatePartnerLinkTypeCommand(process, partner, plt, artifactsDefinition, getRoleKind()));
// getCommandStack().execute(compound);
// // direct edit
// getViewer().getControl().getDisplay().asyncExec(new Runnable() {
// public void run() {
// EditPart part = selectEditPart(partner);
// part.performRequest(new DirectEditRequest());
// }
// });
// return partner;
// }
protected int getRoleKind() {
return ModelHelper.MY_ROLE;
}
protected PartnerLinks getPartnerLinks() {
return (PartnerLinks)getModel();
}
protected EObject getContainer() {
return getPartnerLinks().eContainer();
}
protected BPELEditor getBPELEditor() {
return ModelHelper.getBPELEditor(getContainer());
}
@Override
protected CreationFactory getCreationFactory() {
return UIObjectFactoryProvider.getInstance().getFactoryFor(BPELPackage.eINSTANCE.getPartnerLink());
}
@Override
protected IFigure getAddToolTip() {
return new Label(Messages.PartnerLinksEditPart_0);
}
@Override
protected IFigure getRemoveToolTip() {
return new Label(Messages.PartnerLinksEditPart_1);
}
@Override
protected Adapter createAdapter() {
return new BatchedMultiObjectAdapter() {
@Override
public void finish() {
refresh();
}
@Override
public void notify(Notification n) {
}
};
}
}
| apache-2.0 |