repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
sk163/RocketMQ | rocketmq-common/src/main/java/com/alibaba/rocketmq/common/sysflag/MessageSysFlag.java | 1656 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.rocketmq.common.sysflag;
/**
* @author shijia.wxr
*/
public class MessageSysFlag {
public final static int CompressedFlag = (0x1 << 0);
public final static int MultiTagsFlag = (0x1 << 1);
public final static int TransactionNotType = (0x0 << 2);
public final static int TransactionPreparedType = (0x1 << 2);
public final static int TransactionCommitType = (0x2 << 2);
public final static int TransactionRollbackType = (0x3 << 2);
public static int getTransactionValue(final int flag) {
return flag & TransactionRollbackType;
}
public static int resetTransactionValue(final int flag, final int type) {
return (flag & (~TransactionRollbackType)) | type;
}
public static int clearCompressedFlag(final int flag) {
return flag & (~CompressedFlag);
}
}
| apache-2.0 |
pushtorefresh/storio | storio-content-resolver/src/test/java/com/pushtorefresh/storio3/contentresolver/operations/get/GetCursorStub.java | 4041 | package com.pushtorefresh.storio3.contentresolver.operations.get;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import com.pushtorefresh.storio3.contentresolver.Changes;
import com.pushtorefresh.storio3.contentresolver.StorIOContentResolver;
import com.pushtorefresh.storio3.contentresolver.queries.Query;
import com.pushtorefresh.storio3.test.FlowableBehaviorChecker;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
class GetCursorStub {
@NonNull
final StorIOContentResolver storIOContentResolver;
@NonNull
private final StorIOContentResolver.LowLevel lowLevel;
@NonNull
final Query query;
@NonNull
final GetResolver<Cursor> getResolver;
@NonNull
final Cursor cursor;
@SuppressWarnings("unchecked")
private GetCursorStub() {
storIOContentResolver = mock(StorIOContentResolver.class);
lowLevel = mock(StorIOContentResolver.LowLevel.class);
query = Query.builder()
.uri(mock(Uri.class))
.build();
getResolver = mock(GetResolver.class);
cursor = mock(Cursor.class);
when(storIOContentResolver.lowLevel())
.thenReturn(lowLevel);
when(storIOContentResolver.get())
.thenReturn(new PreparedGet.Builder(storIOContentResolver));
when(getResolver.performGet(storIOContentResolver, query))
.thenReturn(cursor);
when(storIOContentResolver.observeChangesOfUri(query.uri(), BackpressureStrategy.MISSING))
.thenReturn(Flowable.<Changes>empty());
when(getResolver.mapFromCursor(storIOContentResolver, cursor))
.thenReturn(cursor);
}
@NonNull
static GetCursorStub newInstance() {
return new GetCursorStub();
}
void verifyQueryBehaviorForCursor(@NonNull Cursor actualCursor) {
verify(storIOContentResolver).get();
verify(storIOContentResolver).interceptors();
verify(getResolver).performGet(storIOContentResolver, query);
assertThat(actualCursor).isSameAs(cursor);
verify(cursor, never()).close();
verifyNoMoreInteractions(storIOContentResolver, lowLevel, getResolver, cursor);
}
void verifyQueryBehaviorForCursor(@NonNull Flowable<Cursor> flowable) {
new FlowableBehaviorChecker<Cursor>()
.flowable(flowable)
.expectedNumberOfEmissions(1)
.testAction(new Consumer<Cursor>() {
@Override
public void accept(@NonNull Cursor cursor) throws Exception {
// Get Operation should be subscribed to changes of Uri
verify(storIOContentResolver).observeChangesOfUri(query.uri(), BackpressureStrategy.MISSING);
verify(storIOContentResolver).defaultRxScheduler();
verifyQueryBehaviorForCursor(cursor);
}
})
.checkBehaviorOfFlowable();
}
void verifyQueryBehaviorForCursor(@NonNull Single<Cursor> single) {
new FlowableBehaviorChecker<Cursor>()
.flowable(single.toFlowable())
.expectedNumberOfEmissions(1)
.testAction(new Consumer<Cursor>() {
@Override
public void accept(@NonNull Cursor cursor) throws Exception {
verify(storIOContentResolver).defaultRxScheduler();
verifyQueryBehaviorForCursor(cursor);
}
})
.checkBehaviorOfFlowable();
}
}
| apache-2.0 |
dick-the-deployer/dick | dick-web/src/main/java/com/dickthedeployer/dick/web/exception/DickFileMissingException.java | 762 | /*
* Copyright dick the deployer.
*
* 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.dickthedeployer.dick.web.exception;
/**
*
* @author mariusz
*/
public class DickFileMissingException extends Exception {
}
| apache-2.0 |
metlos/hawkular-inventory | hawkular-inventory-rest-api/src/main/java/org/hawkular/inventory/rest/json/ApiError.java | 1814 | /*
* Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.inventory.rest.json;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Return information what failed in the REST-call.
* @author Michael Burman
*/
@ApiModel(description = "If REST-call returns other than success, detailed error is returned.")
public class ApiError {
private final String errorMsg;
private final Object details;
@JsonCreator
public ApiError(@JsonProperty("errorMsg") String errorMsg) {
this(errorMsg, null);
}
@JsonCreator
public ApiError(@JsonProperty("errorMsg") String errorMsg, @JsonProperty("details") Object details) {
this.errorMsg = errorMsg;
this.details = details;
}
@ApiModelProperty("Detailed error message of what happened")
public String getErrorMsg() {
return errorMsg;
}
@ApiModelProperty("Optional details about the error beyond what's provided in the error message.")
public Object getDetails() {
return details;
}
}
| apache-2.0 |
jacksonic/vjlofvhjfgm | src/foam/lib/json/NullParser.java | 330 | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
package foam.lib.json;
import foam.lib.parse.*;
public class NullParser {
private final static Parser instance__ = new Literal("null", null);
public static Parser instance() { return instance__; }
}
| apache-2.0 |
mrjabba/mybatis | src/test/java/com/ibatis/jpetstore/persistence/sqlmapdao/ProductSqlMapDao.java | 1431 | package com.ibatis.jpetstore.persistence.sqlmapdao;
import com.ibatis.common.util.PaginatedList;
import com.ibatis.dao.client.DaoManager;
import com.ibatis.jpetstore.domain.Product;
import com.ibatis.jpetstore.persistence.iface.ProductDao;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class ProductSqlMapDao extends BaseSqlMapDao implements ProductDao {
public ProductSqlMapDao(DaoManager daoManager) {
super(daoManager);
}
public PaginatedList getProductListByCategory(String categoryId) {
return queryForPaginatedList("getProductListByCategory", categoryId, PAGE_SIZE);
}
public Product getProduct(String productId) {
return (Product) queryForObject("getProduct", productId);
}
public PaginatedList searchProductList(String keywords) {
Object parameterObject = new ProductSearch(keywords);
return queryForPaginatedList("searchProductList", parameterObject, PAGE_SIZE);
}
/* Inner Classes */
public static class ProductSearch {
private List keywordList = new ArrayList();
public ProductSearch(String keywords) {
StringTokenizer splitter = new StringTokenizer(keywords, " ", false);
while (splitter.hasMoreTokens()) {
keywordList.add("%" + splitter.nextToken() + "%");
}
}
public List getKeywordList() {
return keywordList;
}
}
}
| apache-2.0 |
wangyum/beam | runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/CombineTranslation.java | 13305 | /*
* 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.beam.runners.core.construction;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.beam.runners.core.construction.PTransformTranslation.COMBINE_TRANSFORM_URN;
import com.google.auto.service.AutoService;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.model.pipeline.v1.RunnerApi.CombinePayload;
import org.apache.beam.model.pipeline.v1.RunnerApi.Components;
import org.apache.beam.model.pipeline.v1.RunnerApi.FunctionSpec;
import org.apache.beam.model.pipeline.v1.RunnerApi.SdkFunctionSpec;
import org.apache.beam.model.pipeline.v1.RunnerApi.SideInput;
import org.apache.beam.runners.core.construction.PTransformTranslation.TransformPayloadTranslator;
import org.apache.beam.sdk.coders.CannotProvideCoderException;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.runners.AppliedPTransform;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.CombineFnBase.GlobalCombineFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.util.AppliedCombineFn;
import org.apache.beam.sdk.util.SerializableUtils;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionView;
/**
* Methods for translating between {@link Combine.PerKey} {@link PTransform PTransforms} and {@link
* RunnerApi.CombinePayload} protos.
*/
public class CombineTranslation {
public static final String JAVA_SERIALIZED_COMBINE_FN_URN = "urn:beam:combinefn:javasdk:v1";
/** A {@link TransformPayloadTranslator} for {@link Combine.PerKey}. */
public static class CombinePayloadTranslator
implements PTransformTranslation.TransformPayloadTranslator<Combine.PerKey<?, ?, ?>> {
public static TransformPayloadTranslator create() {
return new CombinePayloadTranslator();
}
private CombinePayloadTranslator() {}
@Override
public String getUrn(Combine.PerKey<?, ?, ?> transform) {
return COMBINE_TRANSFORM_URN;
}
@Override
public FunctionSpec translate(
AppliedPTransform<?, ?, Combine.PerKey<?, ?, ?>> transform, SdkComponents components)
throws IOException {
return FunctionSpec.newBuilder()
.setUrn(COMBINE_TRANSFORM_URN)
.setPayload(payloadForCombine((AppliedPTransform) transform, components).toByteString())
.build();
}
@Override
public PTransformTranslation.RawPTransform<?, ?> rehydrate(
RunnerApi.PTransform protoTransform, RehydratedComponents rehydratedComponents)
throws IOException {
checkArgument(
protoTransform.getSpec() != null,
"%s received transform with null spec",
getClass().getSimpleName());
checkArgument(protoTransform.getSpec().getUrn().equals(COMBINE_TRANSFORM_URN));
return new RawCombine<>(
CombinePayload.parseFrom(protoTransform.getSpec().getPayload()), rehydratedComponents);
}
/** Registers {@link CombinePayloadTranslator}. */
@AutoService(TransformPayloadTranslatorRegistrar.class)
public static class Registrar implements TransformPayloadTranslatorRegistrar {
@Override
public Map<? extends Class<? extends PTransform>, ? extends TransformPayloadTranslator>
getTransformPayloadTranslators() {
return Collections.singletonMap(Combine.PerKey.class, new CombinePayloadTranslator());
}
@Override
public Map<String, ? extends TransformPayloadTranslator> getTransformRehydrators() {
return Collections.singletonMap(COMBINE_TRANSFORM_URN, new CombinePayloadTranslator());
}
}
}
/**
* These methods drive to-proto translation for both Java SDK transforms and rehydrated
* transforms.
*/
interface CombineLike {
RunnerApi.SdkFunctionSpec getCombineFn();
Coder<?> getAccumulatorCoder();
Map<String, RunnerApi.SideInput> getSideInputs();
}
/** Produces a {@link RunnerApi.CombinePayload} from a portable {@link CombineLike}. */
static RunnerApi.CombinePayload payloadForCombineLike(
CombineLike combine, SdkComponents components) throws IOException {
return RunnerApi.CombinePayload.newBuilder()
.setAccumulatorCoderId(components.registerCoder(combine.getAccumulatorCoder()))
.putAllSideInputs(combine.getSideInputs())
.setCombineFn(combine.getCombineFn())
.build();
}
static <K, InputT, OutputT> CombinePayload payloadForCombine(
final AppliedPTransform<
PCollection<KV<K, InputT>>, PCollection<KV<K, OutputT>>,
Combine.PerKey<K, InputT, OutputT>>
combine,
SdkComponents components)
throws IOException {
return payloadForCombineLike(
new CombineLike() {
@Override
public SdkFunctionSpec getCombineFn() {
return SdkFunctionSpec.newBuilder()
// TODO: Set Java SDK Environment
.setSpec(
FunctionSpec.newBuilder()
.setUrn(JAVA_SERIALIZED_COMBINE_FN_URN)
.setPayload(
ByteString.copyFrom(
SerializableUtils.serializeToByteArray(
combine.getTransform().getFn())))
.build())
.build();
}
@Override
public Coder<?> getAccumulatorCoder() {
GlobalCombineFn<?, ?, ?> combineFn = combine.getTransform().getFn();
try {
return extractAccumulatorCoder(combineFn, (AppliedPTransform) combine);
} catch (CannotProvideCoderException e) {
throw new IllegalStateException(e);
}
}
@Override
public Map<String, SideInput> getSideInputs() {
Map<String, SideInput> sideInputs = new HashMap<>();
for (PCollectionView<?> sideInput : combine.getTransform().getSideInputs()) {
sideInputs.put(
sideInput.getTagInternal().getId(), ParDoTranslation.toProto(sideInput));
}
return sideInputs;
}
},
components);
}
private static class RawCombine<K, InputT, AccumT, OutputT>
extends PTransformTranslation.RawPTransform<
PCollection<KV<K, InputT>>, PCollection<KV<K, OutputT>>>
implements CombineLike {
private final transient RehydratedComponents rehydratedComponents;
private final FunctionSpec spec;
private final CombinePayload payload;
private final Coder<AccumT> accumulatorCoder;
private RawCombine(CombinePayload payload, RehydratedComponents rehydratedComponents) {
this.rehydratedComponents = rehydratedComponents;
this.payload = payload;
this.spec =
FunctionSpec.newBuilder()
.setUrn(COMBINE_TRANSFORM_URN)
.setPayload(payload.toByteString())
.build();
// Eagerly extract the coder to throw a good exception here
try {
this.accumulatorCoder =
(Coder<AccumT>) rehydratedComponents.getCoder(payload.getAccumulatorCoderId());
} catch (IOException exc) {
throw new IllegalArgumentException(
String.format(
"Failure extracting accumulator coder with id '%s' for %s",
payload.getAccumulatorCoderId(), Combine.class.getSimpleName()),
exc);
}
}
@Override
public String getUrn() {
return COMBINE_TRANSFORM_URN;
}
@Nonnull
@Override
public FunctionSpec getSpec() {
return spec;
}
@Override
public RunnerApi.FunctionSpec migrate(SdkComponents sdkComponents) throws IOException {
return RunnerApi.FunctionSpec.newBuilder()
.setUrn(COMBINE_TRANSFORM_URN)
.setPayload(payloadForCombineLike(this, sdkComponents).toByteString())
.build();
}
@Override
public SdkFunctionSpec getCombineFn() {
return payload.getCombineFn();
}
@Override
public Coder<?> getAccumulatorCoder() {
return accumulatorCoder;
}
@Override
public Map<String, SideInput> getSideInputs() {
return payload.getSideInputsMap();
}
}
@VisibleForTesting
static CombinePayload toProto(
AppliedPTransform<?, ?, Combine.PerKey<?, ?, ?>> combine, SdkComponents sdkComponents)
throws IOException {
GlobalCombineFn<?, ?, ?> combineFn = combine.getTransform().getFn();
try {
Coder<?> accumulatorCoder = extractAccumulatorCoder(combineFn, (AppliedPTransform) combine);
Map<String, SideInput> sideInputs = new HashMap<>();
return RunnerApi.CombinePayload.newBuilder()
.setAccumulatorCoderId(sdkComponents.registerCoder(accumulatorCoder))
.putAllSideInputs(sideInputs)
.setCombineFn(toProto(combineFn))
.build();
} catch (CannotProvideCoderException e) {
throw new IllegalStateException(e);
}
}
private static <K, InputT, AccumT> Coder<AccumT> extractAccumulatorCoder(
GlobalCombineFn<InputT, AccumT, ?> combineFn,
AppliedPTransform<PCollection<KV<K, InputT>>, ?, Combine.PerKey<K, InputT, ?>> transform)
throws CannotProvideCoderException {
@SuppressWarnings("unchecked")
PCollection<KV<K, InputT>> mainInput =
(PCollection<KV<K, InputT>>)
Iterables.getOnlyElement(TransformInputs.nonAdditionalInputs(transform));
KvCoder<K, InputT> inputCoder = (KvCoder<K, InputT>) mainInput.getCoder();
return AppliedCombineFn.withInputCoder(
combineFn,
transform.getPipeline().getCoderRegistry(),
inputCoder,
transform.getTransform().getSideInputs(),
((PCollection<?>) Iterables.getOnlyElement(transform.getOutputs().values()))
.getWindowingStrategy())
.getAccumulatorCoder();
}
public static SdkFunctionSpec toProto(GlobalCombineFn<?, ?, ?> combineFn) {
return SdkFunctionSpec.newBuilder()
// TODO: Set Java SDK Environment URN
.setSpec(
FunctionSpec.newBuilder()
.setUrn(JAVA_SERIALIZED_COMBINE_FN_URN)
.setPayload(ByteString.copyFrom(SerializableUtils.serializeToByteArray(combineFn)))
.build())
.build();
}
public static Coder<?> getAccumulatorCoder(
CombinePayload payload, RehydratedComponents components) throws IOException {
String id = payload.getAccumulatorCoderId();
return components.getCoder(id);
}
public static Coder<?> getAccumulatorCoder(AppliedPTransform<?, ?, ?> transform)
throws IOException {
SdkComponents sdkComponents = SdkComponents.create();
String id = getCombinePayload(transform, sdkComponents).getAccumulatorCoderId();
Components components = sdkComponents.toComponents();
return CoderTranslation.fromProto(
components.getCodersOrThrow(id), RehydratedComponents.forComponents(components));
}
public static GlobalCombineFn<?, ?, ?> getCombineFn(CombinePayload payload) throws IOException {
checkArgument(payload.getCombineFn().getSpec().getUrn().equals(JAVA_SERIALIZED_COMBINE_FN_URN));
return (GlobalCombineFn<?, ?, ?>)
SerializableUtils.deserializeFromByteArray(
payload.getCombineFn().getSpec().getPayload().toByteArray(), "CombineFn");
}
public static GlobalCombineFn<?, ?, ?> getCombineFn(AppliedPTransform<?, ?, ?> transform)
throws IOException {
return getCombineFn(getCombinePayload(transform));
}
private static CombinePayload getCombinePayload(AppliedPTransform<?, ?, ?> transform)
throws IOException {
return getCombinePayload(transform, SdkComponents.create());
}
private static CombinePayload getCombinePayload(
AppliedPTransform<?, ?, ?> transform, SdkComponents components) throws IOException {
return CombinePayload.parseFrom(
PTransformTranslation.toProto(
transform, Collections.<AppliedPTransform<?, ?, ?>>emptyList(), components)
.getSpec()
.getPayload());
}
}
| apache-2.0 |
zzcclp/jstorm | jstorm-core/src/main/java/backtype/storm/messaging/TaskMessage.java | 2292 | /**
* 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 backtype.storm.messaging;
import java.nio.ByteBuffer;
public class TaskMessage {
private final short _type; //0 means taskmessage , 1 means task controlmessage
private int _task;
private byte[] _message;
public TaskMessage(int task, byte[] message) {
_type = 0;
_task = task;
_message = message;
}
public TaskMessage(short type, int task, byte[] message) {
_type = type;
_task = task;
_message = message;
}
public short get_type() {
return _type;
}
public int task() {
return _task;
}
public byte[] message() {
return _message;
}
public static boolean isEmpty(TaskMessage message) {
if (message == null) {
return true;
} else if (message.message() == null) {
return true;
} else if (message.message().length == 0) {
return true;
}
return false;
}
/* @Deprecated
public ByteBuffer serialize() {
ByteBuffer bb = ByteBuffer.allocate(_message.length + 4);
bb.putShort((short) _type);
bb.putShort((short) _task);
bb.put(_message);
return bb;
}
@Deprecated
public void deserialize(ByteBuffer packet) {
if (packet == null)
return;
_type = packet.getShort();
_task = packet.getShort();
_message = new byte[packet.limit() - 4];
packet.get(_message);
}*/
}
| apache-2.0 |
tadeegan/eiger | test/unit/org/apache/cassandra/db/SerializationsTest.java | 17493 | package org.apache.cassandra.db;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import org.apache.cassandra.AbstractSerializationsTester;
import org.apache.cassandra.Util;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.dht.AbstractBounds;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessageSerializer;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.thrift.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.junit.Test;
public class SerializationsTest extends AbstractSerializationsTester
{
private static MessageSerializer messageSerializer = new MessageSerializer();
private void testRangeSliceCommandWrite() throws IOException
{
ByteBuffer startCol = ByteBufferUtil.bytes("Start");
ByteBuffer stopCol = ByteBufferUtil.bytes("Stop");
ByteBuffer emptyCol = ByteBufferUtil.bytes("");
SlicePredicate namesPred = new SlicePredicate();
namesPred.column_names = Statics.NamedCols;
SliceRange emptySliceRange = new SliceRange(emptyCol, emptyCol, false, 100);
SliceRange nonEmptySliceRange = new SliceRange(startCol, stopCol, true, 100);
SlicePredicate emptyRangePred = new SlicePredicate();
emptyRangePred.slice_range = emptySliceRange;
SlicePredicate nonEmptyRangePred = new SlicePredicate();
nonEmptyRangePred.slice_range = nonEmptySliceRange;
IPartitioner part = StorageService.getPartitioner();
AbstractBounds<RowPosition> bounds = new Range<Token>(part.getRandomToken(), part.getRandomToken()).toRowBounds();
Message namesCmd = new RangeSliceCommand(Statics.KS, "Standard1", null, namesPred, bounds, 100).getMessage(MessagingService.version_);
Message emptyRangeCmd = new RangeSliceCommand(Statics.KS, "Standard1", null, emptyRangePred, bounds, 100).getMessage(MessagingService.version_);
Message regRangeCmd = new RangeSliceCommand(Statics.KS, "Standard1", null, nonEmptyRangePred, bounds, 100).getMessage(MessagingService.version_);
Message namesCmdSup = new RangeSliceCommand(Statics.KS, "Super1", Statics.SC, namesPred, bounds, 100).getMessage(MessagingService.version_);
Message emptyRangeCmdSup = new RangeSliceCommand(Statics.KS, "Super1", Statics.SC, emptyRangePred, bounds, 100).getMessage(MessagingService.version_);
Message regRangeCmdSup = new RangeSliceCommand(Statics.KS, "Super1", Statics.SC, nonEmptyRangePred, bounds, 100).getMessage(MessagingService.version_);
DataOutputStream dout = getOutput("db.RangeSliceCommand.bin");
messageSerializer.serialize(namesCmd, dout, getVersion());
messageSerializer.serialize(emptyRangeCmd, dout, getVersion());
messageSerializer.serialize(regRangeCmd, dout, getVersion());
messageSerializer.serialize(namesCmdSup, dout, getVersion());
messageSerializer.serialize(emptyRangeCmdSup, dout, getVersion());
messageSerializer.serialize(regRangeCmdSup, dout, getVersion());
dout.close();
}
@Test
public void testRangeSliceCommandRead() throws IOException
{
if (EXECUTE_WRITES)
testRangeSliceCommandWrite();
DataInputStream in = getInput("db.RangeSliceCommand.bin");
for (int i = 0; i < 6; i++)
{
Message msg = messageSerializer.deserialize(in, getVersion());
RangeSliceCommand cmd = RangeSliceCommand.read(msg);
}
in.close();
}
private void testSliceByNamesReadCommandWrite() throws IOException
{
SliceByNamesReadCommand standardCmd = new SliceByNamesReadCommand(Statics.KS, Statics.Key, Statics.StandardPath, Statics.NamedCols);
SliceByNamesReadCommand superCmd = new SliceByNamesReadCommand(Statics.KS, Statics.Key, Statics.SuperPath, Statics.NamedCols);
DataOutputStream out = getOutput("db.SliceByNamesReadCommand.bin");
SliceByNamesReadCommand.serializer().serialize(standardCmd, out, getVersion());
SliceByNamesReadCommand.serializer().serialize(superCmd, out, getVersion());
ReadCommand.serializer().serialize(standardCmd, out, getVersion());
ReadCommand.serializer().serialize(superCmd, out, getVersion());
messageSerializer.serialize(standardCmd.getMessage(getVersion()), out, getVersion());
messageSerializer.serialize(superCmd.getMessage(getVersion()), out, getVersion());
out.close();
}
@Test
public void testSliceByNamesReadCommandRead() throws IOException
{
if (EXECUTE_WRITES)
testSliceByNamesReadCommandWrite();
DataInputStream in = getInput("db.SliceByNamesReadCommand.bin");
assert SliceByNamesReadCommand.serializer().deserialize(in, getVersion()) != null;
assert SliceByNamesReadCommand.serializer().deserialize(in, getVersion()) != null;
assert ReadCommand.serializer().deserialize(in, getVersion()) != null;
assert ReadCommand.serializer().deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
in.close();
}
private void testSliceFromReadCommandWrite() throws IOException
{
SliceFromReadCommand standardCmd = new SliceFromReadCommand(Statics.KS, Statics.Key, Statics.StandardPath, Statics.Start, Statics.Stop, true, 100);
SliceFromReadCommand superCmd = new SliceFromReadCommand(Statics.KS, Statics.Key, Statics.SuperPath, Statics.Start, Statics.Stop, true, 100);
DataOutputStream out = getOutput("db.SliceFromReadCommand.bin");
SliceFromReadCommand.serializer().serialize(standardCmd, out, getVersion());
SliceFromReadCommand.serializer().serialize(superCmd, out, getVersion());
ReadCommand.serializer().serialize(standardCmd, out, getVersion());
ReadCommand.serializer().serialize(superCmd, out, getVersion());
messageSerializer.serialize(standardCmd.getMessage(getVersion()), out, getVersion());
messageSerializer.serialize(superCmd.getMessage(getVersion()), out, getVersion());
out.close();
}
@Test
public void testSliceFromReadCommandRead() throws IOException
{
if (EXECUTE_WRITES)
testSliceFromReadCommandWrite();
DataInputStream in = getInput("db.SliceFromReadCommand.bin");
assert SliceFromReadCommand.serializer().deserialize(in, getVersion()) != null;
assert SliceFromReadCommand.serializer().deserialize(in, getVersion()) != null;
assert ReadCommand.serializer().deserialize(in, getVersion()) != null;
assert ReadCommand.serializer().deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
in.close();
}
private void testRowWrite() throws IOException
{
DataOutputStream out = getOutput("db.Row.bin");
Row.serializer().serialize(Statics.StandardRow, out, getVersion());
Row.serializer().serialize(Statics.SuperRow, out, getVersion());
Row.serializer().serialize(Statics.NullRow, out, getVersion());
out.close();
}
@Test
public void testRowRead() throws IOException
{
if (EXECUTE_WRITES)
testRowWrite();
DataInputStream in = getInput("db.Row.bin");
assert Row.serializer().deserialize(in, getVersion()) != null;
assert Row.serializer().deserialize(in, getVersion()) != null;
assert Row.serializer().deserialize(in, getVersion()) != null;
in.close();
}
private void restRowMutationWrite() throws IOException
{
Set<Dependency> emptyDependencies = new HashSet<Dependency>();
Set<Dependency> oneDependency = new HashSet<Dependency>();
oneDependency.add(new Dependency(Statics.Key, 64));
RowMutation emptyRm = new RowMutation(Statics.KS, Statics.Key, emptyDependencies);
RowMutation standardRowRm = new RowMutation(Statics.KS, Statics.StandardRow);
RowMutation superRowRm = new RowMutation(Statics.KS, Statics.SuperRow, oneDependency);
RowMutation standardRm = new RowMutation(Statics.KS, Statics.Key);
standardRm.add(Statics.StandardCf);
RowMutation superRm = new RowMutation(Statics.KS, Statics.Key);
superRm.add(Statics.SuperCf);
Map<Integer, ColumnFamily> mods = new HashMap<Integer, ColumnFamily>();
mods.put(Statics.StandardCf.metadata().cfId, Statics.StandardCf);
mods.put(Statics.SuperCf.metadata().cfId, Statics.SuperCf);
RowMutation mixedRm = new RowMutation(Statics.KS, Statics.Key, mods, emptyDependencies);
DataOutputStream out = getOutput("db.RowMutation.bin");
RowMutation.serializer().serialize(emptyRm, out, getVersion());
RowMutation.serializer().serialize(standardRowRm, out, getVersion());
RowMutation.serializer().serialize(superRowRm, out, getVersion());
RowMutation.serializer().serialize(standardRm, out, getVersion());
RowMutation.serializer().serialize(superRm, out, getVersion());
RowMutation.serializer().serialize(mixedRm, out, getVersion());
messageSerializer.serialize(emptyRm.getMessage(getVersion()), out, getVersion());
messageSerializer.serialize(standardRowRm.getMessage(getVersion()), out, getVersion());
messageSerializer.serialize(superRowRm.getMessage(getVersion()), out, getVersion());
messageSerializer.serialize(standardRm.getMessage(getVersion()), out, getVersion());
messageSerializer.serialize(superRm.getMessage(getVersion()), out, getVersion());
messageSerializer.serialize(mixedRm.getMessage(getVersion()), out, getVersion());
out.close();
}
@Test
public void testRowMutationRead() throws IOException
{
if (EXECUTE_WRITES)
restRowMutationWrite();
DataInputStream in = getInput("db.RowMutation.bin");
assert RowMutation.serializer().deserialize(in, getVersion()) != null;
assert RowMutation.serializer().deserialize(in, getVersion()) != null;
assert RowMutation.serializer().deserialize(in, getVersion()) != null;
assert RowMutation.serializer().deserialize(in, getVersion()) != null;
assert RowMutation.serializer().deserialize(in, getVersion()) != null;
assert RowMutation.serializer().deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
in.close();
}
public void testTruncateWrite() throws IOException
{
Truncation tr = new Truncation(Statics.KS, "Doesn't Really Matter");
TruncateResponse aff = new TruncateResponse(Statics.KS, "Doesn't Matter Either", true);
TruncateResponse neg = new TruncateResponse(Statics.KS, "Still Doesn't Matter", false);
DataOutputStream out = getOutput("db.Truncation.bin");
Truncation.serializer().serialize(tr, out, getVersion());
TruncateResponse.serializer().serialize(aff, out, getVersion());
TruncateResponse.serializer().serialize(neg, out, getVersion());
messageSerializer.serialize(tr.getMessage(getVersion()), out, getVersion());
messageSerializer.serialize(TruncateResponse.makeTruncateResponseMessage(tr.getMessage(getVersion()), aff), out, getVersion());
messageSerializer.serialize(TruncateResponse.makeTruncateResponseMessage(tr.getMessage(getVersion()), neg), out, getVersion());
// todo: notice how CF names weren't validated.
out.close();
}
@Test
public void testTruncateRead() throws IOException
{
if (EXECUTE_WRITES)
testTruncateWrite();
DataInputStream in = getInput("db.Truncation.bin");
assert Truncation.serializer().deserialize(in, getVersion()) != null;
assert TruncateResponse.serializer().deserialize(in, getVersion()) != null;
assert TruncateResponse.serializer().deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
assert messageSerializer.deserialize(in, getVersion()) != null;
in.close();
}
private void testWriteResponseWrite() throws IOException
{
WriteResponse aff = new WriteResponse(Statics.KS, Statics.Key, true);
WriteResponse neg = new WriteResponse(Statics.KS, Statics.Key, false);
DataOutputStream out = getOutput("db.WriteResponse.bin");
WriteResponse.serializer().serialize(aff, out, getVersion());
WriteResponse.serializer().serialize(neg, out, getVersion());
out.close();
}
@Test
public void testWriteResponseRead() throws IOException
{
if (EXECUTE_WRITES)
testWriteResponseWrite();
DataInputStream in = getInput("db.WriteResponse.bin");
assert WriteResponse.serializer().deserialize(in, getVersion()) != null;
assert WriteResponse.serializer().deserialize(in, getVersion()) != null;
in.close();
}
private static ByteBuffer bb(String s) {
return ByteBufferUtil.bytes(s);
}
private static class Statics
{
private static final String KS = "Keyspace1";
private static final ByteBuffer Key = ByteBufferUtil.bytes("Key01");
private static final List<ByteBuffer> NamedCols = new ArrayList<ByteBuffer>()
{{
add(ByteBufferUtil.bytes("AAA"));
add(ByteBufferUtil.bytes("BBB"));
add(ByteBufferUtil.bytes("CCC"));
}};
private static final ByteBuffer SC = ByteBufferUtil.bytes("SCName");
private static final QueryPath StandardPath = new QueryPath("Standard1");
private static final QueryPath SuperPath = new QueryPath("Super1", SC);
private static final ByteBuffer Start = ByteBufferUtil.bytes("Start");
private static final ByteBuffer Stop = ByteBufferUtil.bytes("Stop");
private static final ColumnFamily StandardCf = ColumnFamily.create(Statics.KS, "Standard1");
private static final ColumnFamily SuperCf = ColumnFamily.create(Statics.KS, "Super1");
private static final SuperColumn SuperCol = new SuperColumn(Statics.SC, Schema.instance.getComparator(Statics.KS, "Super1"))
{{
addColumn(new Column(bb("aaaa")));
addColumn(new Column(bb("bbbb"), bb("bbbbb-value")));
addColumn(new Column(bb("cccc"), bb("ccccc-value"), 1000L));
addColumn(new DeletedColumn(bb("dddd"), 500, 1000, null));
addColumn(new DeletedColumn(bb("eeee"), bb("eeee-value"), 1001));
addColumn(new ExpiringColumn(bb("ffff"), bb("ffff-value"), 2000, 1000));
addColumn(new ExpiringColumn(bb("gggg"), bb("gggg-value"), 2001, 1000, 2002));
}};
private static final Row StandardRow = new Row(Util.dk("key0"), Statics.StandardCf);
private static final Row SuperRow = new Row(Util.dk("key1"), Statics.SuperCf);
private static final Row NullRow = new Row(Util.dk("key2"), null);
static {
StandardCf.addColumn(new Column(bb("aaaa")));
StandardCf.addColumn(new Column(bb("bbbb"), bb("bbbbb-value")));
StandardCf.addColumn(new Column(bb("cccc"), bb("ccccc-value"), 1000L));
StandardCf.addColumn(new DeletedColumn(bb("dddd"), 500, 1000, null));
StandardCf.addColumn(new DeletedColumn(bb("eeee"), bb("eeee-value"), 1001));
StandardCf.addColumn(new ExpiringColumn(bb("ffff"), bb("ffff-value"), 2000, 1000));
StandardCf.addColumn(new ExpiringColumn(bb("gggg"), bb("gggg-value"), 2001, 1000, 2002));
SuperCf.addColumn(Statics.SuperCol);
}
}
}
| apache-2.0 |
jerrinot/hazelcast | hazelcast/src/main/java/com/hazelcast/jet/core/JetDataSerializerHook.java | 3154 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.core;
import com.hazelcast.internal.serialization.DataSerializerHook;
import com.hazelcast.internal.serialization.impl.FactoryIdHelper;
import com.hazelcast.jet.impl.connector.AbstractUpdateMapP.ApplyValuesEntryProcessor;
import com.hazelcast.jet.impl.connector.UpdateMapP.ApplyFnEntryProcessor;
import com.hazelcast.nio.serialization.DataSerializableFactory;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.spi.annotation.PrivateApi;
import static com.hazelcast.jet.impl.JetFactoryIdHelper.JET_DS_FACTORY;
import static com.hazelcast.jet.impl.JetFactoryIdHelper.JET_DS_FACTORY_ID;
/**
* A Java Service Provider hook for Hazelcast's Identified Data Serializable
* mechanism. This is private API.
*/
@PrivateApi
public final class JetDataSerializerHook implements DataSerializerHook {
/**
* Serialization ID of the {@link DAG} class.
*/
public static final int DAG = 0;
/**
* Serialization ID of the {@link Vertex} class.
*/
public static final int VERTEX = 1;
/**
* Serialization ID of the {@link Edge} class.
*/
public static final int EDGE = 2;
/**
* Serialization ID of the {@link ApplyFnEntryProcessor} class.
*/
public static final int APPLY_FN_ENTRY_PROCESSOR = 3;
/**
* Serialization ID of the {@link ApplyValuesEntryProcessor} class.
*/
public static final int APPLY_VALUE_ENTRY_PROCESSOR = 4;
/**
* Factory ID
*/
public static final int FACTORY_ID = FactoryIdHelper.getFactoryId(JET_DS_FACTORY, JET_DS_FACTORY_ID);
@Override
public int getFactoryId() {
return FACTORY_ID;
}
@Override
public DataSerializableFactory createFactory() {
return new Factory();
}
private static class Factory implements DataSerializableFactory {
@Override
public IdentifiedDataSerializable create(int typeId) {
switch (typeId) {
case DAG:
return new DAG();
case EDGE:
return new Edge();
case VERTEX:
return new Vertex();
case APPLY_FN_ENTRY_PROCESSOR:
return new ApplyFnEntryProcessor();
case APPLY_VALUE_ENTRY_PROCESSOR:
return new ApplyValuesEntryProcessor();
default:
throw new IllegalArgumentException("Unknown type id " + typeId);
}
}
}
}
| apache-2.0 |
dbmalkovsky/flowable-engine | modules/flowable-external-job-rest/src/main/java/org/flowable/external/job/rest/service/api/acquire/AcquireExternalWorkerJobRequest.java | 2961 | /* 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.flowable.external.job.rest.service.api.acquire;
import java.time.Duration;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @author Filip Hrisafov
*/
@ApiModel(description = "Request that is used for acquiring external worker jobs")
public class AcquireExternalWorkerJobRequest {
@ApiModelProperty(value = "Acquire jobs with the given topic", example = "order", required = true)
protected String topic;
@ApiModelProperty(
value = "The acquired jobs will be locked with this lock duration. ISO-8601 duration format PnDTnHnMn.nS with days considered to be exactly 24 hours.",
example = "PT10M", dataType = "string", required = true)
protected Duration lockDuration;
@ApiModelProperty(value = "The number of tasks that should be acquired. Default is 1.", example = "1")
protected int numberOfTasks = 1;
@ApiModelProperty(value = "The number of retries if an optimistic lock exception occurs during acquiring. Default is 5", example = "10")
protected int numberOfRetries = 5;
@ApiModelProperty(value = "The id of the external worker that would be used for locking the job", example = "orderWorker1", required = true)
protected String workerId;
@ApiModelProperty(value = "Only acquire jobs with the given scope type", example = "cmmn")
protected String scopeType;
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public Duration getLockDuration() {
return lockDuration;
}
public void setLockDuration(Duration lockDuration) {
this.lockDuration = lockDuration;
}
public int getNumberOfTasks() {
return numberOfTasks;
}
public void setNumberOfTasks(int numberOfTasks) {
this.numberOfTasks = numberOfTasks;
}
public int getNumberOfRetries() {
return numberOfRetries;
}
public void setNumberOfRetries(int numberOfRetries) {
this.numberOfRetries = numberOfRetries;
}
public String getWorkerId() {
return workerId;
}
public void setWorkerId(String workerId) {
this.workerId = workerId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
}
| apache-2.0 |
mikibrv/sling | bundles/resourceresolver/src/main/java/org/apache/sling/resourceresolver/impl/ResourceResolverImpl.java | 55288 | /*
* 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.sling.resourceresolver.impl;
import static org.apache.commons.lang.StringUtils.defaultString;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.jcr.NamespaceException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import org.apache.sling.adapter.annotations.Adaptable;
import org.apache.sling.adapter.annotations.Adapter;
import org.apache.sling.api.SlingException;
import org.apache.sling.api.adapter.SlingAdaptable;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceNotFoundException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ResourceWrapper;
import org.apache.sling.resourceresolver.impl.helper.RedirectResource;
import org.apache.sling.resourceresolver.impl.helper.ResourceIteratorDecorator;
import org.apache.sling.resourceresolver.impl.helper.ResourcePathIterator;
import org.apache.sling.resourceresolver.impl.helper.ResourceResolverContext;
import org.apache.sling.resourceresolver.impl.helper.ResourceResolverControl;
import org.apache.sling.resourceresolver.impl.helper.StarResource;
import org.apache.sling.resourceresolver.impl.helper.URI;
import org.apache.sling.resourceresolver.impl.helper.URIException;
import org.apache.sling.resourceresolver.impl.mapping.MapEntry;
import org.apache.sling.resourceresolver.impl.params.ParsedParameters;
import org.apache.sling.resourceresolver.impl.providers.ResourceProviderStorageProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Adaptable(adaptableClass = ResourceResolver.class, adapters = { @Adapter(Session.class) })
public class ResourceResolverImpl extends SlingAdaptable implements ResourceResolver {
/** Default logger */
private static final Logger logger = LoggerFactory.getLogger(ResourceResolverImpl.class);
private static final Map<String, String> EMPTY_PARAMETERS = Collections.emptyMap();
private static final String MANGLE_NAMESPACE_IN_SUFFIX = "_";
private static final String MANGLE_NAMESPACE_IN_PREFIX = "/_";
private static final Pattern MANGLE_NAMESPACE_IN_PATTERN = Pattern.compile("/_([^_/]+)_");
private static final String MANGLE_NAMESPACE_OUT_SUFFIX = ":";
private static final String MANGLE_NAMESPACE_OUT_PREFIX = "/";
private static final Pattern MANLE_NAMESPACE_OUT_PATTERN = Pattern.compile("/([^:/]+):");
public static final String PROP_REDIRECT_INTERNAL = "sling:internalRedirect";
public static final String PROP_ALIAS = "sling:alias";
// The suffix of a resource being a content node of some parent
// such as nt:file. The slash is included to prevent false
// positives for the String.endsWith check for names like
// "xyzjcr:content"
private static final String JCR_CONTENT_LEAF = "/jcr:content";
/** The factory which created this resource resolver. */
private final CommonResourceResolverFactoryImpl factory;
/** Resource resolver control. */
private final ResourceResolverControl control;
/** Resource resolver context. */
private final ResourceResolverContext context;
private volatile Exception closedResolverException;
public ResourceResolverImpl(final CommonResourceResolverFactoryImpl factory, final boolean isAdmin, final Map<String, Object> authenticationInfo) throws LoginException {
this(factory, isAdmin, authenticationInfo, factory.getResourceProviderTracker());
}
ResourceResolverImpl(final CommonResourceResolverFactoryImpl factory, final boolean isAdmin, final Map<String, Object> authenticationInfo, final ResourceProviderStorageProvider resourceProviderTracker) throws LoginException {
this.factory = factory;
this.context = new ResourceResolverContext(this, factory.getResourceAccessSecurityTracker());
this.control = createControl(resourceProviderTracker, authenticationInfo, isAdmin);
this.factory.register(this, control);
}
/**
* Constructor for cloning the resource resolver
* @param resolver The resolver to clone
* @param authenticationInfo The auth info
* @throws LoginException if auth to a required provider fails
*/
private ResourceResolverImpl(final ResourceResolverImpl resolver, final Map<String, Object> authenticationInfo) throws LoginException {
this.factory = resolver.factory;
Map<String, Object> authInfo = new HashMap<String, Object>();
if (resolver.control.getAuthenticationInfo() != null) {
authInfo.putAll(resolver.control.getAuthenticationInfo());
}
if (authenticationInfo != null) {
authInfo.putAll(authenticationInfo);
}
this.context = new ResourceResolverContext(this, factory.getResourceAccessSecurityTracker());
this.control = createControl(factory.getResourceProviderTracker(), authInfo, resolver.control.isAdmin());
this.factory.register(this, control);
}
/**
* Create the resource resolver control
* @param storage The provider storage
* @param authenticationInfo Current auth info
* @param isAdmin Is this admin?
* @return A control
* @throws LoginException If auth to the required providers fails.
*/
private ResourceResolverControl createControl(final ResourceProviderStorageProvider resourceProviderTracker,
final Map<String, Object> authenticationInfo,
final boolean isAdmin)
throws LoginException {
final ResourceResolverControl control = new ResourceResolverControl(isAdmin, authenticationInfo, resourceProviderTracker);
this.context.getProviderManager().authenticateAll(resourceProviderTracker.getResourceProviderStorage().getAuthRequiredHandlers(), control);
return control;
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#clone(Map)
*/
@Override
public ResourceResolver clone(final Map<String, Object> authenticationInfo)
throws LoginException {
// ensure resolver is still live
checkClosed();
// create a regular resource resolver
return new ResourceResolverImpl(this, authenticationInfo);
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#isLive()
*/
@Override
public boolean isLive() {
return !this.control.isClosed() && this.control.isLive(this.context) && this.factory.isLive();
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#close()
*/
@Override
public void close() {
if (factory.shouldLogResourceResolverClosing()) {
closedResolverException = new Exception("Stack Trace");
}
this.factory.unregister(this, this.control);
}
/**
* Check if the resource resolver is already closed or the factory which created this resolver is no longer live.
*
* @throws IllegalStateException
* If the resolver is already closed or the factory is no longer live.
*/
private void checkClosed() {
if (this.control.isClosed()) {
if (closedResolverException != null) {
logger.error("The ResourceResolver has already been closed.", closedResolverException);
}
throw new IllegalStateException("Resource resolver is already closed.");
}
if (!this.factory.isLive()) {
throw new IllegalStateException("Resource resolver factory which created this resolver is no longer active.");
}
}
// ---------- attributes
/**
* @see org.apache.sling.api.resource.ResourceResolver#getAttributeNames()
*/
@Override
public Iterator<String> getAttributeNames() {
checkClosed();
return this.control.getAttributeNames(this.context).iterator();
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#getAttribute(String)
*/
@Override
public Object getAttribute(final String name) {
checkClosed();
if (name == null) {
throw new NullPointerException("name");
}
return this.control.getAttribute(this.context, name);
}
// ---------- resolving resources
/**
* @see org.apache.sling.api.resource.ResourceResolver#resolve(java.lang.String)
*/
@Override
public Resource resolve(final String path) {
checkClosed();
final Resource rsrc = this.resolveInternal(null, path);
return rsrc;
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#resolve(javax.servlet.http.HttpServletRequest)
*/
@Override
public Resource resolve(final HttpServletRequest request) {
checkClosed();
// throws NPE if request is null as required
final Resource rsrc = this.resolveInternal(request, request.getPathInfo());
return rsrc;
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#resolve(javax.servlet.http.HttpServletRequest,
* java.lang.String)
*/
@Override
public Resource resolve(final HttpServletRequest request, String path) {
checkClosed();
final Resource rsrc = this.resolveInternal(request, path);
return rsrc;
}
private Resource resolveInternal(final HttpServletRequest request, String absPath) {
// make sure abspath is not null and is absolute
if (absPath == null) {
absPath = "/";
} else if (!absPath.startsWith("/")) {
absPath = "/" + absPath;
}
// check for special namespace prefix treatment
absPath = unmangleNamespaces(absPath);
// Assume http://localhost:80 if request is null
String[] realPathList = { absPath };
String requestPath;
if (request != null) {
requestPath = getMapPath(request.getScheme(), request.getServerName(), request.getServerPort(), absPath);
} else {
requestPath = getMapPath("http", "localhost", 80, absPath);
}
logger.debug("resolve: Resolving request path {}", requestPath);
// loop while finding internal or external redirect into the
// content out of the virtual host mapping tree
// the counter is to ensure we are not caught in an endless loop here
// TODO: might do better to be able to log the loop and help the user
for (int i = 0; i < 100; i++) {
String[] mappedPath = null;
final Iterator<MapEntry> mapEntriesIterator = this.factory.getMapEntries().getResolveMapsIterator(requestPath);
while (mapEntriesIterator.hasNext()) {
final MapEntry mapEntry = mapEntriesIterator.next();
mappedPath = mapEntry.replace(requestPath);
if (mappedPath != null) {
if (logger.isDebugEnabled()) {
logger.debug("resolve: MapEntry {} matches, mapped path is {}", mapEntry, Arrays.toString(mappedPath));
}
if (mapEntry.isInternal()) {
// internal redirect
logger.debug("resolve: Redirecting internally");
break;
}
// external redirect
logger.debug("resolve: Returning external redirect");
return this.factory.getResourceDecoratorTracker().decorate(
new RedirectResource(this, absPath, mappedPath[0], mapEntry.getStatus()));
}
}
// if there is no virtual host based path mapping, abort
// and use the original realPath
if (mappedPath == null) {
logger.debug("resolve: Request path {} does not match any MapEntry", requestPath);
break;
}
// if the mapped path is not an URL, use this path to continue
if (!mappedPath[0].contains("://")) {
logger.debug("resolve: Mapped path is for resource tree");
realPathList = mappedPath;
break;
}
// otherwise the mapped path is an URI and we have to try to
// resolve that URI now, using the URI's path as the real path
try {
final URI uri = new URI(mappedPath[0], false);
requestPath = getMapPath(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath());
realPathList = new String[] { uri.getPath() };
logger.debug("resolve: Mapped path is an URL, using new request path {}", requestPath);
} catch (final URIException use) {
// TODO: log and fail
throw new ResourceNotFoundException(absPath);
}
}
// now we have the real path resolved from virtual host mapping
// this path may be absolute or relative, in which case we try
// to resolve it against the search path
Resource res = null;
for (int i = 0; res == null && i < realPathList.length; i++) {
final ParsedParameters parsedPath = new ParsedParameters(realPathList[i]);
final String realPath = parsedPath.getRawPath();
// first check whether the requested resource is a StarResource
if (StarResource.appliesTo(realPath)) {
logger.debug("resolve: Mapped path {} is a Star Resource", realPath);
res = new StarResource(this, ensureAbsPath(realPath));
} else {
if (realPath.startsWith("/")) {
// let's check it with a direct access first
logger.debug("resolve: Try absolute mapped path {}", realPath);
res = resolveInternal(realPath, parsedPath.getParameters());
} else {
final String[] searchPath = getSearchPath();
for (int spi = 0; res == null && spi < searchPath.length; spi++) {
logger.debug("resolve: Try relative mapped path with search path entry {}", searchPath[spi]);
res = resolveInternal(searchPath[spi] + realPath, parsedPath.getParameters());
}
}
}
}
// if no resource has been found, use a NonExistingResource
if (res == null) {
final ParsedParameters parsedPath = new ParsedParameters(realPathList[0]);
final String resourcePath = ensureAbsPath(parsedPath.getRawPath());
logger.debug("resolve: Path {} does not resolve, returning NonExistingResource at {}", absPath, resourcePath);
res = new NonExistingResource(this, resourcePath);
// SLING-864: if the path contains a dot we assume this to be
// the start for any selectors, extension, suffix, which may be
// used for further request processing.
// the resolution path must be the full path and is already set within
// the non existing resource
final int index = resourcePath.indexOf('.');
if (index != -1) {
res.getResourceMetadata().setResolutionPathInfo(resourcePath.substring(index));
}
res.getResourceMetadata().setParameterMap(parsedPath.getParameters());
} else {
logger.debug("resolve: Path {} resolves to Resource {}", absPath, res);
}
return this.factory.getResourceDecoratorTracker().decorate(res);
}
/**
* calls map(HttpServletRequest, String) as map(null, resourcePath)
*
* @see org.apache.sling.api.resource.ResourceResolver#map(java.lang.String)
*/
@Override
public String map(final String resourcePath) {
checkClosed();
return map(null, resourcePath);
}
/**
* full implementation - apply sling:alias from the resource path - apply
* /etc/map mappings (inkl. config backwards compat) - return absolute uri
* if possible
*
* @see org.apache.sling.api.resource.ResourceResolver#map(javax.servlet.http.HttpServletRequest,
* java.lang.String)
*/
@Override
public String map(final HttpServletRequest request, final String resourcePath) {
checkClosed();
// find a fragment or query
int fragmentQueryMark = resourcePath.indexOf('#');
if (fragmentQueryMark < 0) {
fragmentQueryMark = resourcePath.indexOf('?');
}
// cut fragment or query off the resource path
String mappedPath;
final String fragmentQuery;
if (fragmentQueryMark >= 0) {
fragmentQuery = resourcePath.substring(fragmentQueryMark);
mappedPath = resourcePath.substring(0, fragmentQueryMark);
logger.debug("map: Splitting resource path '{}' into '{}' and '{}'", new Object[] { resourcePath, mappedPath,
fragmentQuery });
} else {
fragmentQuery = null;
mappedPath = resourcePath;
}
// cut off scheme and host, if the same as requested
final String schemehostport;
final String schemePrefix;
if (request != null) {
schemehostport = MapEntry.getURI(request.getScheme(), request.getServerName(), request.getServerPort(), "/");
schemePrefix = request.getScheme().concat("://");
logger.debug("map: Mapping path {} for {} (at least with scheme prefix {})", new Object[] { resourcePath,
schemehostport, schemePrefix });
} else {
schemehostport = null;
schemePrefix = null;
logger.debug("map: Mapping path {} for default", resourcePath);
}
ParsedParameters parsed = new ParsedParameters(mappedPath);
final Resource res = resolveInternal(parsed.getRawPath(), parsed.getParameters());
if (res != null) {
// keep, what we might have cut off in internal resolution
final String resolutionPathInfo = res.getResourceMetadata().getResolutionPathInfo();
logger.debug("map: Path maps to resource {} with path info {}", res, resolutionPathInfo);
// find aliases for segments. we can't walk the parent chain
// since the request session might not have permissions to
// read all parents SLING-2093
final LinkedList<String> names = new LinkedList<String>();
Resource current = res;
String path = res.getPath();
while (path != null) {
String alias = null;
if (current != null && !path.endsWith(JCR_CONTENT_LEAF)) {
if (factory.isOptimizeAliasResolutionEnabled()) {
logger.debug("map: Optimize Alias Resolution is Enabled");
String parentPath = ResourceUtil.getParent(path);
if (parentPath != null) {
final Map<String, String> aliases = factory.getMapEntries().getAliasMap(parentPath);
if (aliases!= null && aliases.containsValue(current.getName())) {
for (String key:aliases.keySet()) {
if (current.getName().equals(aliases.get(key))) {
alias = key;
break;
}
}
}
}
} else {
logger.debug("map: Optimize Alias Resolution is Disabled");
alias = ResourceResolverControl.getProperty(current, PROP_ALIAS);
}
}
if (alias == null || alias.length() == 0) {
alias = ResourceUtil.getName(path);
}
names.add(alias);
path = ResourceUtil.getParent(path);
if ("/".equals(path)) {
path = null;
} else if (path != null) {
current = res.getResourceResolver().resolve(path);
}
}
// build path from segment names
final StringBuilder buf = new StringBuilder();
// construct the path from the segments (or root if none)
if (names.isEmpty()) {
buf.append('/');
} else {
while (!names.isEmpty()) {
buf.append('/');
buf.append(names.removeLast());
}
}
// reappend the resolutionPathInfo
if (resolutionPathInfo != null) {
buf.append(resolutionPathInfo);
}
// and then we have the mapped path to work on
mappedPath = buf.toString();
logger.debug("map: Alias mapping resolves to path {}", mappedPath);
}
boolean mappedPathIsUrl = false;
for (final MapEntry mapEntry : this.factory.getMapEntries().getMapMaps()) {
final String[] mappedPaths = mapEntry.replace(mappedPath);
if (mappedPaths != null) {
logger.debug("map: Match for Entry {}", mapEntry);
mappedPathIsUrl = !mapEntry.isInternal();
if (mappedPathIsUrl && schemehostport != null) {
mappedPath = null;
for (final String candidate : mappedPaths) {
if (candidate.startsWith(schemehostport)) {
mappedPath = candidate.substring(schemehostport.length() - 1);
mappedPathIsUrl = false;
logger.debug("map: Found host specific mapping {} resolving to {}", candidate, mappedPath);
break;
} else if (candidate.startsWith(schemePrefix) && mappedPath == null) {
mappedPath = candidate;
}
}
if (mappedPath == null) {
mappedPath = mappedPaths[0];
}
} else {
// we can only go with assumptions selecting the first entry
mappedPath = mappedPaths[0];
}
logger.debug("resolve: MapEntry {} matches, mapped path is {}", mapEntry, mappedPath);
break;
}
}
// this should not be the case, since mappedPath is primed
if (mappedPath == null) {
mappedPath = resourcePath;
}
// [scheme:][//authority][path][?query][#fragment]
try {
// use commons-httpclient's URI instead of java.net.URI, as it can
// actually accept *unescaped* URIs, such as the "mappedPath" and
// return them in proper escaped form, including the path, via
// toString()
final URI uri = new URI(mappedPath, false);
// 1. mangle the namespaces in the path
String path = mangleNamespaces(uri.getPath());
// 2. prepend servlet context path if we have a request
if (request != null && request.getContextPath() != null && request.getContextPath().length() > 0) {
path = request.getContextPath().concat(path);
}
// update the path part of the URI
uri.setPath(path);
mappedPath = uri.toString();
} catch (final URIException e) {
logger.warn("map: Unable to mangle namespaces for " + mappedPath + " returning unmangled", e);
}
logger.debug("map: Returning URL {} as mapping for path {}", mappedPath, resourcePath);
// reappend fragment and/or query
if (fragmentQuery != null) {
mappedPath = mappedPath.concat(fragmentQuery);
}
return mappedPath;
}
// ---------- search path for relative resoures
/**
* @see org.apache.sling.api.resource.ResourceResolver#getSearchPath()
*/
@Override
public String[] getSearchPath() {
checkClosed();
return factory.getSearchPath().clone();
}
// ---------- direct resource access without resolution
/**
* @see org.apache.sling.api.resource.ResourceResolver#getResource(java.lang.String)
*/
@Override
public Resource getResource(String path) {
checkClosed();
final Resource result = this.getResourceInternal(null, path);
return result;
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#getResource(org.apache.sling.api.resource.Resource,
* java.lang.String)
*/
@Override
public Resource getResource(final Resource base, final String path) {
checkClosed();
String absolutePath = path;
if (absolutePath != null && !absolutePath.startsWith("/") && base != null && base.getPath() != null ) {
absolutePath = appendToPath(base.getPath(), absolutePath);
}
final Resource result = getResourceInternal(base, absolutePath);
return result;
}
/**
* Methods concatenates two paths. If the first path contains parameters separated semicolon, they are
* moved at the end of the result.
*
* @param pathWithParameters
* @param segmentToAppend
* @return
*/
private static String appendToPath(final String pathWithParameters, final String segmentToAppend) {
final ParsedParameters parsed = new ParsedParameters(pathWithParameters);
if (parsed.getParametersString() == null) {
return new StringBuilder(parsed.getRawPath()).append('/').append(segmentToAppend).toString();
} else {
return new StringBuilder(parsed.getRawPath()).append('/').append(segmentToAppend).append(parsed.getParametersString()).toString();
}
}
private Resource getResourceInternal(Resource parent, String path) {
Resource result = null;
if ( path != null ) {
// if the path is absolute, normalize . and .. segments and get res
if (path.startsWith("/")) {
final ParsedParameters parsedPath = new ParsedParameters(path);
path = ResourceUtil.normalize(parsedPath.getRawPath());
result = (path != null) ? getAbsoluteResourceInternal(parent, path, parsedPath.getParameters(), false) : null;
if (result != null) {
result = this.factory.getResourceDecoratorTracker().decorate(result);
}
} else {
// otherwise we have to apply the search path
// (don't use this.getSearchPath() to save a few cycle for not cloning)
final String[] paths = factory.getSearchPath();
if (paths != null) {
for (final String prefix : factory.getSearchPath()) {
result = getResource(prefix + path);
if (result != null) {
break;
}
}
}
}
}
return result;
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#listChildren(org.apache.sling.api.resource.Resource)
*/
@Override
public Iterator<Resource> listChildren(final Resource parent) {
checkClosed();
if (parent instanceof ResourceWrapper) {
return listChildren(((ResourceWrapper) parent).getResource());
}
return new ResourceIteratorDecorator(this.factory.getResourceDecoratorTracker(), this.control.listChildren(this.context, parent));
}
/**
* @see org.apache.sling.api.resource.Resource#getChildren()
*/
@Override
public Iterable<Resource> getChildren(final Resource parent) {
return new Iterable<Resource>() {
@Override
public Iterator<Resource> iterator() {
return listChildren(parent);
}
};
}
// ---------- Querying resources
private static final String DEFAULT_QUERY_LANGUAGE = "xpath";
/**
* @see org.apache.sling.api.resource.ResourceResolver#findResources(java.lang.String,
* java.lang.String)
*/
@Override
public Iterator<Resource> findResources(final String query, final String language) throws SlingException {
checkClosed();
return new ResourceIteratorDecorator(this.factory.getResourceDecoratorTracker(),
control.findResources(this.context, query, defaultString(language, DEFAULT_QUERY_LANGUAGE)));
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#queryResources(java.lang.String,
* java.lang.String)
*/
@Override
public Iterator<Map<String, Object>> queryResources(final String query, final String language)
throws SlingException {
checkClosed();
return control.queryResources(this.context, query, defaultString(language, DEFAULT_QUERY_LANGUAGE));
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#getUserID()
*/
@Override
public String getUserID() {
checkClosed();
// Try auth info first
if ( this.control.getAuthenticationInfo() != null ) {
final Object impUser = this.control.getAuthenticationInfo().get(ResourceResolverFactory.USER_IMPERSONATION);
if ( impUser != null ) {
return impUser.toString();
}
final Object user = this.control.getAuthenticationInfo().get(ResourceResolverFactory.USER);
if ( user != null ) {
return user.toString();
}
}
// Try session
final Session session = this.getSession();
if ( session != null ) {
return session.getUserID();
}
// Try attributes
final Object impUser = this.getAttribute(ResourceResolverFactory.USER_IMPERSONATION);
if ( impUser != null ) {
return impUser.toString();
}
final Object user = this.getAttribute(ResourceResolverFactory.USER);
if ( user != null ) {
return user.toString();
}
return null;
}
/** Cached session object, fetched on demand. */
private Session cachedSession;
/** Flag indicating if a searching has already been searched. */
private boolean searchedSession = false;
/**
* Try to get a session from one of the resource providers.
*/
private Session getSession() {
if ( !this.searchedSession ) {
this.searchedSession = true;
this.cachedSession = this.control.adaptTo(this.context, Session.class);
}
return this.cachedSession;
}
// ---------- Adaptable interface
/**
* @see org.apache.sling.api.adapter.SlingAdaptable#adaptTo(java.lang.Class)
*/
@Override
@SuppressWarnings("unchecked")
public <AdapterType> AdapterType adaptTo(final Class<AdapterType> type) {
checkClosed();
if (type == Session.class) {
return (AdapterType) getSession();
}
final AdapterType result = this.control.adaptTo(this.context, type);
if ( result != null ) {
return result;
}
// fall back to default behaviour
return super.adaptTo(type);
}
// ---------- internal
/**
* Returns a string used for matching map entries against the given request
* or URI parts.
*
* @param scheme
* The URI scheme
* @param host
* The host name
* @param port
* The port number. If this is negative, the default value used
* is 80 unless the scheme is "https" in which case the default
* value is 443.
* @param path
* The (absolute) path
* @return The request path string {scheme}/{host}.{port}{path}.
*/
private static String getMapPath(final String scheme, final String host, int port, final String path) {
if (port < 0) {
port = ("https".equals(scheme)) ? 443 : 80;
}
return scheme + "/" + host + "." + port + path;
}
/**
* Internally resolves the absolute path. The will almost always contain
* request selectors and an extension. Therefore this method uses the
* {@link ResourcePathIterator} to cut off parts of the path to find the
* actual resource.
* <p>
* This method operates in two steps:
* <ol>
* <li>Check the path directly
* <li>Drill down the resource tree from the root down to the resource trying to get the child
* as per the respective path segment or finding a child whose <code>sling:alias</code> property
* is set to the respective name.
* </ol>
* <p>
* If neither mechanism (direct access and drill down) resolves to a resource this method
* returns <code>null</code>.
*
* @param absPath
* The absolute path of the resource to return.
* @return The resource found or <code>null</code> if the resource could not
* be found. The
* {@link org.apache.sling.api.resource.ResourceMetadata#getResolutionPathInfo()
* resolution path info} field of the resource returned is set to
* the part of the <code>absPath</code> which has been cut off by
* the {@link ResourcePathIterator} to resolve the resource.
*/
private Resource resolveInternal(final String absPath, final Map<String, String> parameters) {
Resource resource = null;
String curPath = absPath;
try {
final ResourcePathIterator it = new ResourcePathIterator(absPath);
while (it.hasNext() && resource == null) {
curPath = it.next();
resource = getAbsoluteResourceInternal(null, curPath, parameters, true);
}
} catch (final Exception ex) {
throw new SlingException("Problem trying " + curPath + " for request path " + absPath, ex);
}
// SLING-627: set the part cut off from the uriPath as
// sling.resolutionPathInfo property such that
// uriPath = curPath + sling.resolutionPathInfo
if (resource != null) {
final String rpi = absPath.substring(curPath.length());
resource.getResourceMetadata().setResolutionPath(absPath.substring(0, curPath.length()));
resource.getResourceMetadata().setResolutionPathInfo(rpi);
resource.getResourceMetadata().setParameterMap(parameters);
logger.debug("resolveInternal: Found resource {} with path info {} for {}", new Object[] { resource, rpi, absPath });
} else {
String tokenizedPath = absPath;
// no direct resource found, so we have to drill down into the
// resource tree to find a match
resource = getAbsoluteResourceInternal(null, "/", parameters, true);
//no read access on / drilling further down
//SLING-5638
if (resource == null) {
resource = getAbsoluteResourceInternal(absPath, parameters, true);
if (resource != null) {
tokenizedPath = tokenizedPath.substring(resource.getPath().length());
}
}
final StringBuilder resolutionPath = new StringBuilder();
final StringTokenizer tokener = new StringTokenizer(tokenizedPath, "/");
while (resource != null && tokener.hasMoreTokens()) {
final String childNameRaw = tokener.nextToken();
Resource nextResource = getChildInternal(resource, childNameRaw);
if (nextResource != null) {
resource = nextResource;
resolutionPath.append("/").append(childNameRaw);
} else {
String childName = null;
final ResourcePathIterator rpi = new ResourcePathIterator(childNameRaw);
while (rpi.hasNext() && nextResource == null) {
childName = rpi.next();
nextResource = getChildInternal(resource, childName);
}
// switch the currentResource to the nextResource (may be
// null)
resource = nextResource;
resolutionPath.append("/").append(childName);
// terminate the search if a resource has been found
// with the extension cut off
if (nextResource != null) {
break;
}
}
}
// SLING-627: set the part cut off from the uriPath as
// sling.resolutionPathInfo property such that
// uriPath = curPath + sling.resolutionPathInfo
if (resource != null) {
final String path = resolutionPath.toString();
final String pathInfo = absPath.substring(path.length());
resource.getResourceMetadata().setResolutionPath(path);
resource.getResourceMetadata().setResolutionPathInfo(pathInfo);
resource.getResourceMetadata().setParameterMap(parameters);
logger.debug("resolveInternal: Found resource {} with path info {} for {}", new Object[] { resource, pathInfo,
absPath });
}
}
return resource;
}
private Resource getChildInternal(final Resource parent, final String childName) {
final String path;
if ( childName.startsWith("/") ) {
path = childName;
} else {
path = parent.getPath() + '/' + childName;
}
Resource child = getAbsoluteResourceInternal(parent, ResourceUtil.normalize(path), EMPTY_PARAMETERS, true );
if (child != null) {
final String alias = ResourceResolverControl.getProperty(child, PROP_REDIRECT_INTERNAL);
if (alias != null) {
// TODO: might be a redirect ??
logger.warn("getChildInternal: Internal redirect to {} for Resource {} is not supported yet, ignoring", alias,
child);
}
// we have the resource name, continue with the next level
return child;
}
// we do not have a child with the exact name, so we look for
// a child, whose alias matches the childName
if (factory.isOptimizeAliasResolutionEnabled()){
logger.debug("getChildInternal: Optimize Alias Resolution is Enabled");
//optimization made in SLING-2521
final Map<String, String> aliases = factory.getMapEntries().getAliasMap(parent.getPath());
if (aliases != null) {
final String aliasName = aliases.get(childName);
if (aliasName != null ) {
final String aliasPath;
if ( aliasName.startsWith("/") ) {
aliasPath = aliasName;
} else {
aliasPath = parent.getPath() + '/' + aliasName;
}
final Resource aliasedChild = getAbsoluteResourceInternal(parent, ResourceUtil.normalize(aliasPath), EMPTY_PARAMETERS, true );
logger.debug("getChildInternal: Found Resource {} with alias {} to use", aliasedChild, childName);
return aliasedChild;
}
}
} else {
logger.debug("getChildInternal: Optimize Alias Resolution is Disabled");
final Iterator<Resource> children = listChildren(parent);
while (children.hasNext()) {
child = children.next();
if (!child.getPath().endsWith(JCR_CONTENT_LEAF)) {
final String[] aliases = ResourceResolverControl.getProperty(child, PROP_ALIAS, String[].class);
if (aliases != null) {
for (final String alias : aliases) {
if (childName.equals(alias)) {
logger.debug("getChildInternal: Found Resource {} with alias {} to use", child, childName);
final Resource aliasedChild = getAbsoluteResourceInternal(parent, ResourceUtil.normalize(child.getPath()) , EMPTY_PARAMETERS, true);
return aliasedChild;
}
}
}
}
}
}
// no match for the childName found
logger.debug("getChildInternal: Resource {} has no child {}", parent, childName);
return null;
}
/**
* Creates a resource with the given path if existing
*/
private Resource getAbsoluteResourceInternal(@CheckForNull final Resource parent, @CheckForNull final String path, final Map<String, String> parameters, final boolean isResolve) {
if (path == null || path.length() == 0 || path.charAt(0) != '/') {
logger.debug("getResourceInternal: Path must be absolute {}", path);
return null; // path must be absolute
}
final Resource parentToUse;
if (parent != null && path.startsWith(parent.getPath())) {
parentToUse = parent;
} else {
parentToUse = null;
}
final Resource resource = this.control.getResource(this.context, path, parentToUse, parameters, isResolve);
if (resource != null) {
resource.getResourceMetadata().setResolutionPath(path);
resource.getResourceMetadata().setParameterMap(parameters);
return resource;
}
logger.debug("getResourceInternal: Cannot resolve path '{}' to a resource", path);
return null;
}
/**
* Creates a resource, traversing bottom up, to the highest readable resource.
*
*/
private Resource getAbsoluteResourceInternal(String absPath, final Map<String, String> parameters, final boolean isResolved) {
if (!absPath.contains("/") || "/".equals(absPath)) {
return null;
}
absPath = absPath.substring(absPath.indexOf("/"));
Resource resource = getAbsoluteResourceInternal(null, absPath, parameters, isResolved);
absPath = absPath.substring(0, absPath.lastIndexOf("/"));
while (!absPath.equals("")) {
Resource r = getAbsoluteResourceInternal(null, absPath, parameters, true);
if (r != null) {
resource = r;
}
absPath = absPath.substring(0, absPath.lastIndexOf("/"));
}
return resource;
}
/**
* Returns the <code>path</code> as an absolute path. If the path is already
* absolute it is returned unmodified (the same instance actually). If the
* path is relative it is made absolute by prepending the first entry of the
* {@link #getSearchPath() search path}.
*
* @param path
* The path to ensure absolute
* @return The absolute path as explained above
*/
private String ensureAbsPath(String path) {
if (!path.startsWith("/")) {
path = getSearchPath()[0] + path;
}
return path;
}
private String mangleNamespaces(String absPath) {
if (factory.isMangleNamespacePrefixes() && absPath != null && absPath.contains(MANGLE_NAMESPACE_OUT_SUFFIX)) {
final Matcher m = MANLE_NAMESPACE_OUT_PATTERN.matcher(absPath);
final StringBuffer buf = new StringBuffer();
while (m.find()) {
final String namespace = m.group(1);
try {
// throws if "namespace" is not a registered
// namespace prefix
final Session session = getSession();
if ( session != null ) {
session.getNamespaceURI(namespace);
final String replacement = MANGLE_NAMESPACE_IN_PREFIX + namespace + MANGLE_NAMESPACE_IN_SUFFIX;
m.appendReplacement(buf, replacement);
} else {
logger.debug("mangleNamespaces: '{}' is not a prefix, not mangling", namespace);
}
} catch (final NamespaceException ne) {
// not a valid prefix
logger.debug("mangleNamespaces: '{}' is not a prefix, not mangling", namespace);
} catch (final RepositoryException re) {
logger.warn("mangleNamespaces: Problem checking namespace '{}'", namespace, re);
}
}
m.appendTail(buf);
absPath = buf.toString();
}
return absPath;
}
private String unmangleNamespaces(String absPath) {
if (factory.isMangleNamespacePrefixes() && absPath.contains(MANGLE_NAMESPACE_IN_PREFIX)) {
final Matcher m = MANGLE_NAMESPACE_IN_PATTERN.matcher(absPath);
final StringBuffer buf = new StringBuffer();
while (m.find()) {
final String namespace = m.group(1);
try {
// throws if "namespace" is not a registered
// namespace prefix
final Session session = getSession();
if ( session != null ) {
session.getNamespaceURI(namespace);
final String replacement = MANGLE_NAMESPACE_OUT_PREFIX + namespace + MANGLE_NAMESPACE_OUT_SUFFIX;
m.appendReplacement(buf, replacement);
} else {
logger.debug("unmangleNamespaces: '{}' is not a prefix, not unmangling", namespace);
}
} catch (final NamespaceException ne) {
// not a valid prefix
logger.debug("unmangleNamespaces: '{}' is not a prefix, not unmangling", namespace);
} catch (final RepositoryException re) {
logger.warn("unmangleNamespaces: Problem checking namespace '{}'", namespace, re);
}
}
m.appendTail(buf);
absPath = buf.toString();
}
return absPath;
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#delete(org.apache.sling.api.resource.Resource)
*/
@Override
public void delete(final Resource resource)
throws PersistenceException {
// check if the resource is non existing - throws NPE if resource is null as stated in the API
if ( ResourceUtil.isNonExistingResource(resource) ) {
// nothing to do
return;
}
// if resource is null, we get an NPE as stated in the API
this.control.delete(this.context, resource);
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#create(org.apache.sling.api.resource.Resource, java.lang.String, Map)
*/
@Override
public Resource create(final Resource parent, final String name, final Map<String, Object> properties)
throws PersistenceException {
// if parent or name is null, we get an NPE as stated in the API
if ( name == null ) {
throw new NullPointerException("name");
}
// name should be a name not a path
if ( name.indexOf("/") != -1 ) {
throw new IllegalArgumentException("Name should not contain a slash: " + name);
}
final String path;
if ( parent.getPath().equals("/") ) {
path = parent.getPath() + name;
} else {
path = parent.getPath() + "/" + name;
}
// experimental code for handling synthetic resources
if ( ResourceUtil.isSyntheticResource(parent) ) {
Resource grandParent = parent.getParent();
if (grandParent != null) {
this.create(grandParent, parent.getName(), null);
} else {
throw new IllegalArgumentException("Can't create child on a synthetic root");
}
}
final Resource rsrc = this.control.create(this.context, path, properties);
rsrc.getResourceMetadata().setResolutionPath(rsrc.getPath());
return this.factory.getResourceDecoratorTracker().decorate(rsrc);
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#revert()
*/
@Override
public void revert() {
this.control.revert(this.context);
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#commit()
*/
@Override
public void commit() throws PersistenceException {
this.control.commit(this.context);
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#hasChanges()
*/
@Override
public boolean hasChanges() {
return this.control.hasChanges(this.context);
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#hasChildren()
*/
@Override
public boolean hasChildren(Resource resource) {
return listChildren(resource).hasNext();
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#getParentResourceType(org.apache.sling.api.resource.Resource)
*/
@Override
public String getParentResourceType(final Resource resource) {
String resourceSuperType = null;
if ( resource != null ) {
resourceSuperType = resource.getResourceSuperType();
if (resourceSuperType == null) {
resourceSuperType = this.getParentResourceType(resource.getResourceType());
}
}
return resourceSuperType;
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#getParentResourceType(java.lang.String)
*/
@Override
public String getParentResourceType(final String resourceType) {
return this.control.getParentResourceType(this.factory, this, resourceType);
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#isResourceType(org.apache.sling.api.resource.Resource, java.lang.String)
*/
@Override
public boolean isResourceType(final Resource resource, final String resourceType) {
boolean result = false;
if ( resource != null && resourceType != null ) {
// Check if the resource is of the given type. This method first checks the
// resource type of the resource, then its super resource type and continues
// to go up the resource super type hierarchy.
if (ResourceTypeUtil.areResourceTypesEqual(resourceType, resource.getResourceType(), getSearchPath())) {
result = true;
} else {
Set<String> superTypesChecked = new HashSet<String>();
String superType = this.getParentResourceType(resource);
while (!result && superType != null) {
if (ResourceTypeUtil.areResourceTypesEqual(resourceType, superType, getSearchPath())) {
result = true;
} else {
superTypesChecked.add(superType);
superType = this.getParentResourceType(superType);
if (superType != null && superTypesChecked.contains(superType)) {
throw new SlingException("Cyclic dependency for resourceSuperType hierarchy detected on resource " + resource.getPath(), null);
}
}
}
}
}
return result;
}
/**
* @see org.apache.sling.api.resource.ResourceResolver#refresh()
*/
@Override
public void refresh() {
this.control.refresh(this.context);
}
@Override
public Resource getParent(final Resource child) {
Resource rsrc = null;
final String parentPath = ResourceUtil.getParent(child.getPath());
if ( parentPath != null ) {
// if the parent path is relative, resolve using search paths.
if ( !parentPath.startsWith("/") ) {
rsrc = context.getResourceResolver().getResource(parentPath);
} else {
rsrc = this.control.getParent(this.context, parentPath, child);
if (rsrc != null ) {
rsrc.getResourceMetadata().setResolutionPath(rsrc.getPath());
rsrc = this.factory.getResourceDecoratorTracker().decorate(rsrc);
}
}
}
return rsrc;
}
@Override
public Resource copy(final String srcAbsPath, final String destAbsPath) throws PersistenceException {
Resource rsrc = this.control.copy(this.context, srcAbsPath, destAbsPath);
if (rsrc != null ) {
rsrc.getResourceMetadata().setResolutionPath(rsrc.getPath());
rsrc = this.factory.getResourceDecoratorTracker().decorate(rsrc);
}
return rsrc;
}
@Override
public Resource move(final String srcAbsPath, final String destAbsPath) throws PersistenceException {
Resource rsrc = this.control.move(this.context, srcAbsPath, destAbsPath);
if (rsrc != null ) {
rsrc.getResourceMetadata().setResolutionPath(rsrc.getPath());
rsrc = this.factory.getResourceDecoratorTracker().decorate(rsrc);
}
return rsrc;
}
}
| apache-2.0 |
liuyuanyuan/dbeaver | plugins/org.jkiss.dbeaver.ext.exasol/src/org/jkiss/dbeaver/ext/exasol/model/lock/ExasolLockItem.java | 3979 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2016-2016 Karl Griesser (fullref@gmail.com)
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ext.exasol.model.lock;
import org.jkiss.dbeaver.model.admin.locks.DBAServerLockItem;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.Property;
import java.sql.ResultSet;
import java.sql.Timestamp;
public class ExasolLockItem implements DBAServerLockItem {
private String sqlText;
private String userName;
private String host;
private String osUser;
private String osName;
private String scopeSchema;
private String status;
private String client;
private Integer resources;
private String priority;
private Timestamp loginTime;
private String driver;
private String activity;
private String commandName;
private String evaluation;
private String lockType;
@Property(viewable = true, order = 10)
public String getLockType()
{
return lockType;
}
ExasolLockItem(ResultSet dbResult) {
this.sqlText = JDBCUtils.safeGetString(dbResult, "SQL_TEXT");
this.userName = JDBCUtils.safeGetString(dbResult, "USER_NAME");
this.host = JDBCUtils.safeGetString(dbResult, "HOST");
this.osUser = JDBCUtils.safeGetString(dbResult, "OS_USER");
this.scopeSchema = JDBCUtils.safeGetString(dbResult, "SCOPE_SCHEMA");
this.status = JDBCUtils.safeGetString(dbResult, "STATUS");
this.client = JDBCUtils.safeGetString(dbResult, "CLIENT");
this.resources = JDBCUtils.safeGetInteger(dbResult, "RESOURCES");
this.priority = JDBCUtils.safeGetString(dbResult, "PRIORITY");
this.loginTime = JDBCUtils.safeGetTimestamp(dbResult, "LOGIN_TIME");
this.driver = JDBCUtils.safeGetString(dbResult, "DRIVER");
this.activity = JDBCUtils.safeGetString(dbResult, "ACTIVITY");
this.evaluation = JDBCUtils.safeGetString(dbResult, "EVALUATION");
this.lockType = JDBCUtils.safeGetString(dbResult, "HAS_LOCKS");
}
@Property(viewable = true, order = 150)
public String getSqlText()
{
return sqlText;
}
@Property(viewable = true, order = 20)
public String getUserName()
{
return userName;
}
@Property(viewable = true, order = 140)
public String getHost()
{
return host;
}
@Property(viewable = true, order = 30)
public String getOsUser()
{
return osUser;
}
@Property(viewable = true, order = 130)
public String getOsName()
{
return osName;
}
@Property(viewable = true, order = 120)
public String getScopeSchema()
{
return scopeSchema;
}
@Property(viewable = true, order = 40)
public String getStatus()
{
return status;
}
@Property(viewable = true, order = 50)
public String getClient()
{
return client;
}
@Property(viewable = true, order = 110)
public Integer getResources()
{
return resources;
}
@Property(viewable = true, order = 100)
public String getPriority()
{
return priority;
}
@Property(viewable = true, order = 60)
public Timestamp getLoginTime()
{
return loginTime;
}
public String getDriver()
{
return driver;
}
@Property(viewable = true, order = 90)
public String getActivity()
{
return activity;
}
@Property(viewable = true, order = 70)
public String getCommandName()
{
return commandName;
}
@Property(viewable = true, order = 80)
public String getEvaluation()
{
return evaluation;
}
public Timestamp ltime()
{
return this.loginTime;
}
}
| apache-2.0 |
apache/ant-easyant-core | src/test/java/org/apache/easyant/tasks/ImportDeferredTest.java | 9791 | /*
* 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.easyant.tasks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.easyant.core.EasyAntMagicNames;
import org.apache.easyant.core.ant.ProjectUtils;
import org.apache.ivy.ant.IvyConfigure;
import org.apache.ivy.ant.IvyDependency;
import org.apache.tools.ant.Location;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
public class ImportDeferredTest {
private ImportDeferred importTask;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Before
public void setUp() throws URISyntaxException, IOException {
Project project = new Project();
ProjectUtils.configureProjectHelper(project);
File cache = folder.newFolder("build-cache");
project.setProperty("ivy.cache.dir", cache.getAbsolutePath());
IvyConfigure configure = new IvyConfigure();
configure.setProject(project);
File f = new File(this.getClass().getResource("/repositories/easyant-ivysettings-test.xml").toURI());
configure.setFile(f);
configure.setSettingsId(EasyAntMagicNames.EASYANT_IVY_INSTANCE);
configure.execute();
ResolvePlugins resolvePlugins = new ResolvePlugins();
resolvePlugins.setProject(project);
IvyDependency simplePluginDependency = resolvePlugins.createDependency();
simplePluginDependency.setOrg("mycompany");
simplePluginDependency.setName("simpleplugin");
simplePluginDependency.setRev("0.1");
IvyDependency simplePluginWithPropertiesDependency = resolvePlugins.createDependency();
simplePluginWithPropertiesDependency.setOrg("mycompany");
simplePluginWithPropertiesDependency.setName("simplepluginwithproperties");
simplePluginWithPropertiesDependency.setRev("0.1");
resolvePlugins.execute();
importTask = new ImportDeferred();
importTask.setProject(project);
importTask.setOwningTarget(ProjectUtils.createTopLevelTarget());
importTask.setLocation(new Location(ProjectUtils.emulateMainScript(project).getAbsolutePath()));
}
@Test
public void shouldFailIfNoMandatoryAttributeAreSet() {
expectedException
.expectMessage("The module to import is not properly specified, you must set set organisation / module attributes");
importTask.execute();
}
@Test
public void shouldIncludeSimplePlugin() {
importTask.setOrg("mycompany");
importTask.setModule("simpleplugin");
importTask.setMode("include");
importTask.execute();
Path pluginClasspath = importTask.getProject().getReference("mycompany#simpleplugin.classpath");
org.junit.Assert.assertNotNull(pluginClasspath);
assertNotNull(pluginClasspath);
assertEquals(0, pluginClasspath.list().length);
}
@Test
public void shouldImportSimplePlugin() {
importTask.setOrg("mycompany");
importTask.setModule("simpleplugin");
importTask.execute();
Path pluginClasspath = importTask.getProject().getReference("mycompany#simpleplugin.classpath");
assertNotNull(pluginClasspath);
assertEquals(0, pluginClasspath.list().length);
}
@Test
public void shouldImportSimplePluginWithProperties() {
importTask.setOrg("mycompany");
importTask.setModule("simplepluginwithproperties");
importTask.execute();
verifySimplePluginWithPropertiesIsImported();
}
private void verifySimplePluginWithPropertiesIsImported() {
Path pluginClasspath = importTask.getProject().getReference("mycompany#simplepluginwithproperties.classpath");
assertNotNull(pluginClasspath);
assertEquals(0, pluginClasspath.list().length);
String propertiesFileLocation = importTask.getProject().getProperty(
"mycompany#simplepluginwithproperties.properties.file");
assertNotNull(propertiesFileLocation);
String srcMainJavaProperty = importTask.getProject().getProperty("src.main.java");
assertNotNull(srcMainJavaProperty);
assertEquals(importTask.getProject().getBaseDir() + "/src/main/java", srcMainJavaProperty);
// imported from property file
String aProperty = importTask.getProject().getProperty("aproperty");
assertNotNull(aProperty);
assertEquals("value", aProperty);
String anotherJavaProperty = importTask.getProject().getProperty("anotherproperty");
assertNotNull(anotherJavaProperty);
assertEquals("value", anotherJavaProperty);
}
@Test
public void shouldSkipSimplePlugin() {
importTask.getProject().setNewProperty("skip.mycompany#simplepluginwithproperties", "true");
importTask.setOrg("mycompany");
importTask.setModule("simplepluginwithproperties");
importTask.execute();
verifySimplePluginWithPropertiesIsSkipped();
}
private void verifySimplePluginWithPropertiesIsSkipped() {
Path pluginClasspath = importTask.getProject().getReference("mycompany#simplepluginwithproperties.classpath");
Assert.assertNull(pluginClasspath);
String propertiesFileLocation = importTask.getProject().getProperty(
"mycompany#simplepluginwithproperties.properties.file");
assertNull(propertiesFileLocation);
String srcMainJavaProperty = importTask.getProject().getProperty("src.main.java");
assertNull(srcMainJavaProperty);
// imported from property file
String aProperty = importTask.getProject().getProperty("aproperty");
assertNull(aProperty);
String anotherJavaProperty = importTask.getProject().getProperty("anotherproperty");
assertNull(anotherJavaProperty);
}
@Test
public void shouldSkipSimplePluginWithAsAttribute() {
importTask.getProject().setNewProperty("skip.myalias", "true");
importTask.setOrg("mycompany");
importTask.setModule("simplepluginwithproperties");
importTask.setAs("myalias");
importTask.execute();
verifySimplePluginWithPropertiesIsSkipped();
}
@Test
public void shouldNotSkipMandatoryPlugin() {
importTask.getProject().setNewProperty("skip.mycompany#simplepluginwithproperties;0.1", "true");
importTask.setOrg("mycompany");
importTask.setModule("simplepluginwithproperties");
importTask.setMandatory(true);
importTask.execute();
verifySimplePluginWithPropertiesIsImported();
}
@Test
public void shouldImportMandatoryPlugin() {
importTask.setOrg("mycompany");
importTask.setModule("simplepluginwithproperties");
importTask.setMandatory(true);
importTask.execute();
verifySimplePluginWithPropertiesIsImported();
}
@Test
public void shouldComputeAsAttributeOnInclude() {
importTask.setOrg("mycompany");
importTask.setModule("simpleplugin");
importTask.setMode("include");
importTask.execute();
// as attribute is preconfigured with module name
assertNotNull(importTask.getAs());
assertEquals("simpleplugin", importTask.getAs());
}
@Test
public void shouldFailBuildConfAreFound() {
expectedException.expectMessage("there is no available build configuration");
importTask.setOrg("mycompany");
importTask.setModule("simplepluginwithproperties");
importTask.setBuildConfigurations("amissingConf");
importTask.execute();
}
@Test
public void shouldNotImportIfBuildConfDoesntMatch() {
importTask.getProject().setProperty(EasyAntMagicNames.AVAILABLE_BUILD_CONFIGURATIONS, "aBuildConfNotActive");
importTask.setOrg("mycompany");
importTask.setModule("simplepluginwithproperties");
importTask.setBuildConfigurations("aBuildConfNotActive");
importTask.execute();
verifySimplePluginWithPropertiesIsSkipped();
}
@Test
public void shouldImportIfBuildConfMatch() {
importTask.getProject().setProperty(EasyAntMagicNames.AVAILABLE_BUILD_CONFIGURATIONS, "aBuildConfActive");
importTask.getProject().setProperty(EasyAntMagicNames.MAIN_CONFS, "aBuildConfActive");
importTask.setOrg("mycompany");
importTask.setModule("simplepluginwithproperties");
importTask.setBuildConfigurations("aBuildConfActive");
importTask.execute();
verifySimplePluginWithPropertiesIsImported();
}
}
| apache-2.0 |
mhurne/aws-sdk-java | aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/model/DataRetrievalRule.java | 7218 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.glacier.model;
import java.io.Serializable;
/**
* <p>
* Data retrieval policy rule.
* </p>
*/
public class DataRetrievalRule implements Serializable, Cloneable {
/**
* The type of data retrieval policy to set. <p>Valid values:
* BytesPerHour|FreeTier|None
*/
private String strategy;
/**
* The maximum number of bytes that can be retrieved in an hour. <p>This
* field is required only if the value of the Strategy field is
* <code>BytesPerHour</code>. Your PUT operation will be rejected if the
* Strategy field is not set to <code>BytesPerHour</code> and you set
* this field.
*/
private Long bytesPerHour;
/**
* The type of data retrieval policy to set. <p>Valid values:
* BytesPerHour|FreeTier|None
*
* @return The type of data retrieval policy to set. <p>Valid values:
* BytesPerHour|FreeTier|None
*/
public String getStrategy() {
return strategy;
}
/**
* The type of data retrieval policy to set. <p>Valid values:
* BytesPerHour|FreeTier|None
*
* @param strategy The type of data retrieval policy to set. <p>Valid values:
* BytesPerHour|FreeTier|None
*/
public void setStrategy(String strategy) {
this.strategy = strategy;
}
/**
* The type of data retrieval policy to set. <p>Valid values:
* BytesPerHour|FreeTier|None
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param strategy The type of data retrieval policy to set. <p>Valid values:
* BytesPerHour|FreeTier|None
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DataRetrievalRule withStrategy(String strategy) {
this.strategy = strategy;
return this;
}
/**
* The maximum number of bytes that can be retrieved in an hour. <p>This
* field is required only if the value of the Strategy field is
* <code>BytesPerHour</code>. Your PUT operation will be rejected if the
* Strategy field is not set to <code>BytesPerHour</code> and you set
* this field.
*
* @return The maximum number of bytes that can be retrieved in an hour. <p>This
* field is required only if the value of the Strategy field is
* <code>BytesPerHour</code>. Your PUT operation will be rejected if the
* Strategy field is not set to <code>BytesPerHour</code> and you set
* this field.
*/
public Long getBytesPerHour() {
return bytesPerHour;
}
/**
* The maximum number of bytes that can be retrieved in an hour. <p>This
* field is required only if the value of the Strategy field is
* <code>BytesPerHour</code>. Your PUT operation will be rejected if the
* Strategy field is not set to <code>BytesPerHour</code> and you set
* this field.
*
* @param bytesPerHour The maximum number of bytes that can be retrieved in an hour. <p>This
* field is required only if the value of the Strategy field is
* <code>BytesPerHour</code>. Your PUT operation will be rejected if the
* Strategy field is not set to <code>BytesPerHour</code> and you set
* this field.
*/
public void setBytesPerHour(Long bytesPerHour) {
this.bytesPerHour = bytesPerHour;
}
/**
* The maximum number of bytes that can be retrieved in an hour. <p>This
* field is required only if the value of the Strategy field is
* <code>BytesPerHour</code>. Your PUT operation will be rejected if the
* Strategy field is not set to <code>BytesPerHour</code> and you set
* this field.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param bytesPerHour The maximum number of bytes that can be retrieved in an hour. <p>This
* field is required only if the value of the Strategy field is
* <code>BytesPerHour</code>. Your PUT operation will be rejected if the
* Strategy field is not set to <code>BytesPerHour</code> and you set
* this field.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DataRetrievalRule withBytesPerHour(Long bytesPerHour) {
this.bytesPerHour = bytesPerHour;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getStrategy() != null) sb.append("Strategy: " + getStrategy() + ",");
if (getBytesPerHour() != null) sb.append("BytesPerHour: " + getBytesPerHour() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getStrategy() == null) ? 0 : getStrategy().hashCode());
hashCode = prime * hashCode + ((getBytesPerHour() == null) ? 0 : getBytesPerHour().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof DataRetrievalRule == false) return false;
DataRetrievalRule other = (DataRetrievalRule)obj;
if (other.getStrategy() == null ^ this.getStrategy() == null) return false;
if (other.getStrategy() != null && other.getStrategy().equals(this.getStrategy()) == false) return false;
if (other.getBytesPerHour() == null ^ this.getBytesPerHour() == null) return false;
if (other.getBytesPerHour() != null && other.getBytesPerHour().equals(this.getBytesPerHour()) == false) return false;
return true;
}
@Override
public DataRetrievalRule clone() {
try {
return (DataRetrievalRule) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!",
e);
}
}
}
| apache-2.0 |
freeVM/freeVM | enhanced/java/classlib/modules/swing/src/test/api/java.injected/javax/swing/event/TreeExpansionEventTest.java | 1616 | /*
* 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.
*/
/**
* @author Anton Avtamonov
*/
package javax.swing.event;
import javax.swing.BasicSwingTestCase;
import javax.swing.tree.TreePath;
public class TreeExpansionEventTest extends BasicSwingTestCase {
private TreeExpansionEvent event;
public TreeExpansionEventTest(final String name) {
super(name);
}
@Override
protected void tearDown() throws Exception {
event = null;
}
public void testTreeExpansionEvent() throws Exception {
Object source = new Object();
TreePath path = new TreePath("path");
event = new TreeExpansionEvent(source, path);
assertSame(source, event.getSource());
assertSame(path, event.getPath());
event = new TreeExpansionEvent(source, null);
assertNull(event.getPath());
}
}
| apache-2.0 |
liveqmock/platform-tools-idea | plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/ManualArrayCopyInspection.java | 23346 | /*
* Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ig.performance;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.ExpressionUtils;
import com.siyeh.ig.psiutils.ParenthesesUtils;
import com.siyeh.ig.psiutils.SideEffectChecker;
import com.siyeh.ig.psiutils.VariableAccessUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ManualArrayCopyInspection extends BaseInspection {
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message(
"manual.array.copy.display.name");
}
@Override
public boolean isEnabledByDefault() {
return true;
}
@Override
@NotNull
protected String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message(
"manual.array.copy.problem.descriptor");
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new ManualArrayCopyVisitor();
}
@Override
public InspectionGadgetsFix buildFix(Object... infos) {
final Boolean decrement = (Boolean)infos[0];
return new ManualArrayCopyFix(decrement.booleanValue());
}
private static class ManualArrayCopyFix extends InspectionGadgetsFix {
private final boolean decrement;
public ManualArrayCopyFix(boolean decrement) {
this.decrement = decrement;
}
@Override
@NotNull
public String getName() {
return InspectionGadgetsBundle.message("manual.array.copy.replace.quickfix");
}
@Override
public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
final PsiElement forElement = descriptor.getPsiElement();
final PsiForStatement forStatement = (PsiForStatement)forElement.getParent();
final String newExpression = buildSystemArrayCopyText(forStatement);
if (newExpression == null) {
return;
}
replaceStatement(forStatement, newExpression);
}
@Nullable
private String buildSystemArrayCopyText(PsiForStatement forStatement) throws IncorrectOperationException {
final PsiExpression condition = forStatement.getCondition();
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)ParenthesesUtils.stripParentheses(condition);
if (binaryExpression == null) {
return null;
}
final IElementType tokenType = binaryExpression.getOperationTokenType();
final PsiExpression limit;
if (decrement ^ JavaTokenType.LT.equals(tokenType) || JavaTokenType.LE.equals(tokenType)) {
limit = binaryExpression.getROperand();
}
else {
limit = binaryExpression.getLOperand();
}
if (limit == null) {
return null;
}
final PsiStatement initialization = forStatement.getInitialization();
if (initialization == null) {
return null;
}
if (!(initialization instanceof PsiDeclarationStatement)) {
return null;
}
final PsiDeclarationStatement declaration = (PsiDeclarationStatement)initialization;
final PsiElement[] declaredElements = declaration.getDeclaredElements();
if (declaredElements.length != 1) {
return null;
}
final PsiElement declaredElement = declaredElements[0];
if (!(declaredElement instanceof PsiLocalVariable)) {
return null;
}
final PsiLocalVariable variable = (PsiLocalVariable)declaredElement;
final String lengthText;
final PsiExpression initializer = variable.getInitializer();
if (decrement) {
lengthText = buildLengthText(initializer, limit, JavaTokenType.LE.equals(tokenType) || JavaTokenType.GE.equals(tokenType));
}
else {
lengthText = buildLengthText(limit, initializer, JavaTokenType.LE.equals(tokenType) || JavaTokenType.GE.equals(tokenType));
}
if (lengthText == null) {
return null;
}
final PsiArrayAccessExpression lhs = getLhsArrayAccessExpression(forStatement);
if (lhs == null) {
return null;
}
final PsiExpression lArray = lhs.getArrayExpression();
final String toArrayText = lArray.getText();
final PsiArrayAccessExpression rhs = getRhsArrayAccessExpression(forStatement);
if (rhs == null) {
return null;
}
final PsiExpression rArray = rhs.getArrayExpression();
final String fromArrayText = rArray.getText();
final PsiExpression rhsIndexExpression = rhs.getIndexExpression();
final PsiExpression strippedRhsIndexExpression = ParenthesesUtils.stripParentheses(rhsIndexExpression);
final PsiExpression limitExpression;
if (decrement) {
limitExpression = limit;
}
else {
limitExpression = initializer;
}
final String fromOffsetText = buildOffsetText(strippedRhsIndexExpression, variable, limitExpression, decrement &&
(JavaTokenType.LT.equals(tokenType) || JavaTokenType.GT.equals(tokenType)));
final PsiExpression lhsIndexExpression = lhs.getIndexExpression();
final PsiExpression strippedLhsIndexExpression = ParenthesesUtils.stripParentheses(lhsIndexExpression);
final String toOffsetText = buildOffsetText(strippedLhsIndexExpression, variable,
limitExpression, decrement && (JavaTokenType.LT.equals(tokenType) || JavaTokenType.GT.equals(tokenType)));
@NonNls final StringBuilder buffer = new StringBuilder(60);
buffer.append("System.arraycopy(");
buffer.append(fromArrayText);
buffer.append(", ");
buffer.append(fromOffsetText);
buffer.append(", ");
buffer.append(toArrayText);
buffer.append(", ");
buffer.append(toOffsetText);
buffer.append(", ");
buffer.append(lengthText);
buffer.append(");");
return buffer.toString();
}
@Nullable
private static PsiArrayAccessExpression getLhsArrayAccessExpression(
PsiForStatement forStatement) {
PsiStatement body = forStatement.getBody();
while (body instanceof PsiBlockStatement) {
final PsiBlockStatement blockStatement =
(PsiBlockStatement)body;
final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
final PsiStatement[] statements = codeBlock.getStatements();
if (statements.length == 2) {
body = statements[1];
}
else if (statements.length == 1) {
body = statements[0];
}
else {
return null;
}
}
if (!(body instanceof PsiExpressionStatement)) {
return null;
}
final PsiExpressionStatement expressionStatement =
(PsiExpressionStatement)body;
final PsiExpression expression =
expressionStatement.getExpression();
if (!(expression instanceof PsiAssignmentExpression)) {
return null;
}
final PsiAssignmentExpression assignmentExpression =
(PsiAssignmentExpression)expression;
final PsiExpression lhs = assignmentExpression.getLExpression();
final PsiExpression deparenthesizedExpression =
ParenthesesUtils.stripParentheses(lhs);
if (!(deparenthesizedExpression instanceof
PsiArrayAccessExpression)) {
return null;
}
return (PsiArrayAccessExpression)deparenthesizedExpression;
}
@Nullable
private static PsiArrayAccessExpression getRhsArrayAccessExpression(
PsiForStatement forStatement) {
PsiStatement body = forStatement.getBody();
while (body instanceof PsiBlockStatement) {
final PsiBlockStatement blockStatement =
(PsiBlockStatement)body;
final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
final PsiStatement[] statements = codeBlock.getStatements();
if (statements.length == 1 || statements.length == 2) {
body = statements[0];
}
else {
return null;
}
}
final PsiExpression arrayAccessExpression;
if (body instanceof PsiDeclarationStatement) {
final PsiDeclarationStatement declarationStatement =
(PsiDeclarationStatement)body;
final PsiElement[] declaredElements =
declarationStatement.getDeclaredElements();
if (declaredElements.length != 1) {
return null;
}
final PsiElement declaredElement = declaredElements[0];
if (!(declaredElement instanceof PsiVariable)) {
return null;
}
final PsiVariable variable = (PsiVariable)declaredElement;
arrayAccessExpression = variable.getInitializer();
}
else if (body instanceof PsiExpressionStatement) {
final PsiExpressionStatement expressionStatement =
(PsiExpressionStatement)body;
final PsiExpression expression =
expressionStatement.getExpression();
if (!(expression instanceof PsiAssignmentExpression)) {
return null;
}
final PsiAssignmentExpression assignmentExpression =
(PsiAssignmentExpression)expression;
arrayAccessExpression = assignmentExpression.getRExpression();
}
else {
return null;
}
final PsiExpression unparenthesizedExpression =
ParenthesesUtils.stripParentheses(arrayAccessExpression);
if (!(unparenthesizedExpression instanceof
PsiArrayAccessExpression)) {
return null;
}
return (PsiArrayAccessExpression)unparenthesizedExpression;
}
@NonNls
@Nullable
private static String buildLengthText(PsiExpression max, PsiExpression min, boolean plusOne) {
max = ParenthesesUtils.stripParentheses(max);
if (max == null) {
return null;
}
min = ParenthesesUtils.stripParentheses(min);
if (min == null) {
return buildExpressionText(max, plusOne, false);
}
final Object minConstant = ExpressionUtils.computeConstantExpression(min);
if (minConstant instanceof Number) {
final Number minNumber = (Number)minConstant;
final int minValue;
if (plusOne) {
minValue = minNumber.intValue() - 1;
}
else {
minValue = minNumber.intValue();
}
if (minValue == 0) {
return buildExpressionText(max, false, false);
}
if (max instanceof PsiLiteralExpression) {
final Object maxConstant = ExpressionUtils.computeConstantExpression(max);
if (maxConstant instanceof Number) {
final Number number = (Number)maxConstant;
return String.valueOf(number.intValue() - minValue);
}
}
final String maxText = buildExpressionText(max, false, false);
if (minValue > 0) {
return maxText + '-' + minValue;
}
else {
return maxText + '+' + -minValue;
}
}
final int precedence = ParenthesesUtils.getPrecedence(min);
final String minText;
if (precedence >= ParenthesesUtils.ADDITIVE_PRECEDENCE) {
minText = '(' + min.getText() + ')';
}
else {
minText = min.getText();
}
final String maxText = buildExpressionText(max, plusOne, false);
return maxText + '-' + minText;
}
private static String buildExpressionText(PsiExpression expression, boolean plusOne, boolean parenthesize) {
if (!plusOne) {
final int precedence = ParenthesesUtils.getPrecedence(expression);
if (precedence > ParenthesesUtils.ADDITIVE_PRECEDENCE) {
return '(' + expression.getText() + ')';
}
else {
if (parenthesize && precedence >= ParenthesesUtils.ADDITIVE_PRECEDENCE) {
return '(' + expression.getText() + ')';
}
return expression.getText();
}
}
if (expression instanceof PsiBinaryExpression) {
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression;
final IElementType tokenType = binaryExpression.getOperationTokenType();
if (tokenType == JavaTokenType.MINUS) {
final PsiExpression rhs = binaryExpression.getROperand();
if (ExpressionUtils.isOne(rhs)) {
return binaryExpression.getLOperand().getText();
}
}
}
else if (expression instanceof PsiLiteralExpression) {
final PsiLiteralExpression literalExpression = (PsiLiteralExpression)expression;
final Object value = literalExpression.getValue();
if (value instanceof Integer) {
final Integer integer = (Integer)value;
return String.valueOf(integer.intValue() + 1);
}
}
final int precedence = ParenthesesUtils.getPrecedence(expression);
final String result;
if (precedence > ParenthesesUtils.ADDITIVE_PRECEDENCE) {
result = '(' + expression.getText() + ")+1";
}
else {
result = expression.getText() + "+1";
}
if (parenthesize) {
return '(' + result + ')';
}
return result;
}
@NonNls
@Nullable
private static String buildOffsetText(PsiExpression expression,
PsiLocalVariable variable,
PsiExpression limitExpression,
boolean plusOne)
throws IncorrectOperationException {
if (expression == null) {
return null;
}
final String expressionText = expression.getText();
final String variableName = variable.getName();
if (expressionText.equals(variableName)) {
final PsiExpression initialValue =
ParenthesesUtils.stripParentheses(limitExpression);
if (initialValue == null) {
return null;
}
return buildExpressionText(initialValue, plusOne, false);
}
else if (expression instanceof PsiBinaryExpression) {
final PsiBinaryExpression binaryExpression =
(PsiBinaryExpression)expression;
final PsiExpression lhs = binaryExpression.getLOperand();
final PsiExpression rhs = binaryExpression.getROperand();
final String rhsText =
buildOffsetText(rhs, variable, limitExpression, plusOne);
final PsiJavaToken sign = binaryExpression.getOperationSign();
final IElementType tokenType = sign.getTokenType();
if (ExpressionUtils.isZero(lhs)) {
if (tokenType.equals(JavaTokenType.MINUS)) {
return '-' + rhsText;
}
return rhsText;
}
if (plusOne && tokenType.equals(JavaTokenType.MINUS) &&
ExpressionUtils.isOne(rhs)) {
return buildOffsetText(lhs, variable, limitExpression,
false);
}
final String lhsText = buildOffsetText(lhs, variable,
limitExpression, plusOne);
if (ExpressionUtils.isZero(rhs)) {
return lhsText;
}
return collapseConstant(lhsText + sign.getText() + rhsText,
variable);
}
return collapseConstant(expression.getText(), variable);
}
private static String collapseConstant(@NonNls String expressionText,
PsiElement context)
throws IncorrectOperationException {
final Project project = context.getProject();
final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
final PsiElementFactory factory = psiFacade.getElementFactory();
final PsiExpression fromOffsetExpression =
factory.createExpressionFromText(expressionText, context);
final Object fromOffsetConstant =
ExpressionUtils.computeConstantExpression(
fromOffsetExpression);
if (fromOffsetConstant != null) {
return fromOffsetConstant.toString();
}
else {
return expressionText;
}
}
}
private static class ManualArrayCopyVisitor extends BaseInspectionVisitor {
@Override
public void visitForStatement(
@NotNull PsiForStatement statement) {
super.visitForStatement(statement);
final PsiStatement initialization = statement.getInitialization();
if (!(initialization instanceof PsiDeclarationStatement)) {
return;
}
final PsiDeclarationStatement declaration =
(PsiDeclarationStatement)initialization;
final PsiElement[] declaredElements =
declaration.getDeclaredElements();
if (declaredElements.length != 1) {
return;
}
final PsiElement declaredElement = declaredElements[0];
if (!(declaredElement instanceof PsiLocalVariable)) {
return;
}
final PsiLocalVariable variable = (PsiLocalVariable)declaredElement;
final PsiExpression initialValue = variable.getInitializer();
if (initialValue == null) {
return;
}
final PsiStatement update = statement.getUpdate();
final boolean decrement;
if (VariableAccessUtils.variableIsIncremented(variable, update)) {
decrement = false;
}
else if (VariableAccessUtils.variableIsDecremented(variable,
update)) {
decrement = true;
}
else {
return;
}
final PsiExpression condition = statement.getCondition();
if (decrement) {
if (!ExpressionUtils.isVariableGreaterThanComparison(
condition, variable)) {
return;
}
}
else {
if (!ExpressionUtils.isVariableLessThanComparison(
condition, variable)) {
return;
}
}
final PsiStatement body = statement.getBody();
if (!bodyIsArrayCopy(body, variable, null)) {
return;
}
registerStatementError(statement, Boolean.valueOf(decrement));
}
private static boolean bodyIsArrayCopy(
PsiStatement body, PsiVariable variable,
@Nullable PsiVariable variable2) {
if (body instanceof PsiExpressionStatement) {
final PsiExpressionStatement exp =
(PsiExpressionStatement)body;
final PsiExpression expression = exp.getExpression();
return expressionIsArrayCopy(expression, variable, variable2);
}
else if (body instanceof PsiBlockStatement) {
final PsiBlockStatement blockStatement =
(PsiBlockStatement)body;
final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
final PsiStatement[] statements = codeBlock.getStatements();
if (statements.length == 1) {
return bodyIsArrayCopy(statements[0], variable, variable2);
}
else if (statements.length == 2) {
final PsiStatement statement = statements[0];
if (!(statement instanceof PsiDeclarationStatement)) {
return false;
}
final PsiDeclarationStatement declarationStatement =
(PsiDeclarationStatement)statement;
final PsiElement[] declaredElements =
declarationStatement.getDeclaredElements();
if (declaredElements.length != 1) {
return false;
}
final PsiElement declaredElement = declaredElements[0];
if (!(declaredElement instanceof PsiVariable)) {
return false;
}
final PsiVariable localVariable =
(PsiVariable)declaredElement;
final PsiExpression initializer =
localVariable.getInitializer();
if (!ExpressionUtils.isOffsetArrayAccess(initializer,
variable)) {
return false;
}
return bodyIsArrayCopy(statements[1], variable,
localVariable);
}
}
return false;
}
private static boolean expressionIsArrayCopy(
@Nullable PsiExpression expression,
@NotNull PsiVariable variable,
@Nullable PsiVariable variable2) {
final PsiExpression strippedExpression =
ParenthesesUtils.stripParentheses(expression);
if (strippedExpression == null) {
return false;
}
if (!(strippedExpression instanceof PsiAssignmentExpression)) {
return false;
}
final PsiAssignmentExpression assignment =
(PsiAssignmentExpression)strippedExpression;
final IElementType tokenType = assignment.getOperationTokenType();
if (!tokenType.equals(JavaTokenType.EQ)) {
return false;
}
final PsiExpression lhs = assignment.getLExpression();
if (SideEffectChecker.mayHaveSideEffects(lhs)) {
return false;
}
if (!ExpressionUtils.isOffsetArrayAccess(lhs, variable)) {
return false;
}
final PsiExpression rhs = assignment.getRExpression();
if (rhs == null) {
return false;
}
if (SideEffectChecker.mayHaveSideEffects(rhs)) {
return false;
}
if (!areExpressionsCopyable(lhs, rhs)) {
return false;
}
final PsiType type = lhs.getType();
if (type instanceof PsiPrimitiveType) {
final PsiExpression strippedLhs =
ParenthesesUtils.stripParentheses(lhs);
final PsiExpression strippedRhs =
ParenthesesUtils.stripParentheses(rhs);
if (!areExpressionsCopyable(strippedLhs, strippedRhs)) {
return false;
}
}
if (variable2 == null) {
return ExpressionUtils.isOffsetArrayAccess(rhs, variable);
}
else {
return VariableAccessUtils.evaluatesToVariable(rhs, variable2);
}
}
private static boolean areExpressionsCopyable(
@Nullable PsiExpression lhs, @Nullable PsiExpression rhs) {
if (lhs == null || rhs == null) {
return false;
}
final PsiType lhsType = lhs.getType();
if (lhsType == null) {
return false;
}
final PsiType rhsType = rhs.getType();
if (rhsType == null) {
return false;
}
if (lhsType instanceof PsiPrimitiveType) {
if (!lhsType.equals(rhsType)) {
return false;
}
}
else {
if (!lhsType.isAssignableFrom(rhsType) ||
rhsType instanceof PsiPrimitiveType) {
return false;
}
}
return true;
}
}
} | apache-2.0 |
roberthafner/flowable-engine | modules/flowable5-engine/src/main/java/org/activiti5/engine/impl/variable/JsonType.java | 2205 | /* 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.activiti5.engine.impl.variable;
import org.activiti.engine.impl.variable.ValueFields;
import org.activiti.engine.impl.variable.VariableType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author Tijs Rademakers
*/
public class JsonType implements VariableType {
private static final Logger logger = LoggerFactory.getLogger(JsonType.class);
protected final int maxLength;
protected ObjectMapper objectMapper;
public JsonType(int maxLength, ObjectMapper objectMapper) {
this.maxLength = maxLength;
this.objectMapper = objectMapper;
}
public String getTypeName() {
return "json";
}
public boolean isCachable() {
return true;
}
public Object getValue(ValueFields valueFields) {
JsonNode jsonValue = null;
if (valueFields.getTextValue() != null && valueFields.getTextValue().length() > 0) {
try {
jsonValue = objectMapper.readTree(valueFields.getTextValue());
} catch (Exception e) {
logger.error("Error reading json variable " + valueFields.getName(), e);
}
}
return jsonValue;
}
public void setValue(Object value, ValueFields valueFields) {
valueFields.setTextValue(value != null ? value.toString() : null);
}
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
if (JsonNode.class.isAssignableFrom(value.getClass())) {
JsonNode jsonValue = (JsonNode) value;
return jsonValue.toString().length() <= maxLength;
}
return false;
}
}
| apache-2.0 |
mayonghui2112/helloWorld | sourceCode/testMaven/onjava8/src/main/java/onjava/Repeat.java | 371 | // onjava/Repeat.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package onjava;
import static java.util.stream.IntStream.*;
public class Repeat {
public static void repeat(int n, Runnable action) {
range(0, n).forEach(i -> action.run());
}
}
| apache-2.0 |
weebl2000/modeshape | modeshape-jcr/src/main/java/org/modeshape/jcr/index/local/LocalDuplicateIndex.java | 5102 | /*
* ModeShape (http://www.modeshape.org)
*
* 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.modeshape.jcr.index.local;
import java.util.Comparator;
import java.util.concurrent.atomic.AtomicLong;
import javax.jcr.query.qom.StaticOperand;
import org.mapdb.DB;
import org.mapdb.Fun;
import org.mapdb.Serializer;
import org.modeshape.common.logging.Logger;
import org.modeshape.jcr.cache.NodeKey;
import org.modeshape.jcr.index.local.IndexValues.Converter;
import org.modeshape.jcr.index.local.MapDB.UniqueKey;
import org.modeshape.jcr.spi.index.Index;
/**
* An {@link Index} that associates a single value with multiple {@link NodeKey}s. All values are stored in natural sort order,
* allowing finding all the node keys for a range of values.
*
* @param <T> the type of values
* @author Randall Hauch (rhauch@redhat.com)
*/
final class LocalDuplicateIndex<T> extends LocalMapIndex<UniqueKey<T>, T> {
/**
* Create a new index that allows duplicate values across all keys.
*
* @param name the name of the index; may not be null or empty
* @param workspaceName the name of the workspace; may not be null
* @param db the database in which the index information is to be stored; may not be null
* @param converter the converter from {@link StaticOperand} to values being indexed; may not be null
* @param valueSerializer the serializer for the type of value being indexed
* @param comparator the comparator for the values; may not be null
* @return the new index; never null
*/
static <T> LocalDuplicateIndex<T> create( String name,
String workspaceName,
DB db,
Converter<T> converter,
Serializer<T> valueSerializer,
Comparator<T> comparator ) {
return new LocalDuplicateIndex<>(name, workspaceName, db, converter, valueSerializer, comparator);
}
private static final String NEXT_COUNTER = "next-counter";
private final Logger logger = Logger.getLogger(getClass());
private final AtomicLong counter;
protected LocalDuplicateIndex( String name,
String workspaceName,
DB db,
Converter<T> converter,
Serializer<T> valueSerializer,
Comparator<T> comparator ) {
super(name, workspaceName, db, IndexValues.uniqueKeyConverter(converter), MapDB.uniqueKeyBTreeSerializer(valueSerializer,
comparator),
MapDB.uniqueKeySerializer(valueSerializer, comparator));
Long nextCounter = (Long)options.get(NEXT_COUNTER);
this.counter = new AtomicLong(nextCounter != null ? nextCounter : -1L);
}
@Override
public void add( String nodeKey,
String propertyName,
T value ) {
logger.trace("Adding node '{0}' to '{1}' index with value '{2}'", nodeKey, name, value);
// Store the value of the next counter in the options map first so in the case of a failure we'll pick up at least from there
long nextId = (long) options.compute(NEXT_COUNTER, (key, val) -> counter.incrementAndGet());
// then store the data in the index
keysByValue.compute(new UniqueKey<T>(value, nextId), (key, val) -> nodeKey);
}
@Override
public void remove( String nodeKey,
String propertyName,
T value ) {
// Find all of the T values (entry keys) for the given node key (entry values) and remove those which have value 'value'
for (UniqueKey<T> key : Fun.filter(valuesByKey, nodeKey)) {
if (key.actualKey.equals(value)) {
logger.trace("Removing node '{0}' from '{1}' index with value '{2}'", nodeKey, name, key.actualKey);
keysByValue.remove(key);
}
}
}
@Override
public void remove( String nodeKey ) {
// Find all of the T values (entry keys) for the given node key (entry values) ...
for (UniqueKey<T> key : Fun.filter(valuesByKey, nodeKey)) {
logger.trace("Removing node '{0}' from '{1}' index with value '{2}'", nodeKey, name, key.actualKey);
keysByValue.remove(key);
}
}
}
| apache-2.0 |
runepeter/maven-deploy-plugin-2.8.1 | maven-model/src/test/java/org/apache/maven/model/SiteTest.java | 1441 | package org.apache.maven.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import junit.framework.TestCase;
/**
* Tests {@code Site}.
*
* @author Benjamin Bentmann
*/
public class SiteTest
extends TestCase
{
public void testHashCodeNullSafe()
{
new Site().hashCode();
}
public void testEqualsNullSafe()
{
assertFalse( new Site().equals( null ) );
new Site().equals( new Site() );
}
public void testEqualsIdentity()
{
Site thing = new Site();
assertTrue( thing.equals( thing ) );
}
public void testToStringNullSafe()
{
assertNotNull( new Site().toString() );
}
}
| apache-2.0 |
RLDevOps/Scholastic | src/main/java/org/olat/resource/references/ReferenceImpl.java | 2457 | /**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <p>
*/
package org.olat.resource.references;
import org.olat.core.commons.persistence.PersistentObject;
import org.olat.core.logging.AssertException;
import org.olat.resource.OLATResourceImpl;
/**
* Initial Date: May 27, 2004
*
* @author Mike Stock Comment:
*/
public class ReferenceImpl extends PersistentObject {
// FIXME:ms:c (by fj) extract interface Reference
private OLATResourceImpl source;
private OLATResourceImpl target;
private String userdata;
private static final int USERDATA_MAXLENGTH = 64;
protected ReferenceImpl() {
// hibernate
}
/**
* @param source
* @param target
* @param userdata
*/
public ReferenceImpl(final OLATResourceImpl source, final OLATResourceImpl target, final String userdata) {
this.source = source;
this.target = target;
this.userdata = userdata;
}
/**
* @return Returns the source.
*/
public OLATResourceImpl getSource() {
return source;
}
/**
* @param source The source to set.
*/
public void setSource(final OLATResourceImpl source) {
this.source = source;
}
/**
* @return Returns the target.
*/
public OLATResourceImpl getTarget() {
return target;
}
/**
* @param target The target to set.
*/
public void setTarget(final OLATResourceImpl target) {
this.target = target;
}
/**
* @return Returns the userdata.
*/
public String getUserdata() {
return userdata;
}
/**
* @param userdata The userdata to set.
*/
public void setUserdata(final String userdata) {
if (userdata != null && userdata.length() > USERDATA_MAXLENGTH) { throw new AssertException("field userdata of table o_reference too long"); }
this.userdata = userdata;
}
}
| apache-2.0 |
flofreud/aws-sdk-java | aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/Region.java | 9533 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.s3.model;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.regions.RegionUtils;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.internal.Constants;
/**
* Specifies constants that define Amazon S3 Regions.
* <p>
* Amazon S3 Regions allow the user to choose the geographical region where Amazon S3
* will store the buckets the user creates. Choose a Amazon S3 Region to optimize
* latency, minimize costs, or address regulatory requirements.
* </p>
* <p>
* Objects stored in a Amazon S3 Region never leave that region unless explicitly
* transferred to another region.
* </p>
* <p>
* In Amazon S3, all the regions provides
* read-after-write consistency for PUTS of new objects in Amazon
* S3 buckets and eventual consistency for overwrite PUTS and DELETES.
* </p>
*/
public enum Region {
/**
* The US Standard Amazon S3 Region. This region
* uses Amazon S3 servers located in the United
* States.
* <p>
* This is the default Amazon S3 Region. All requests sent to
* <code>s3.amazonaws.com</code> go
* to this region unless a location constraint is specified when creating a bucket.
* The US Standard Region automatically places
* data in either Amazon's east or west coast data centers depending on
* which one provides the lowest latency.
* </p>
*/
US_Standard((String[])null),
/**
* The US-West (Northern California) Amazon S3 Region. This region uses Amazon S3
* servers located in Northern California.
* <p>
* When using buckets in this region, set the client
* endpoint to <code>s3-us-west-1.amazonaws.com</code> on all requests to these
* buckets to reduce any latency experienced after the first
* hour of creating a bucket in this region.
* </p>
*/
US_West("us-west-1"),
/**
* The US-West-2 (Oregon) Region. This region uses Amazon S3 servers located
* in Oregon.
* <p>
* When using buckets in this region, set the client
* endpoint to <code>s3-us-west-2.amazonaws.com</code> on all requests to these buckets
* to reduce any latency experienced after the first hour of
* creating a bucket in this region.
* </p>
*/
US_West_2("us-west-2"),
/**
* The US GovCloud Region. This region uses Amazon S3 servers located in the Northwestern
* region of the United States.
*/
US_GovCloud("us-gov-west-1"),
/**
* The EU (Ireland) Amazon S3 Region. This region uses Amazon S3 servers located
* in Ireland.
*/
EU_Ireland("eu-west-1","EU"),
/**
* The EU (Frankfurt) Amazon S3 Region. This region uses Amazon S3 servers
* located in Frankfurt.
* <p>
* The EU (Frankfurt) Region requires AWS V4 authentication, therefore when
* accessing buckets inside this region, you need to explicitly configure
* the "eu-central-1" endpoint for the AmazonS3Client in order to enable V4
* signing:
*
* <pre>
* AmazonS3Client s3 = new AmazonS3Client();
* s3.setRegion(RegionUtils.getRegion("eu-central-1"));
* </pre>
*
* </p>
*
* @see AmazonS3Client#setEndpoint(String)
* @see AmazonS3Client#setRegion(com.amazonaws.regions.Region)
*/
EU_Frankfurt("eu-central-1"),
/**
* The Asia Pacific (Singapore) Region. This region uses Amazon S3 servers located
* in Singapore.
* <p>
* When using buckets in this region, set the client
* endpoint to <code>s3-ap-southeast-1.amazonaws.com</code> on all requests to these buckets
* to reduce any latency experienced after the first hour of
* creating a bucket in this region.
* </p>
*/
AP_Singapore("ap-southeast-1"),
/**
* The Asia Pacific (Sydney) Region. This region uses Amazon S3 servers
* located in Sydney, Australia.
* <p>
* When using buckets in this region, set the client endpoint to
* <code>s3-ap-southeast-2.amazonaws.com</code> on all requests to these buckets
* to reduce any latency experienced after the first hour of creating a
* bucket in this region.
* </p>
*/
AP_Sydney("ap-southeast-2"),
/**
* The Asia Pacific (Tokyo) Region. This region uses Amazon S3 servers
* located in Tokyo.
* <p>
* When using buckets in this region, set the client endpoint to
* <code>s3-ap-northeast-1.amazonaws.com</code> on all requests to these
* buckets to reduce any latency experienced after the first hour of
* creating a bucket in this region.
* </p>
*/
AP_Tokyo("ap-northeast-1"),
/**
* The Asia Pacific (Seoul) Region. This region uses Amazon S3 servers
* located in Seoul.
* <p>
* When using buckets in this region, set the client endpoint to
* <code>s3.ap-northeast-2.amazonaws.com</code> on all requests to these
* buckets to reduce any latency experienced after the first hour of
* creating a bucket in this region.
* </p>
*/
AP_Seoul("ap-northeast-2"),
/**
* The South America (Sao Paulo) Region. This region uses Amazon S3 servers
* located in Sao Paulo.
* <p>
* When using buckets in this region, set the client endpoint to
* <code>s3-sa-east-1.amazonaws.com</code> on all requests to these buckets
* to reduce any latency experienced after the first hour of creating a
* bucket in this region.
* </p>
*/
SA_SaoPaulo("sa-east-1"),
/**
* The China (Beijing) Region. This region uses Amazon S3 servers
* located in Beijing.
* <p>
* When using buckets in this region, you must set the client endpoint to
* <code>s3.cn-north-1.amazonaws.com.cn</code>.
*/
CN_Beijing("cn-north-1");
/**
* Used to extract the S3 regional id from an S3 end point.
* Note this pattern will not match the S3 US standard endpoint by intent.
* Exampless:
* <pre>
* s3-eu-west-1.amazonaws.com
* s3.cn-north-1.amazonaws.com.cn
* </pre>
*/
public static final Pattern S3_REGIONAL_ENDPOINT_PATTERN =
Pattern.compile("s3[-.]([^.]+)\\.amazonaws\\.com(\\.[^.]*)?");
/** The list of ID's representing each region. */
private final List<String> regionIds;
/**
* Constructs a new region with the specified region ID's.
*
* @param regionIds
* The list of ID's representing the S3 region.
*/
private Region(String... regionIds) {
this.regionIds = regionIds != null ? Arrays.asList(regionIds) : null;
}
/*
* (non-Javadoc)
*
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return getFirstRegionId0();
}
/**
* Returns the first region id or null for {@link #US_Standard}.
*/
public String getFirstRegionId() {
return getFirstRegionId0();
}
private String getFirstRegionId0() {
return this.regionIds == null || regionIds.size() == 0
? null : this.regionIds.get(0);
}
/**
* Returns the Amazon S3 Region enumeration value representing the specified Amazon
* S3 Region ID string. If specified string doesn't map to a known Amazon S3
* Region, then an <code>IllegalArgumentException</code> is thrown.
*
* @param s3RegionId
* The Amazon S3 region ID string.
*
* @return The Amazon S3 Region enumeration value representing the specified Amazon
* S3 Region ID.
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known
* Amazon S3 regions.
*/
public static Region fromValue(final String s3RegionId) throws IllegalArgumentException
{
if (s3RegionId == null || s3RegionId.equals("US"))
return Region.US_Standard;
for (Region region : Region.values()) {
List<String> regionIds = region.regionIds;
if (regionIds != null && regionIds.contains(s3RegionId))
return region;
}
throw new IllegalArgumentException(
"Cannot create enum from " + s3RegionId + " value!");
}
/**
* Returns the respective AWS region.
*/
public com.amazonaws.regions.Region toAWSRegion() {
String s3regionId = getFirstRegionId();
if ( s3regionId == null ) { // US Standard
// TODO This is a bit of a hack but customers are relying on this returning us-east-1 rather then
// aws-global. For now we'll keep the legacy behavior and consider changing it in the next major version
// bump. See TT0073140598
return RegionUtils.getRegion("us-east-1");
} else {
return RegionUtils.getRegion(s3regionId);
}
}
}
| apache-2.0 |
optimizely/incubator-zeppelin | zeppelin-server/src/test/java/org/apache/zeppelin/rest/InterpreterRestApiTest.java | 7772 | /*
* 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.zeppelin.rest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.zeppelin.interpreter.InterpreterSetting;
import org.apache.zeppelin.notebook.Note;
import org.apache.zeppelin.notebook.Paragraph;
import org.apache.zeppelin.scheduler.Job.Status;
import org.apache.zeppelin.server.ZeppelinServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import static org.junit.Assert.*;
/**
* Zeppelin interpreter rest api tests
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class InterpreterRestApiTest extends AbstractTestRestApi {
Gson gson = new Gson();
@BeforeClass
public static void init() throws Exception {
AbstractTestRestApi.startUp();
}
@AfterClass
public static void destroy() throws Exception {
AbstractTestRestApi.shutDown();
}
@Test
public void getAvailableInterpreters() throws IOException {
// when
GetMethod get = httpGet("/interpreter");
// then
assertThat(get, isAllowed());
Map<String, Object> resp = gson.fromJson(get.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {
}.getType());
Map<String, Object> body = (Map<String, Object>) resp.get("body");
assertEquals(ZeppelinServer.notebook.getInterpreterFactory().getAvailableInterpreterSettings().size(), body.size());
get.releaseConnection();
}
@Test
public void getSettings() throws IOException {
// when
GetMethod get = httpGet("/interpreter/setting");
// then
Map<String, Object> resp = gson.fromJson(get.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {
}.getType());
assertThat(get, isAllowed());
get.releaseConnection();
}
@Test
public void testSettingsCRUD() throws IOException {
// Call Create Setting REST API
String jsonRequest = "{\"name\":\"md2\",\"group\":\"md\",\"properties\":{\"propname\":\"propvalue\"}," +
"\"interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\",\"name\":\"md\"}]," +
"\"dependencies\":[]," +
"\"option\": { \"remote\": true, \"perNoteSession\": false }}";
PostMethod post = httpPost("/interpreter/setting/", jsonRequest);
LOG.info("testSettingCRUD create response\n" + post.getResponseBodyAsString());
assertThat("test create method:", post, isCreated());
Map<String, Object> resp = gson.fromJson(post.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {
}.getType());
Map<String, Object> body = (Map<String, Object>) resp.get("body");
//extract id from body string {id=2AWMQDNX7, name=md2, group=md,
String newSettingId = body.toString().split(",")[0].split("=")[1];
post.releaseConnection();
// Call Update Setting REST API
jsonRequest = "{\"name\":\"md2\",\"group\":\"md\",\"properties\":{\"propname\":\"Otherpropvalue\"}," +
"\"interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\",\"name\":\"md\"}]," +
"\"dependencies\":[]," +
"\"option\": { \"remote\": true, \"perNoteSession\": false }}";
PutMethod put = httpPut("/interpreter/setting/" + newSettingId, jsonRequest);
LOG.info("testSettingCRUD update response\n" + put.getResponseBodyAsString());
assertThat("test update method:", put, isAllowed());
put.releaseConnection();
// Call Delete Setting REST API
DeleteMethod delete = httpDelete("/interpreter/setting/" + newSettingId);
LOG.info("testSettingCRUD delete response\n" + delete.getResponseBodyAsString());
assertThat("Test delete method:", delete, isAllowed());
delete.releaseConnection();
}
@Test
public void testInterpreterAutoBinding() throws IOException {
// create note
Note note = ZeppelinServer.notebook.createNote(null);
// check interpreter is binded
GetMethod get = httpGet("/notebook/interpreter/bind/" + note.id());
assertThat(get, isAllowed());
get.addRequestHeader("Origin", "http://localhost");
Map<String, Object> resp = gson.fromJson(get.getResponseBodyAsString(), new TypeToken<Map<String, Object>>() {
}.getType());
List<Map<String, String>> body = (List<Map<String, String>>) resp.get("body");
assertTrue(0 < body.size());
get.releaseConnection();
//cleanup
ZeppelinServer.notebook.removeNote(note.getId(), null);
}
@Test
public void testInterpreterRestart() throws IOException, InterruptedException {
// create new note
Note note = ZeppelinServer.notebook.createNote(null);
note.addParagraph();
Paragraph p = note.getLastParagraph();
Map config = p.getConfig();
config.put("enabled", true);
// run markdown paragraph
p.setConfig(config);
p.setText("%md markdown");
note.run(p.getId());
while (p.getStatus() != Status.FINISHED) {
Thread.sleep(100);
}
assertEquals("<p>markdown</p>\n", p.getResult().message());
// restart interpreter
for (InterpreterSetting setting : ZeppelinServer.notebook.getInterpreterFactory().getInterpreterSettings(note.getId())) {
if (setting.getName().equals("md")) {
// Call Restart Interpreter REST API
PutMethod put = httpPut("/interpreter/setting/restart/" + setting.getId(), "");
assertThat("test interpreter restart:", put, isAllowed());
put.releaseConnection();
break;
}
}
// run markdown paragraph, again
p = note.addParagraph();
p.setConfig(config);
p.setText("%md markdown restarted");
note.run(p.getId());
while (p.getStatus() != Status.FINISHED) {
Thread.sleep(100);
}
assertEquals("<p>markdown restarted</p>\n", p.getResult().message());
//cleanup
ZeppelinServer.notebook.removeNote(note.getId(), null);
}
@Test
public void testListRepository() throws IOException {
GetMethod get = httpGet("/interpreter/repository");
assertThat(get, isAllowed());
get.releaseConnection();
}
@Test
public void testAddDeleteRepository() throws IOException {
// Call create repository REST API
String repoId = "securecentral";
String jsonRequest = "{\"id\":\"" + repoId +
"\",\"url\":\"https://repo1.maven.org/maven2\",\"snapshot\":\"false\"}";
PostMethod post = httpPost("/interpreter/repository/", jsonRequest);
assertThat("Test create method:", post, isCreated());
post.releaseConnection();
// Call delete repository REST API
DeleteMethod delete = httpDelete("/interpreter/repository/" + repoId);
assertThat("Test delete method:", delete, isAllowed());
delete.releaseConnection();
}
}
| apache-2.0 |
adbrucker/SecureBPMN | designer/src/org.activiti.designer.model/src/main/java/org/eclipse/bpmn2/di/impl/BpmnDiFactoryImpl.java | 6676 | /**
* <copyright>
*
* Copyright (c) 2010 SAP AG.
* 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:
* Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation
*
* </copyright>
*/
package org.eclipse.bpmn2.di.impl;
import org.eclipse.bpmn2.di.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class BpmnDiFactoryImpl extends EFactoryImpl implements BpmnDiFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static BpmnDiFactory init() {
try {
BpmnDiFactory theBpmnDiFactory = (BpmnDiFactory) EPackage.Registry.INSTANCE
.getEFactory("http://www.omg.org/spec/BPMN/20100524/DI-XMI");
if (theBpmnDiFactory != null) {
return theBpmnDiFactory;
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new BpmnDiFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BpmnDiFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case BpmnDiPackage.DOCUMENT_ROOT:
return createDocumentRoot();
case BpmnDiPackage.BPMN_DIAGRAM:
return createBPMNDiagram();
case BpmnDiPackage.BPMN_EDGE:
return createBPMNEdge();
case BpmnDiPackage.BPMN_LABEL:
return createBPMNLabel();
case BpmnDiPackage.BPMN_LABEL_STYLE:
return createBPMNLabelStyle();
case BpmnDiPackage.BPMN_PLANE:
return createBPMNPlane();
case BpmnDiPackage.BPMN_SHAPE:
return createBPMNShape();
default:
throw new IllegalArgumentException("The class '" + eClass.getName()
+ "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case BpmnDiPackage.MESSAGE_VISIBLE_KIND:
return createMessageVisibleKindFromString(eDataType, initialValue);
case BpmnDiPackage.PARTICIPANT_BAND_KIND:
return createParticipantBandKindFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '"
+ eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case BpmnDiPackage.MESSAGE_VISIBLE_KIND:
return convertMessageVisibleKindToString(eDataType, instanceValue);
case BpmnDiPackage.PARTICIPANT_BAND_KIND:
return convertParticipantBandKindToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '"
+ eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BPMNDiagram createBPMNDiagram() {
BPMNDiagramImpl bpmnDiagram = new BPMNDiagramImpl();
return bpmnDiagram;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BPMNEdge createBPMNEdge() {
BPMNEdgeImpl bpmnEdge = new BPMNEdgeImpl();
return bpmnEdge;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BPMNLabel createBPMNLabel() {
BPMNLabelImpl bpmnLabel = new BPMNLabelImpl();
return bpmnLabel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BPMNLabelStyle createBPMNLabelStyle() {
BPMNLabelStyleImpl bpmnLabelStyle = new BPMNLabelStyleImpl();
return bpmnLabelStyle;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BPMNPlane createBPMNPlane() {
BPMNPlaneImpl bpmnPlane = new BPMNPlaneImpl();
return bpmnPlane;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BPMNShape createBPMNShape() {
BPMNShapeImpl bpmnShape = new BPMNShapeImpl();
return bpmnShape;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MessageVisibleKind createMessageVisibleKindFromString(
EDataType eDataType, String initialValue) {
MessageVisibleKind result = MessageVisibleKind.get(initialValue);
if (result == null)
throw new IllegalArgumentException("The value '" + initialValue
+ "' is not a valid enumerator of '" + eDataType.getName()
+ "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertMessageVisibleKindToString(EDataType eDataType,
Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ParticipantBandKind createParticipantBandKindFromString(
EDataType eDataType, String initialValue) {
ParticipantBandKind result = ParticipantBandKind.get(initialValue);
if (result == null)
throw new IllegalArgumentException("The value '" + initialValue
+ "' is not a valid enumerator of '" + eDataType.getName()
+ "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertParticipantBandKindToString(EDataType eDataType,
Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BpmnDiPackage getBpmnDiPackage() {
return (BpmnDiPackage) getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static BpmnDiPackage getPackage() {
return BpmnDiPackage.eINSTANCE;
}
} //BpmnDiFactoryImpl
| apache-2.0 |
Thopap/camel | components/camel-zookeeper/src/test/java/org/apache/camel/component/zookeeper/ha/SpringZooKeeperClusteredRouteConfigurationTest.java | 1833 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.zookeeper.ha;
import org.apache.camel.ha.CamelClusterService;
import org.apache.camel.impl.ha.ClusteredRoutePolicyFactory;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringZooKeeperClusteredRouteConfigurationTest extends CamelSpringTestSupport {
@Test
public void test() {
assertNotNull(context.hasService(CamelClusterService.class));
assertTrue(context.getRoutePolicyFactories().stream().anyMatch(ClusteredRoutePolicyFactory.class::isInstance));
}
// ***********************
// Routes
// ***********************
@Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/component/zookeeper/ha/SpringZooKeeperClusteredRouteConfigurationTest.xml");
}
}
| apache-2.0 |
codescale/logging-log4j2 | log4j-core/src/test/java/org/apache/logging/log4j/core/filter/ScriptFilterTest.java | 1400 | /*
* 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.logging.log4j.core.filter;
import org.apache.logging.log4j.categories.Scripts;
import org.apache.logging.log4j.junit.LoggerContextRule;
import org.junit.ClassRule;
import org.junit.experimental.categories.Category;
/**
*
*/
@Category(Scripts.Groovy.class)
public class ScriptFilterTest extends AbstractScriptFilterTest {
private static final String CONFIG = "log4j-script-filters.xml";
@ClassRule
public static LoggerContextRule context = new LoggerContextRule(CONFIG);
@Override
public LoggerContextRule getContext() {
return context;
}
}
| apache-2.0 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/blocking/provider/BlockedErrorExtensionProvider.java | 1348 | /**
*
* Copyright 2016 Fernando Ramirez
*
* 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.blocking.provider;
import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smackx.blocking.element.BlockedErrorExtension;
/**
* Blocked error extension class.
*
* @author Fernando Ramirez
* @see <a href="http://xmpp.org/extensions/xep-0191.html">XEP-0191: Blocking
* Command</a>
*/
public class BlockedErrorExtensionProvider extends ExtensionElementProvider<BlockedErrorExtension> {
@Override
public BlockedErrorExtension parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) {
return new BlockedErrorExtension();
}
}
| apache-2.0 |
tkaefer/camunda-bpm-platform | engine-rest/src/test/java/org/camunda/bpm/engine/rest/util/DtoUtilTest.java | 10855 | package org.camunda.bpm.engine.rest.util;
import static org.fest.assertions.Assertions.assertThat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.camunda.bpm.engine.rest.dto.runtime.VariableValueDto;
import org.junit.Test;
public class DtoUtilTest {
@Test
public void testDtoUtilToMap_String() throws Exception {
// given
String type = "String";
String firstTestValue = "aTestValue";
String firstTestVar = "firstTestVar";
String secondTestValue = null;
String secondTestVar = "secondTestVar";
String thirdTestValue = "";
String thirdTestVar = "thirdTestVar";
Integer fourthTestValue = 5;
String fourthTestVar = "fourthTestVar";
Map<String, VariableValueDto> variables = new HashMap<String, VariableValueDto>();
variables.put(firstTestVar, new VariableValueDto(firstTestValue, type));
variables.put(secondTestVar, new VariableValueDto(secondTestValue, type));
variables.put(thirdTestVar, new VariableValueDto(thirdTestValue, type));
variables.put(fourthTestVar, new VariableValueDto(fourthTestValue, type));
// when
Map<String, Object> result = DtoUtil.toMap(variables);
// then
assertThat(result.size()).isEqualTo(4);
Object firstValue = result.get(firstTestVar);
assertThat(firstValue).isInstanceOf(String.class);
assertThat(firstValue).isEqualTo(firstTestValue);
Object secondValue = result.get(secondTestVar);
assertThat(secondValue).isNull();
Object thirdValue = result.get(thirdTestVar);
assertThat(thirdValue).isInstanceOf(String.class);
assertThat(thirdValue).isEqualTo(thirdTestValue);
Object fourthValue = result.get(fourthTestVar);
assertThat(fourthValue).isInstanceOf(String.class);
assertThat(fourthValue).isEqualTo("5");
}
@Test
public void testDtoUtilToMap_Boolean() throws Exception {
// given
String type = "Boolean";
Boolean firstTestValue = true;
String firstTestVar = "firstTestVar";
Boolean secondTestValue = false;
String secondTestVar = "secondTestVar";
String thirdTestValue = "true";
String thirdTestVar = "thirdTestVar";
String fourthTestValue = "false";
String fourthTestVar = "fourthTestVar";
String fifthTestValue = "abc";
String fifthTestVar = "fifthTestVar";
String sixthTestValue = null;
String sixthTestVar = "sixthTestVar";
Map<String, VariableValueDto> variables = new HashMap<String, VariableValueDto>();
variables.put(firstTestVar, new VariableValueDto(firstTestValue, type));
variables.put(secondTestVar, new VariableValueDto(secondTestValue, type));
variables.put(thirdTestVar, new VariableValueDto(thirdTestValue, type));
variables.put(fourthTestVar, new VariableValueDto(fourthTestValue, type));
variables.put(fifthTestVar, new VariableValueDto(fifthTestValue, type));
variables.put(sixthTestVar, new VariableValueDto(sixthTestValue, type));
// when
Map<String, Object> result = DtoUtil.toMap(variables);
// then
assertThat(result.size()).isEqualTo(6);
Object firstValue = result.get(firstTestVar);
assertThat(firstValue).isInstanceOf(Boolean.class);
assertThat(firstValue).isEqualTo(firstTestValue);
Object secondValue = result.get(secondTestVar);
assertThat(secondValue).isInstanceOf(Boolean.class);
assertThat(secondValue).isEqualTo(secondTestValue);
Object thirdValue = result.get(thirdTestVar);
assertThat(thirdValue).isInstanceOf(Boolean.class);
assertThat(thirdValue).isEqualTo(true);
Object fourthValue = result.get(fourthTestVar);
assertThat(fourthValue).isInstanceOf(Boolean.class);
assertThat(fourthValue).isEqualTo(false);
Object fifthValue = result.get(fifthTestVar);
assertThat(fifthValue).isInstanceOf(Boolean.class);
assertThat(fifthValue).isEqualTo(false);
Object sixthValue = result.get(sixthTestVar);
assertThat(sixthValue).isNull();
}
@Test
public void testDtoUtilToMap_Integer() throws Exception {
// given
String type = "Integer";
Integer firstTestValue = 123;
String firstTestVar = "firstTestVar";
String secondTestValue = "123";
String secondTestVar = "secondTestVar";
Integer thirdTestValue = null;
String thirdTestVar = "thirdTestVar";
Map<String, VariableValueDto> variables = new HashMap<String, VariableValueDto>();
variables.put(firstTestVar, new VariableValueDto(firstTestValue, type));
variables.put(secondTestVar, new VariableValueDto(secondTestValue, type));
variables.put(thirdTestVar, new VariableValueDto(thirdTestValue, type));
// when
Map<String, Object> result = DtoUtil.toMap(variables);
// then
assertThat(result.size()).isEqualTo(3);
Object firstValue = result.get(firstTestVar);
assertThat(firstValue).isInstanceOf(Integer.class);
assertThat(firstValue).isEqualTo(firstTestValue);
Object secondValue = result.get(secondTestVar);
assertThat(secondValue).isInstanceOf(Integer.class);
assertThat(secondValue).isEqualTo(123);
Object thirdValue = result.get(thirdTestVar);
assertThat(thirdValue).isNull();
}
@Test
public void testDtoUtilToMap_Short() throws Exception {
// given
String type = "Short";
Short firstTestValue = 123;
String firstTestVar = "firstTestVar";
String secondTestValue = "123";
String secondTestVar = "secondTestVar";
Short thirdTestValue = null;
String thirdTestVar = "thirdTestVar";
Map<String, VariableValueDto> variables = new HashMap<String, VariableValueDto>();
variables.put(firstTestVar, new VariableValueDto(firstTestValue, type));
variables.put(secondTestVar, new VariableValueDto(secondTestValue, type));
variables.put(thirdTestVar, new VariableValueDto(thirdTestValue, type));
// when
Map<String, Object> result = DtoUtil.toMap(variables);
// then
assertThat(result.size()).isEqualTo(3);
Object firstValue = result.get(firstTestVar);
assertThat(firstValue).isInstanceOf(Short.class);
assertThat(firstValue).isEqualTo(firstTestValue);
Object secondValue = result.get(secondTestVar);
assertThat(secondValue).isInstanceOf(Short.class);
assertThat(secondValue).isEqualTo((short) 123);
Object thirdValue = result.get(thirdTestVar);
assertThat(thirdValue).isNull();
}
@Test
public void testDtoUtilToMap_Long() throws Exception {
// given
String type = "Long";
Long firstTestValue = Long.valueOf(123);
String firstTestVar = "firstTestVar";
String secondTestValue = "123";
String secondTestVar = "secondTestVar";
Long thirdTestValue = null;
String thirdTestVar = "thirdTestVar";
Map<String, VariableValueDto> variables = new HashMap<String, VariableValueDto>();
variables.put(firstTestVar, new VariableValueDto(firstTestValue, type));
variables.put(secondTestVar, new VariableValueDto(secondTestValue, type));
variables.put(thirdTestVar, new VariableValueDto(thirdTestValue, type));
// when
Map<String, Object> result = DtoUtil.toMap(variables);
// then
assertThat(result.size()).isEqualTo(3);
Object firstValue = result.get(firstTestVar);
assertThat(firstValue).isInstanceOf(Long.class);
assertThat(firstValue).isEqualTo(firstTestValue);
Object secondValue = result.get(secondTestVar);
assertThat(secondValue).isInstanceOf(Long.class);
assertThat(secondValue).isEqualTo((long) 123);
Object thirdValue = result.get(thirdTestVar);
assertThat(thirdValue).isNull();
}
@Test
public void testDtoUtilToMap_Double() throws Exception {
// given
String type = "Double";
Double firstTestValue = Double.valueOf(123.456);
String firstTestVar = "firstTestVar";
String secondTestValue = "123.456";
String secondTestVar = "secondTestVar";
Double thirdTestValue = null;
String thirdTestVar = "thirdTestVar";
String fourthTestValue = "123";
String fourthTestVar = "fourthTestVar";
Map<String, VariableValueDto> variables = new HashMap<String, VariableValueDto>();
variables.put(firstTestVar, new VariableValueDto(firstTestValue, type));
variables.put(secondTestVar, new VariableValueDto(secondTestValue, type));
variables.put(thirdTestVar, new VariableValueDto(thirdTestValue, type));
variables.put(fourthTestVar, new VariableValueDto(fourthTestValue, type));
// when
Map<String, Object> result = DtoUtil.toMap(variables);
// then
assertThat(result.size()).isEqualTo(4);
Object firstValue = result.get(firstTestVar);
assertThat(firstValue).isInstanceOf(Double.class);
assertThat(firstValue).isEqualTo(firstTestValue);
Object secondValue = result.get(secondTestVar);
assertThat(secondValue).isInstanceOf(Double.class);
assertThat(secondValue).isEqualTo((double) 123.456);
Object thirdValue = result.get(thirdTestVar);
assertThat(thirdValue).isNull();
Object fourthValue = result.get(fourthTestVar);
assertThat(fourthValue).isInstanceOf(Double.class);
assertThat(fourthValue).isEqualTo((double) 123.0);
}
@Test
public void testDtoUtilToMap_Date() throws Exception {
// given
String type = "Date";
Date now = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String firstTestValue = formatter.format(now);
String firstTestVar = "firstTestVar";
String secondTestValue = null;
String secondTestVar = "secondTestVar";
Map<String, VariableValueDto> variables = new HashMap<String, VariableValueDto>();
variables.put(firstTestVar, new VariableValueDto(firstTestValue, type));
variables.put(secondTestVar, new VariableValueDto(secondTestValue, type));
// when
Map<String, Object> result = DtoUtil.toMap(variables);
// then
assertThat(result.size()).isEqualTo(2);
Object firstValue = result.get(firstTestVar);
assertThat(firstValue).isInstanceOf(Date.class);
assertThat(formatter.format(firstValue)).isEqualTo(formatter.format(now));
Object secondValue = result.get(secondTestVar);
assertThat(secondValue).isNull();
}
}
| apache-2.0 |
mirego/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/tests/android/icu/dev/test/stringprep/TestInputDataStructure.java | 3415 | /* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*
*******************************************************************************
* Copyright (C) 2005, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package android.icu.dev.test.stringprep;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author limaoyu
*/
public class TestInputDataStructure {
// TODO(junit): not running before - added empty test to keep failures away
@Ignore
@Test
public void dummyTest() {}
private String desc = null;
private String namebase = null;
private String nameutf8 = null;
private String namezone = null;
private String failzone1 = null;
private String failzone2 = null;
private String token = null;
private String passfail = null;
private String type = null;
/**
* @return Returns the desc.
*/
public String getDesc() {
return desc;
}
/**
* @param desc The desc to set.
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* @return Returns the failzone1.
*/
public String getFailzone1() {
return failzone1;
}
/**
* @param failzone1 The failzone1 to set.
*/
public void setFailzone1(String failzone1) {
this.failzone1 = failzone1;
}
/**
* @return Returns the failzone2.
*/
public String getFailzone2() {
return failzone2;
}
/**
* @param failzone2 The failzone2 to set.
*/
public void setFailzone2(String failzone2) {
this.failzone2 = failzone2;
}
/**
* @return Returns the namebase.
*/
public String getNamebase() {
return namebase;
}
/**
* @param namebase The namebase to set.
*/
public void setNamebase(String namebase) {
this.namebase = namebase;
}
/**
* @return Returns the nameutf8.
*/
public String getNameutf8() {
return nameutf8;
}
/**
* @param nameutf8 The nameutf8 to set.
*/
public void setNameutf8(String nameutf8) {
this.nameutf8 = nameutf8;
}
/**
* @return Returns the namezone.
*/
public String getNamezone() {
return namezone;
}
/**
* @param namezone The namezone to set.
*/
public void setNamezone(String namezone) {
this.namezone = namezone;
}
/**
* @return Returns the passfail.
*/
public String getPassfail() {
return passfail;
}
/**
* @param passfail The passfail to set.
*/
public void setPassfail(String passfail) {
this.passfail = passfail;
}
/**
* @return Returns the token.
*/
public String getToken() {
return token;
}
/**
* @param token The token to set.
*/
public void setToken(String token) {
this.token = token;
}
/**
* @return Returns the type.
*/
public String getType() {
return type;
}
/**
* @param type The type to set.
*/
public void setType(String type) {
this.type = type;
}
} | apache-2.0 |
mtseu/pentaho-hadoop-shims | hdp22/src/org/pentaho/hbase/shim/hdp22/DeserializedBooleanComparator.java | 6338 | /*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.hbase.shim.hdp22;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.hadoop.hbase.filter.ByteArrayComparable;
import org.apache.hadoop.hbase.util.Bytes;
/**
* Comparator for use in HBase column filtering that deserializes a boolean column value before performing a comparison.
* Various string and numeric deserializations are tried. All representations of "false" (for a given encoding type)
* sort before "true" - e.g. "false" < "true"; 0 < 1; "F" < "T"; "N" < "Y" etc. Thus < or > comparisons (excluding <
* false and > true) are equivalent to !=.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class DeserializedBooleanComparator extends ByteArrayComparable {
protected Boolean m_value;
// Use the HBaseBytesUtilShim to convert your boolean to bytes
public DeserializedBooleanComparator( byte[] raw ) {
super( raw );
m_value = Bytes.toBoolean( raw );
}
public DeserializedBooleanComparator( boolean value ) {
this( Bytes.toBytes( value ) );
}
public byte[] getValue() {
return Bytes.toBytes( m_value.booleanValue() );
}
public void readFields( DataInput in ) throws IOException {
m_value = new Boolean( in.readBoolean() );
}
public void write( DataOutput out ) throws IOException {
out.writeBoolean( m_value.booleanValue() );
}
public int compareTo( byte[] value ) {
Boolean decodedValue = decodeBoolFromString( value );
// if null then try as a number
if ( decodedValue == null ) {
decodedValue = decodeBoolFromNumber( value );
}
if ( decodedValue != null ) {
if ( m_value.equals( decodedValue ) ) {
return 0;
}
if ( m_value.booleanValue() == false && decodedValue.booleanValue() == true ) {
return -1;
}
return 1;
}
// doesn't matter what we return here because the step wont be able to
// decode this value either so an Exception will be raised
return 0;
}
public int compareTo( byte[] value, int offset, int length ) {
return compareTo( Bytes.copy( value, offset, length ) );
}
public static Boolean decodeBoolFromString( byte[] rawEncoded ) {
String tempString = Bytes.toString( rawEncoded );
if ( tempString.equalsIgnoreCase( "Y" ) || tempString.equalsIgnoreCase( "N" )
|| tempString.equalsIgnoreCase( "YES" ) || tempString.equalsIgnoreCase( "NO" )
|| tempString.equalsIgnoreCase( "TRUE" ) || tempString.equalsIgnoreCase( "FALSE" )
|| tempString.equalsIgnoreCase( "T" ) || tempString.equalsIgnoreCase( "F" )
|| tempString.equalsIgnoreCase( "1" ) || tempString.equalsIgnoreCase( "0" ) ) {
return Boolean.valueOf( tempString.equalsIgnoreCase( "Y" ) || tempString.equalsIgnoreCase( "YES" )
|| tempString.equalsIgnoreCase( "TRUE" ) || tempString.equalsIgnoreCase( "T" )
|| tempString.equalsIgnoreCase( "1" ) );
}
// not identifiable from a string
return null;
}
public static Boolean decodeBoolFromNumber( byte[] rawEncoded ) {
if ( rawEncoded.length == Bytes.SIZEOF_BYTE ) {
byte val = rawEncoded[ 0 ];
if ( val == 0 || val == 1 ) {
return new Boolean( val == 1 );
}
}
if ( rawEncoded.length == Bytes.SIZEOF_SHORT ) {
short tempShort = Bytes.toShort( rawEncoded );
if ( tempShort == 0 || tempShort == 1 ) {
return new Boolean( tempShort == 1 );
}
}
if ( rawEncoded.length == Bytes.SIZEOF_INT || rawEncoded.length == Bytes.SIZEOF_FLOAT ) {
int tempInt = Bytes.toInt( rawEncoded );
if ( tempInt == 1 || tempInt == 0 ) {
return new Boolean( tempInt == 1 );
}
float tempFloat = Bytes.toFloat( rawEncoded );
if ( tempFloat == 0.0f || tempFloat == 1.0f ) {
return new Boolean( tempFloat == 1.0f );
}
}
if ( rawEncoded.length == Bytes.SIZEOF_LONG || rawEncoded.length == Bytes.SIZEOF_DOUBLE ) {
long tempLong = Bytes.toLong( rawEncoded );
if ( tempLong == 0L || tempLong == 1L ) {
return new Boolean( tempLong == 1L );
}
double tempDouble = Bytes.toDouble( rawEncoded );
if ( tempDouble == 0.0 || tempDouble == 1.0 ) {
return new Boolean( tempDouble == 1.0 );
}
}
// not identifiable from a number
return null;
}
@Override
public byte[] toByteArray() {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream( byteArrayOutputStream );
try {
write( output );
output.close();
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
} catch ( IOException e ) {
throw new RuntimeException( "Unable to serialize to byte array.", e );
}
}
/**
* Needed for hbase-0.95+
*
* @throws IOException
*/
public static ByteArrayComparable parseFrom( final byte[] pbBytes ) {
DataInput in = new DataInputStream( new ByteArrayInputStream( pbBytes ) );
try {
boolean m_value = new Boolean( in.readBoolean() );
return new DeserializedBooleanComparator( m_value );
} catch ( IOException e ) {
throw new RuntimeException( "Unable to deserialize byte array", e );
}
}
}
| apache-2.0 |
Subasinghe/ode | bpel-compiler/src/main/java/org/apache/ode/bpel/elang/xpath10/compiler/XPath10ExpressionCompilerBPEL11.java | 2330 | /*
* 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.ode.bpel.elang.xpath10.compiler;
import org.apache.ode.bpel.compiler.api.CompilationException;
import org.apache.ode.bpel.compiler.bom.Expression;
import org.apache.ode.bpel.elang.xpath10.obj.OXPath10Expression;
import org.apache.ode.bpel.obj.OExpression;
import org.apache.ode.bpel.obj.OLValueExpression;
import org.apache.ode.utils.Namespaces;
/**
* XPath 1.0 expression compiler for BPEL v1.1.
*/
public class XPath10ExpressionCompilerBPEL11 extends XPath10ExpressionCompilerImpl {
public XPath10ExpressionCompilerBPEL11() {
super(Namespaces.BPEL11_NS);
}
/**
* @see org.apache.ode.bpel.compiler.api.ExpressionCompiler#compileJoinCondition(java.lang.Object)
*/
public OExpression compileJoinCondition(Object source) throws CompilationException {
return compile(source);
}
public OLValueExpression compileLValue(Object source) throws CompilationException {
throw new UnsupportedOperationException("Not supported for bpel 1.1");
}
/**
* @see org.apache.ode.bpel.compiler.api.ExpressionCompiler#compile(java.lang.Object)
*/
public OExpression compile(Object source) throws CompilationException {
Expression xpath = (Expression)source;
OXPath10Expression oexp = new OXPath10Expression(
_compilerContext.getOProcess(),
_qnFnGetVariableData,
_qnFnGetVariableProperty,
_qnFnGetLinkStatus);
oexp.setNamespaceCtx(xpath.getNamespaceContext());
doJaxenCompile(oexp, xpath);
return oexp;
}
}
| apache-2.0 |
apache/commons-vfs | commons-vfs2/src/main/java/org/apache/commons/vfs2/cache/DefaultFilesCache.java | 4683 | /*
* 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.commons.vfs2.cache;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
/**
* A simple {@link org.apache.commons.vfs2.FilesCache FilesCache} implementation.
* <p>
* This implementation caches every file with no expire or limit. All files and file systems are hard reachable
* references. This implementation holds a list of file system specific {@linkplain ConcurrentHashMap ConcurrentHashMaps}
* in the main cache map.
* </p>
* <p>
* Cached {@linkplain FileObject FileObjects} as well as {@linkplain FileSystem FileSystems} are only removed when
* {@link #clear(FileSystem)} is called (i.e. on file system close). When the used
* {@link org.apache.commons.vfs2.FileSystemManager FileSystemManager} is closed, it will also {@linkplain #close()
* close} this cache (which frees all entries).
* </p>
* <p>
* Despite its name, this is not the fallback implementation used by
* {@link org.apache.commons.vfs2.impl.DefaultFileSystemManager#init() DefaultFileSystemManager#init()} anymore.
* </p>
*/
public class DefaultFilesCache extends AbstractFilesCache {
private static final float LOAD_FACTOR = 0.75f;
private static final int INITIAL_CAPACITY = 200;
/** The FileSystem cache. Keeps one Map for each FileSystem. */
private final ConcurrentMap<FileSystem, ConcurrentMap<FileName, FileObject>> fileSystemCache = new ConcurrentHashMap<>(10);
@Override
public void clear(final FileSystem filesystem) {
// avoid keeping a reference to the FileSystem (key) object
final Map<FileName, FileObject> files = fileSystemCache.remove(filesystem);
if (files != null) {
files.clear(); // help GC
}
}
@Override
public void close() {
super.close();
fileSystemCache.clear();
}
@Override
public FileObject getFile(final FileSystem filesystem, final FileName name) {
// avoid creating filesystem entry for empty filesystem cache:
final Map<FileName, FileObject> files = fileSystemCache.get(filesystem);
if (files == null) {
// cache for filesystem is not known => file is not cached:
return null;
}
return files.get(name); // or null
}
protected ConcurrentMap<FileName, FileObject> getOrCreateFilesystemCache(final FileSystem filesystem) {
ConcurrentMap<FileName, FileObject> files = fileSystemCache.get(filesystem);
// we loop to make sure we never return null even when concurrent clean is called
while (files == null) {
files = fileSystemCache.computeIfAbsent(filesystem,
k -> new ConcurrentHashMap<>(INITIAL_CAPACITY, LOAD_FACTOR, Math.max(2, Runtime.getRuntime().availableProcessors()) / 2));
}
return files;
}
@Override
public void putFile(final FileObject file) {
final Map<FileName, FileObject> files = getOrCreateFilesystemCache(file.getFileSystem());
files.put(file.getName(), file);
}
@Override
public boolean putFileIfAbsent(final FileObject file) {
final ConcurrentMap<FileName, FileObject> files = getOrCreateFilesystemCache(file.getFileSystem());
return files.putIfAbsent(file.getName(), file) == null;
}
@Override
public void removeFile(final FileSystem filesystem, final FileName name) {
// avoid creating filesystem entry for empty filesystem cache:
final Map<FileName, FileObject> files = fileSystemCache.get(filesystem);
if (files != null) {
files.remove(name);
// This would be too racey:
// if (files.empty()) filesystemCache.remove(filessystem);
}
}
}
| apache-2.0 |
ravikiran438/my-vertx-first-app | src/main/java/io/vertx/blog/first/Whisky.java | 738 | package io.vertx.blog.first;
import java.util.concurrent.atomic.AtomicInteger;
public class Whisky {
private static final AtomicInteger COUNTER = new AtomicInteger();
private final int id;
private String name;
private String origin;
public Whisky(String name, String origin) {
this.id = COUNTER.getAndIncrement();
this.name = name;
this.origin = origin;
}
public Whisky() {
this.id = COUNTER.getAndIncrement();
}
public String getName() {
return name;
}
public String getOrigin() {
return origin;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public void setOrigin(String origin) {
this.origin = origin;
}
}
| apache-2.0 |
jinglining/flink | flink-connectors/flink-connector-base/src/main/java/org/apache/flink/connector/base/source/reader/SingleThreadMultiplexSourceReaderBase.java | 2350 | /*
* 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.connector.base.source.reader;
import org.apache.flink.api.connector.source.SourceReader;
import org.apache.flink.api.connector.source.SourceReaderContext;
import org.apache.flink.api.connector.source.SourceSplit;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.base.source.reader.fetcher.SingleThreadFetcherManager;
import org.apache.flink.connector.base.source.reader.splitreader.SplitReader;
import org.apache.flink.connector.base.source.reader.synchronization.FutureCompletingBlockingQueue;
import org.apache.flink.connector.base.source.reader.synchronization.FutureNotifier;
import java.util.function.Supplier;
/**
* A abstract {@link SourceReader} implementation that assign all the splits to a single thread to consume.
* @param <E>
* @param <T>
* @param <SplitT>
* @param <SplitStateT>
*/
public abstract class SingleThreadMultiplexSourceReaderBase<E, T, SplitT extends SourceSplit, SplitStateT>
extends SourceReaderBase<E, T, SplitT, SplitStateT> {
public SingleThreadMultiplexSourceReaderBase(
FutureNotifier futureNotifier,
FutureCompletingBlockingQueue<RecordsWithSplitIds<E>> elementsQueue,
Supplier<SplitReader<E, SplitT>> splitFetcherSupplier,
RecordEmitter<E, T, SplitStateT> recordEmitter,
Configuration config,
SourceReaderContext context) {
super(
futureNotifier,
elementsQueue,
new SingleThreadFetcherManager<>(futureNotifier, elementsQueue, splitFetcherSupplier),
recordEmitter,
config,
context);
}
}
| apache-2.0 |
apache/incubator-groovy | src/main/java/org/codehaus/groovy/runtime/DefaultMethodKey.java | 1467 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.runtime;
/**
* A default implementation of MethodKey
*/
public class DefaultMethodKey extends MethodKey{
private final Class[] parameterTypes;
public DefaultMethodKey(Class sender, String name, Class[] parameterTypes, boolean isCallToSuper) {
super(sender, name,isCallToSuper);
this.parameterTypes = parameterTypes;
}
@Override
public int getParameterCount() {
return parameterTypes.length;
}
@Override
public Class getParameterType(int index) {
Class c = parameterTypes[index];
if (c==null) return Object.class;
return c;
}
} | apache-2.0 |
kulinski/myfaces | shared/src/main/java/org/apache/myfaces/shared/util/MyFacesObjectInputStream.java | 3059 | /*
* 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.myfaces.shared.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.lang.reflect.Proxy;
/**
* Tried to deploy v0.4.2 on JBoss 3.2.1 and had a classloading problem again.
* The problem seemed to be with JspInfo, line 98. We are using an
* ObjectInputStream Class, which then cannot find the classes to deserialize
* the input stream. The solution appears to be to subclass ObjectInputStream
* (eg. CustomInputStream), and specify a different class-loading mechanism.
*/
public class MyFacesObjectInputStream
extends ObjectInputStream
{
public MyFacesObjectInputStream(InputStream in) throws IOException
{
super(in);
}
protected Class resolveClass(ObjectStreamClass desc)
throws ClassNotFoundException, IOException
{
try
{
return ClassUtils.classForName(desc.getName());
}
catch (ClassNotFoundException e)
{
return super.resolveClass(desc);
}
}
protected Class resolveProxyClass(String[] interfaces)
throws IOException, ClassNotFoundException
{
// Only option that would match the current code would be to
// expand ClassLoaderExtension to handle 'getProxyClass', which
// would break all existing ClassLoaderExtension implementations
Class[] cinterfaces = new Class[interfaces.length];
for (int i = 0; i < interfaces.length; i++)
{
cinterfaces[i] = ClassUtils.classForName(interfaces[i]);
}
try
{
// Try WebApp ClassLoader first
return Proxy.getProxyClass(ClassUtils.getContextClassLoader(), cinterfaces);
}
catch (Exception ex)
{
// fallback: Try ClassLoader for MyFacesObjectInputStream (i.e. the myfaces.jar lib)
try
{
return Proxy.getProxyClass(
MyFacesObjectInputStream.class.getClassLoader(), cinterfaces);
}
catch (IllegalArgumentException e)
{
throw new ClassNotFoundException(e.toString(), e);
}
}
}
}
| apache-2.0 |
bboyfeiyu/AndroidJUnit4 | android-junit3-extension-support-v4/src/main/java/com/uphyca/testing/junit3/support/v4/LoaderTestCase.java | 4714 | /*
* Copyright (C) 2012 uPhyca Inc.
*
* Base on previous work by
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
/*
* Copyright (C) 2012 uPhyca Inc. http://www.uphyca.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.uphyca.testing.junit3.support.v4;
import java.util.concurrent.ArrayBlockingQueue;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.test.AndroidTestCase;
/**
* A convenience class for testing {@link Loader}s. This test case
* provides a simple way to synchronously get the result from a Loader making
* it easy to assert that the Loader returns the expected result.
*/
public class LoaderTestCase extends AndroidTestCase {
static {
// Force class loading of AsyncTask on the main thread so that it's handlers are tied to
// the main thread and responses from the worker thread get delivered on the main thread.
// The tests are run on another thread, allowing them to block waiting on a response from
// the code running on the main thread. The main thread can't block since the AysncTask
// results come in via the event loop.
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... args) {return null;}
@Override
protected void onPostExecute(Void result) {}
};
}
/**
* Runs a Loader synchronously and returns the result of the load. The loader will
* be started, stopped, and destroyed by this method so it cannot be reused.
*
* @param loader The loader to run synchronously
* @return The result from the loader
*/
public <T> T getLoaderResultSynchronously(final Loader<T> loader) {
// The test thread blocks on this queue until the loader puts it's result in
final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>(1);
// This callback runs on the "main" thread and unblocks the test thread
// when it puts the result into the blocking queue
final OnLoadCompleteListener<T> listener = new OnLoadCompleteListener<T>() {
@Override
public void onLoadComplete(Loader<T> completedLoader, T data) {
// Shut the loader down
completedLoader.unregisterListener(this);
completedLoader.stopLoading();
completedLoader.reset();
// Store the result, unblocking the test thread
queue.add(data);
}
};
// This handler runs on the "main" thread of the process since AsyncTask
// is documented as needing to run on the main thread and many Loaders use
// AsyncTask
final Handler mainThreadHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
loader.registerListener(0, listener);
loader.startLoading();
}
};
// Ask the main thread to start the loading process
mainThreadHandler.sendEmptyMessage(0);
// Block on the queue waiting for the result of the load to be inserted
T result;
while (true) {
try {
result = queue.take();
break;
} catch (InterruptedException e) {
throw new RuntimeException("waiting thread interrupted", e);
}
}
return result;
}
}
| apache-2.0 |
christophd/camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GoogleCalendarStreamEndpointBuilderFactory.java | 41907 | /*
* 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.builder.endpoint.dsl;
import java.util.*;
import java.util.Map;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.*;
import javax.annotation.Generated;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
/**
* Poll for changes in a Google Calendar.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface GoogleCalendarStreamEndpointBuilderFactory {
/**
* Builder for endpoint for the Google Calendar Stream component.
*/
public interface GoogleCalendarStreamEndpointBuilder
extends
EndpointConsumerBuilder {
default AdvancedGoogleCalendarStreamEndpointBuilder advanced() {
return (AdvancedGoogleCalendarStreamEndpointBuilder) this;
}
/**
* Google Calendar application name. Example would be
* camel-google-calendar/1.0.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param applicationName the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder applicationName(
String applicationName) {
doSetProperty("applicationName", applicationName);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder bridgeErrorHandler(
String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* The calendarId to be used.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: primary
* Group: consumer
*
* @param calendarId the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder calendarId(String calendarId) {
doSetProperty("calendarId", calendarId);
return this;
}
/**
* Client ID of the calendar application.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param clientId the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder clientId(String clientId) {
doSetProperty("clientId", clientId);
return this;
}
/**
* Take into account the lastUpdate of the last event polled as start
* date for the next poll.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param considerLastUpdate the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder considerLastUpdate(
boolean considerLastUpdate) {
doSetProperty("considerLastUpdate", considerLastUpdate);
return this;
}
/**
* Take into account the lastUpdate of the last event polled as start
* date for the next poll.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param considerLastUpdate the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder considerLastUpdate(
String considerLastUpdate) {
doSetProperty("considerLastUpdate", considerLastUpdate);
return this;
}
/**
* Consume events in the selected calendar from now on.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer
*
* @param consumeFromNow the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder consumeFromNow(
boolean consumeFromNow) {
doSetProperty("consumeFromNow", consumeFromNow);
return this;
}
/**
* Consume events in the selected calendar from now on.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: true
* Group: consumer
*
* @param consumeFromNow the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder consumeFromNow(
String consumeFromNow) {
doSetProperty("consumeFromNow", consumeFromNow);
return this;
}
/**
* Delegate for wide-domain service account.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param delegate the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder delegate(String delegate) {
doSetProperty("delegate", delegate);
return this;
}
/**
* Max results to be returned.
*
* The option is a: <code>int</code> type.
*
* Default: 10
* Group: consumer
*
* @param maxResults the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder maxResults(int maxResults) {
doSetProperty("maxResults", maxResults);
return this;
}
/**
* Max results to be returned.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 10
* Group: consumer
*
* @param maxResults the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder maxResults(String maxResults) {
doSetProperty("maxResults", maxResults);
return this;
}
/**
* The query to execute on calendar.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: consumer
*
* @param query the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder query(String query) {
doSetProperty("query", query);
return this;
}
/**
* Specifies the level of permissions you want a calendar application to
* have to a user account. See
* https://developers.google.com/calendar/auth for more info.
*
* The option is a:
* <code>java.util.List&lt;java.lang.String&gt;</code> type.
*
* Group: consumer
*
* @param scopes the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder scopes(
List<java.lang.String> scopes) {
doSetProperty("scopes", scopes);
return this;
}
/**
* Specifies the level of permissions you want a calendar application to
* have to a user account. See
* https://developers.google.com/calendar/auth for more info.
*
* The option will be converted to a
* <code>java.util.List&lt;java.lang.String&gt;</code> type.
*
* Group: consumer
*
* @param scopes the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder scopes(String scopes) {
doSetProperty("scopes", scopes);
return this;
}
/**
* If the polling consumer did not poll any files, you can enable this
* option to send an empty message (no body) instead.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param sendEmptyMessageWhenIdle the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder sendEmptyMessageWhenIdle(
boolean sendEmptyMessageWhenIdle) {
doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle);
return this;
}
/**
* If the polling consumer did not poll any files, you can enable this
* option to send an empty message (no body) instead.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param sendEmptyMessageWhenIdle the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder sendEmptyMessageWhenIdle(
String sendEmptyMessageWhenIdle) {
doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle);
return this;
}
/**
* Sync events, see https://developers.google.com/calendar/v3/sync Note:
* not compatible with: 'query' and 'considerLastUpdate' parameters.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param syncFlow the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder syncFlow(boolean syncFlow) {
doSetProperty("syncFlow", syncFlow);
return this;
}
/**
* Sync events, see https://developers.google.com/calendar/v3/sync Note:
* not compatible with: 'query' and 'considerLastUpdate' parameters.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param syncFlow the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder syncFlow(String syncFlow) {
doSetProperty("syncFlow", syncFlow);
return this;
}
/**
* The number of subsequent error polls (failed due some error) that
* should happen before the backoffMultipler should kick-in.
*
* The option is a: <code>int</code> type.
*
* Group: scheduler
*
* @param backoffErrorThreshold the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder backoffErrorThreshold(
int backoffErrorThreshold) {
doSetProperty("backoffErrorThreshold", backoffErrorThreshold);
return this;
}
/**
* The number of subsequent error polls (failed due some error) that
* should happen before the backoffMultipler should kick-in.
*
* The option will be converted to a <code>int</code> type.
*
* Group: scheduler
*
* @param backoffErrorThreshold the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder backoffErrorThreshold(
String backoffErrorThreshold) {
doSetProperty("backoffErrorThreshold", backoffErrorThreshold);
return this;
}
/**
* The number of subsequent idle polls that should happen before the
* backoffMultipler should kick-in.
*
* The option is a: <code>int</code> type.
*
* Group: scheduler
*
* @param backoffIdleThreshold the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder backoffIdleThreshold(
int backoffIdleThreshold) {
doSetProperty("backoffIdleThreshold", backoffIdleThreshold);
return this;
}
/**
* The number of subsequent idle polls that should happen before the
* backoffMultipler should kick-in.
*
* The option will be converted to a <code>int</code> type.
*
* Group: scheduler
*
* @param backoffIdleThreshold the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder backoffIdleThreshold(
String backoffIdleThreshold) {
doSetProperty("backoffIdleThreshold", backoffIdleThreshold);
return this;
}
/**
* To let the scheduled polling consumer backoff if there has been a
* number of subsequent idles/errors in a row. The multiplier is then
* the number of polls that will be skipped before the next actual
* attempt is happening again. When this option is in use then
* backoffIdleThreshold and/or backoffErrorThreshold must also be
* configured.
*
* The option is a: <code>int</code> type.
*
* Group: scheduler
*
* @param backoffMultiplier the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder backoffMultiplier(
int backoffMultiplier) {
doSetProperty("backoffMultiplier", backoffMultiplier);
return this;
}
/**
* To let the scheduled polling consumer backoff if there has been a
* number of subsequent idles/errors in a row. The multiplier is then
* the number of polls that will be skipped before the next actual
* attempt is happening again. When this option is in use then
* backoffIdleThreshold and/or backoffErrorThreshold must also be
* configured.
*
* The option will be converted to a <code>int</code> type.
*
* Group: scheduler
*
* @param backoffMultiplier the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder backoffMultiplier(
String backoffMultiplier) {
doSetProperty("backoffMultiplier", backoffMultiplier);
return this;
}
/**
* Milliseconds before the next poll.
*
* The option is a: <code>long</code> type.
*
* Default: 500
* Group: scheduler
*
* @param delay the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder delay(long delay) {
doSetProperty("delay", delay);
return this;
}
/**
* Milliseconds before the next poll.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 500
* Group: scheduler
*
* @param delay the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder delay(String delay) {
doSetProperty("delay", delay);
return this;
}
/**
* If greedy is enabled, then the ScheduledPollConsumer will run
* immediately again, if the previous run polled 1 or more messages.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: scheduler
*
* @param greedy the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder greedy(boolean greedy) {
doSetProperty("greedy", greedy);
return this;
}
/**
* If greedy is enabled, then the ScheduledPollConsumer will run
* immediately again, if the previous run polled 1 or more messages.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: scheduler
*
* @param greedy the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder greedy(String greedy) {
doSetProperty("greedy", greedy);
return this;
}
/**
* Milliseconds before the first poll starts.
*
* The option is a: <code>long</code> type.
*
* Default: 1000
* Group: scheduler
*
* @param initialDelay the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder initialDelay(
long initialDelay) {
doSetProperty("initialDelay", initialDelay);
return this;
}
/**
* Milliseconds before the first poll starts.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 1000
* Group: scheduler
*
* @param initialDelay the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder initialDelay(
String initialDelay) {
doSetProperty("initialDelay", initialDelay);
return this;
}
/**
* Specifies a maximum limit of number of fires. So if you set it to 1,
* the scheduler will only fire once. If you set it to 5, it will only
* fire five times. A value of zero or negative means fire forever.
*
* The option is a: <code>long</code> type.
*
* Default: 0
* Group: scheduler
*
* @param repeatCount the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder repeatCount(long repeatCount) {
doSetProperty("repeatCount", repeatCount);
return this;
}
/**
* Specifies a maximum limit of number of fires. So if you set it to 1,
* the scheduler will only fire once. If you set it to 5, it will only
* fire five times. A value of zero or negative means fire forever.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 0
* Group: scheduler
*
* @param repeatCount the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder repeatCount(
String repeatCount) {
doSetProperty("repeatCount", repeatCount);
return this;
}
/**
* The consumer logs a start/complete log line when it polls. This
* option allows you to configure the logging level for that.
*
* The option is a:
* <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: TRACE
* Group: scheduler
*
* @param runLoggingLevel the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder runLoggingLevel(
org.apache.camel.LoggingLevel runLoggingLevel) {
doSetProperty("runLoggingLevel", runLoggingLevel);
return this;
}
/**
* The consumer logs a start/complete log line when it polls. This
* option allows you to configure the logging level for that.
*
* The option will be converted to a
* <code>org.apache.camel.LoggingLevel</code> type.
*
* Default: TRACE
* Group: scheduler
*
* @param runLoggingLevel the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder runLoggingLevel(
String runLoggingLevel) {
doSetProperty("runLoggingLevel", runLoggingLevel);
return this;
}
/**
* Allows for configuring a custom/shared thread pool to use for the
* consumer. By default each consumer has its own single threaded thread
* pool.
*
* The option is a:
* <code>java.util.concurrent.ScheduledExecutorService</code> type.
*
* Group: scheduler
*
* @param scheduledExecutorService the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder scheduledExecutorService(
ScheduledExecutorService scheduledExecutorService) {
doSetProperty("scheduledExecutorService", scheduledExecutorService);
return this;
}
/**
* Allows for configuring a custom/shared thread pool to use for the
* consumer. By default each consumer has its own single threaded thread
* pool.
*
* The option will be converted to a
* <code>java.util.concurrent.ScheduledExecutorService</code> type.
*
* Group: scheduler
*
* @param scheduledExecutorService the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder scheduledExecutorService(
String scheduledExecutorService) {
doSetProperty("scheduledExecutorService", scheduledExecutorService);
return this;
}
/**
* To use a cron scheduler from either camel-spring or camel-quartz
* component. Use value spring or quartz for built in scheduler.
*
* The option is a: <code>java.lang.Object</code> type.
*
* Default: none
* Group: scheduler
*
* @param scheduler the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder scheduler(Object scheduler) {
doSetProperty("scheduler", scheduler);
return this;
}
/**
* To use a cron scheduler from either camel-spring or camel-quartz
* component. Use value spring or quartz for built in scheduler.
*
* The option will be converted to a
* <code>java.lang.Object</code> type.
*
* Default: none
* Group: scheduler
*
* @param scheduler the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder scheduler(String scheduler) {
doSetProperty("scheduler", scheduler);
return this;
}
/**
* To configure additional properties when using a custom scheduler or
* any of the Quartz, Spring based scheduler.
*
* The option is a: <code>java.util.Map&lt;java.lang.String,
* java.lang.Object&gt;</code> type.
* The option is multivalued, and you can use the
* schedulerProperties(String, Object) method to add a value (call the
* method multiple times to set more values).
*
* Group: scheduler
*
* @param key the option key
* @param value the option value
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder schedulerProperties(
String key,
Object value) {
doSetMultiValueProperty("schedulerProperties", "scheduler." + key, value);
return this;
}
/**
* To configure additional properties when using a custom scheduler or
* any of the Quartz, Spring based scheduler.
*
* The option is a: <code>java.util.Map&lt;java.lang.String,
* java.lang.Object&gt;</code> type.
* The option is multivalued, and you can use the
* schedulerProperties(String, Object) method to add a value (call the
* method multiple times to set more values).
*
* Group: scheduler
*
* @param values the values
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder schedulerProperties(
Map values) {
doSetMultiValueProperties("schedulerProperties", "scheduler.", values);
return this;
}
/**
* Whether the scheduler should be auto started.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: scheduler
*
* @param startScheduler the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder startScheduler(
boolean startScheduler) {
doSetProperty("startScheduler", startScheduler);
return this;
}
/**
* Whether the scheduler should be auto started.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: true
* Group: scheduler
*
* @param startScheduler the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder startScheduler(
String startScheduler) {
doSetProperty("startScheduler", startScheduler);
return this;
}
/**
* Time unit for initialDelay and delay options.
*
* The option is a:
* <code>java.util.concurrent.TimeUnit</code> type.
*
* Default: MILLISECONDS
* Group: scheduler
*
* @param timeUnit the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder timeUnit(TimeUnit timeUnit) {
doSetProperty("timeUnit", timeUnit);
return this;
}
/**
* Time unit for initialDelay and delay options.
*
* The option will be converted to a
* <code>java.util.concurrent.TimeUnit</code> type.
*
* Default: MILLISECONDS
* Group: scheduler
*
* @param timeUnit the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder timeUnit(String timeUnit) {
doSetProperty("timeUnit", timeUnit);
return this;
}
/**
* Controls if fixed delay or fixed rate is used. See
* ScheduledExecutorService in JDK for details.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: scheduler
*
* @param useFixedDelay the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder useFixedDelay(
boolean useFixedDelay) {
doSetProperty("useFixedDelay", useFixedDelay);
return this;
}
/**
* Controls if fixed delay or fixed rate is used. See
* ScheduledExecutorService in JDK for details.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: true
* Group: scheduler
*
* @param useFixedDelay the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder useFixedDelay(
String useFixedDelay) {
doSetProperty("useFixedDelay", useFixedDelay);
return this;
}
/**
* OAuth 2 access token. This typically expires after an hour so
* refreshToken is recommended for long term usage.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessToken the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder accessToken(
String accessToken) {
doSetProperty("accessToken", accessToken);
return this;
}
/**
* Client secret of the calendar application.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param clientSecret the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder clientSecret(
String clientSecret) {
doSetProperty("clientSecret", clientSecret);
return this;
}
/**
* The emailAddress of the Google Service Account.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param emailAddress the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder emailAddress(
String emailAddress) {
doSetProperty("emailAddress", emailAddress);
return this;
}
/**
* Sets .json file with credentials for Service account.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param keyResource the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder keyResource(
String keyResource) {
doSetProperty("keyResource", keyResource);
return this;
}
/**
* The name of the p12 file which has the private key to use with the
* Google Service Account.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param p12FileName the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder p12FileName(
String p12FileName) {
doSetProperty("p12FileName", p12FileName);
return this;
}
/**
* OAuth 2 refresh token. Using this, the Google Calendar component can
* obtain a new accessToken whenever the current one expires - a
* necessity if the application is long-lived.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param refreshToken the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder refreshToken(
String refreshToken) {
doSetProperty("refreshToken", refreshToken);
return this;
}
/**
* The email address of the user the application is trying to
* impersonate in the service account flow.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param user the value to set
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder user(String user) {
doSetProperty("user", user);
return this;
}
}
/**
* Advanced builder for endpoint for the Google Calendar Stream component.
*/
public interface AdvancedGoogleCalendarStreamEndpointBuilder
extends
EndpointConsumerBuilder {
default GoogleCalendarStreamEndpointBuilder basic() {
return (GoogleCalendarStreamEndpointBuilder) this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a:
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedGoogleCalendarStreamEndpointBuilder exceptionHandler(
org.apache.camel.spi.ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedGoogleCalendarStreamEndpointBuilder exceptionHandler(
String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a:
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedGoogleCalendarStreamEndpointBuilder exchangePattern(
org.apache.camel.ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedGoogleCalendarStreamEndpointBuilder exchangePattern(
String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option is a:
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedGoogleCalendarStreamEndpointBuilder pollStrategy(
org.apache.camel.spi.PollingConsumerPollStrategy pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option will be converted to a
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedGoogleCalendarStreamEndpointBuilder pollStrategy(
String pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
}
public interface GoogleCalendarStreamBuilders {
/**
* Google Calendar Stream (camel-google-calendar)
* Poll for changes in a Google Calendar.
*
* Category: cloud
* Since: 2.23
* Maven coordinates: org.apache.camel:camel-google-calendar
*
* Syntax: <code>google-calendar-stream:index</code>
*
* Path parameter: index (required)
* Specifies an index for the endpoint
*
* @param path index
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder googleCalendarStream(
String path) {
return GoogleCalendarStreamEndpointBuilderFactory.endpointBuilder("google-calendar-stream", path);
}
/**
* Google Calendar Stream (camel-google-calendar)
* Poll for changes in a Google Calendar.
*
* Category: cloud
* Since: 2.23
* Maven coordinates: org.apache.camel:camel-google-calendar
*
* Syntax: <code>google-calendar-stream:index</code>
*
* Path parameter: index (required)
* Specifies an index for the endpoint
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path index
* @return the dsl builder
*/
default GoogleCalendarStreamEndpointBuilder googleCalendarStream(
String componentName,
String path) {
return GoogleCalendarStreamEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static GoogleCalendarStreamEndpointBuilder endpointBuilder(
String componentName,
String path) {
class GoogleCalendarStreamEndpointBuilderImpl extends AbstractEndpointBuilder implements GoogleCalendarStreamEndpointBuilder, AdvancedGoogleCalendarStreamEndpointBuilder {
public GoogleCalendarStreamEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new GoogleCalendarStreamEndpointBuilderImpl(path);
}
} | apache-2.0 |
googleinterns/calcite | splunk/src/main/java/org/apache/calcite/adapter/splunk/SplunkDriver.java | 4370 | /*
* 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.calcite.adapter.splunk;
import org.apache.calcite.adapter.splunk.search.SearchResultListener;
import org.apache.calcite.adapter.splunk.search.SplunkConnection;
import org.apache.calcite.adapter.splunk.search.SplunkConnectionImpl;
import org.apache.calcite.avatica.DriverVersion;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.linq4j.Enumerator;
import org.apache.calcite.schema.SchemaPlus;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* JDBC driver for Splunk.
*
* <p>It accepts connect strings that start with "jdbc:splunk:".</p>
*/
public class SplunkDriver extends org.apache.calcite.jdbc.Driver {
protected SplunkDriver() {
super();
}
static {
new SplunkDriver().register();
}
protected String getConnectStringPrefix() {
return "jdbc:splunk:";
}
protected DriverVersion createDriverVersion() {
return new SplunkDriverVersion();
}
@Override public Connection connect(String url, Properties info)
throws SQLException {
Connection connection = super.connect(url, info);
CalciteConnection calciteConnection = (CalciteConnection) connection;
SplunkConnection splunkConnection;
try {
String url1 = info.getProperty("url");
if (url1 == null) {
throw new IllegalArgumentException(
"Must specify 'url' property");
}
if (url1.equals("mock")) {
splunkConnection = new MockSplunkConnection();
} else {
String user = info.getProperty("user");
if (user == null) {
throw new IllegalArgumentException(
"Must specify 'user' property");
}
String password = info.getProperty("password");
if (password == null) {
throw new IllegalArgumentException(
"Must specify 'password' property");
}
URL url2 = new URL(url1);
splunkConnection = new SplunkConnectionImpl(url2, user, password);
}
} catch (Exception e) {
throw new SQLException("Cannot connect", e);
}
final SchemaPlus rootSchema = calciteConnection.getRootSchema();
rootSchema.add("splunk", new SplunkSchema(splunkConnection));
return connection;
}
/** Connection that looks up responses from a static map. */
private static class MockSplunkConnection implements SplunkConnection {
public Enumerator<Object> getSearchResultEnumerator(String search,
Map<String, String> otherArgs, List<String> fieldList) {
throw null;
}
public void getSearchResults(String search, Map<String, String> otherArgs,
List<String> fieldList, SearchResultListener srl) {
throw new UnsupportedOperationException();
}
}
/** Connection that records requests and responses. */
private static class WrappingSplunkConnection implements SplunkConnection {
private final SplunkConnection connection;
WrappingSplunkConnection(SplunkConnection connection) {
this.connection = connection;
}
public void getSearchResults(String search, Map<String, String> otherArgs,
List<String> fieldList, SearchResultListener srl) {
System.out.println("search='" + search
+ "', otherArgs=" + otherArgs
+ ", fieldList='" + fieldList);
}
public Enumerator<Object> getSearchResultEnumerator(String search,
Map<String, String> otherArgs, List<String> fieldList) {
throw new UnsupportedOperationException();
}
}
}
| apache-2.0 |
tripodsan/jackrabbit-filevault | vault-core/src/main/java/org/apache/jackrabbit/vault/util/RejectingEntityDefaultHandler.java | 1764 | /*
* 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.vault.util;
import java.io.IOException;
import java.io.StringReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Default handler with special entity resolver that handles all entity resolution requests by returning an empty input
* source. This is to prevent "Arbitrary DTD inclusion in XML parsing".
*/
public class RejectingEntityDefaultHandler extends DefaultHandler {
/**
* default logger
*/
private static final Logger log = LoggerFactory.getLogger(RejectingEntityDefaultHandler.class);
@Override
public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException {
log.warn("Rejecting external entity loading with publicId={} systemId={}", publicId, systemId);
return new InputSource(new StringReader(""));
}
} | apache-2.0 |
anycrane/apollo | apollo-client/src/test/java/com/ctrip/framework/apollo/spring/AbstractSpringIntegrationTest.java | 2303 | package com.ctrip.framework.apollo.spring;
import java.lang.reflect.Method;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.springframework.util.ReflectionUtils;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.internals.ConfigManager;
import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor;
import com.google.common.collect.Maps;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public abstract class AbstractSpringIntegrationTest {
private static final Map<String, Config> CONFIG_REGISTRY = Maps.newHashMap();
private static Method PROPERTY_SOURCES_PROCESSOR_CLEAR;
private static Method CONFIG_SERVICE_RESET;
static {
try {
PROPERTY_SOURCES_PROCESSOR_CLEAR = PropertySourcesProcessor.class.getDeclaredMethod("reset");
ReflectionUtils.makeAccessible(PROPERTY_SOURCES_PROCESSOR_CLEAR);
CONFIG_SERVICE_RESET = ConfigService.class.getDeclaredMethod("reset");
ReflectionUtils.makeAccessible(CONFIG_SERVICE_RESET);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
@Before
public void setUp() throws Exception {
//as PropertySourcesProcessor has some static states, so we must manually clear its state
ReflectionUtils.invokeMethod(PROPERTY_SOURCES_PROCESSOR_CLEAR, null);
//as ConfigService is singleton, so we must manually clear its container
ReflectionUtils.invokeMethod(CONFIG_SERVICE_RESET, null);
MockInjector.reset();
MockInjector.setInstance(ConfigManager.class, new MockConfigManager());
}
@After
public void tearDown() throws Exception {
CONFIG_REGISTRY.clear();
}
protected void mockConfig(String namespace, Config config) {
CONFIG_REGISTRY.put(namespace, config);
}
public static class MockConfigManager implements ConfigManager {
@Override
public Config getConfig(String namespace) {
return CONFIG_REGISTRY.get(namespace);
}
@Override
public ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat) {
return null;
}
}
}
| apache-2.0 |
ftomassetti/effectivejava | test-resources/sample-codebases/javaparser/japa/parser/ast/expr/MemberValuePair.java | 2149 | /*
* Copyright (C) 2007 Júlio Vilmar Gesser.
*
* This file is part of Java 1.5 parser and Abstract Syntax Tree.
*
* Java 1.5 parser and Abstract Syntax Tree 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.
*
* Java 1.5 parser and Abstract Syntax Tree 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 Java 1.5 parser and Abstract Syntax Tree. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Created on 21/11/2006
*/
package japa.parser.ast.expr;
import japa.parser.ast.Node;
import japa.parser.ast.visitor.GenericVisitor;
import japa.parser.ast.visitor.VoidVisitor;
/**
* @author Julio Vilmar Gesser
*/
public final class MemberValuePair extends Node {
private String name;
private Expression value;
public MemberValuePair() {
}
public MemberValuePair(final String name, final Expression value) {
setName(name);
setValue(value);
}
public MemberValuePair(final int beginLine, final int beginColumn, final int endLine, final int endColumn,
final String name, final Expression value) {
super(beginLine, beginColumn, endLine, endColumn);
setName(name);
setValue(value);
}
@Override public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
public String getName() {
return name;
}
public Expression getValue() {
return value;
}
public void setName(final String name) {
this.name = name;
}
public void setValue(final Expression value) {
this.value = value;
setAsParentNodeOf(this.value);
}
}
| apache-2.0 |
andyj24/googleads-java-lib | examples/dfp_axis/src/main/java/dfp/axis/v201505/productservice/UpdateProducts.java | 3478 | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dfp.axis.v201505.productservice;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.dfp.axis.factory.DfpServices;
import com.google.api.ads.dfp.axis.utils.v201505.StatementBuilder;
import com.google.api.ads.dfp.axis.v201505.Product;
import com.google.api.ads.dfp.axis.v201505.ProductPage;
import com.google.api.ads.dfp.axis.v201505.ProductServiceInterface;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.collect.Iterables;
import java.util.Arrays;
/**
* This example updates a product's notes. To determine which products exist, run
* GetAllProducts.java.
*
* Credentials and properties in {@code fromFile()} are pulled from the
* "ads.properties" file. See README for more info.
*
* Tags: ProductService.getProductsByStatement
* Tags: ProductService.updateProducts
*
* @author Nicholas Chen
*/
public class UpdateProducts {
// Set the ID of the product to update.
private static final String PRODUCT_ID = "INSERT_PRODUCT_ID_HERE";
public static void runExample(DfpServices dfpServices, DfpSession session, long productId)
throws Exception {
// Get the ProductService.
ProductServiceInterface productService =
dfpServices.get(session, ProductServiceInterface.class);
// Create a statement to only select a single product by ID.
StatementBuilder statementBuilder = new StatementBuilder()
.where("id = :id")
.orderBy("id ASC")
.limit(1)
.withBindVariableValue("id", productId);
// Get the product.
ProductPage page =
productService.getProductsByStatement(statementBuilder.toStatement());
Product product = Iterables.getOnlyElement(Arrays.asList(page.getResults()));
// Update the product's notes.
product.setNotes("Product needs further review before approval.");
// Update the product on the server.
Product[] products = productService.updateProducts(new Product[] {product});
for (Product updatedProduct : products) {
System.out.printf("Product with ID \"%d\" and name \"%s\" was updated.%n",
updatedProduct.getId(),
updatedProduct.getName());
}
}
public static void main(String[] args) throws Exception {
// Generate a refreshable OAuth2 credential.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.DFP)
.fromFile()
.build()
.generateCredential();
// Construct a DfpSession.
DfpSession session = new DfpSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
DfpServices dfpServices = new DfpServices();
runExample(dfpServices, session, Long.parseLong(PRODUCT_ID));
}
}
| apache-2.0 |
mathieucarbou/terracotta-platform | management/management-model/src/main/java/org/terracotta/management/model/stats/NumberUnit.java | 883 | /*
* Copyright Terracotta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terracotta.management.model.stats;
/**
* @author Mathieu Carbou
*/
public enum NumberUnit {
RATIO {
@Override
public String toString() {
return "ratio";
}
},
COUNT {
@Override
public String toString() {
return "counts";
}
}
}
| apache-2.0 |
ufctester/apache-jmeter | src/jorphan/org/apache/jorphan/gui/MinMaxLongRenderer.java | 1668 | /*
* 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.jorphan.gui;
/**
* Renders a min or max value and hides the extrema as they
* are used for initialization of the values and will likely be interpreted as
* random values.
* <p>
* {@link Long#MIN_VALUE} and {@link Long#MAX_VALUE} will be displayed as
* {@code #N/A}.
*
*/
public class MinMaxLongRenderer extends NumberRenderer { // NOSONAR
private static final long serialVersionUID = 1L;
public MinMaxLongRenderer(String format) {
super(format);
}
@Override
public void setValue(Object value) {
if (value instanceof Long) {
long longValue = ((Long) value).longValue();
if (!(longValue == Long.MAX_VALUE || longValue == Long.MIN_VALUE)) {
setText(formatter.format(longValue));
return;
}
}
setText("#N/A");
}
}
| apache-2.0 |
titusfortner/selenium | java/test/org/openqa/selenium/net/UrlsTest.java | 2201 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.net;
import org.junit.Test;
import java.net.URI;
import static org.assertj.core.api.Assertions.assertThat;
public class UrlsTest {
@Test
public void shouldCreateUrlFromProperlyFormedUrl() {
URI uri = Urls.from("http://localhost:4444");
assertThat(uri).isEqualTo(URI.create("http://localhost:4444"));
}
@Test
public void shouldAssumeAPlainStringIsAHostName() {
URI uri = Urls.from("localhost");
assertThat(uri).isEqualTo(URI.create("http://localhost"));
}
@Test
public void shouldHandleShortFormIp6AddressWithScheme() {
URI uri = Urls.from("https://2001:db8::1:0:0:1");
assertThat(uri).isEqualTo(URI.create("https://2001:db8::1:0:0:1"));
}
@Test
public void shouldHandleAShortFormIp6Address() {
URI uri = Urls.from("2001:db8::1:0:0:1");
assertThat(uri).isEqualTo(URI.create("http://[2001:db8::1:0:0:1]"));
}
@Test
public void shouldHandleTheIp6LoopbackAddress() {
URI uri = Urls.from("::1");
assertThat(uri).isEqualTo(URI.create("http://[::1]"));
}
@Test
public void shouldHandleTheUnspecifiedIp6Address() {
URI uri = Urls.from("::");
assertThat(uri).isEqualTo(URI.create("http://[::]"));
}
@Test
public void shouldHandleIpv6LoopbackAddressWithPath() {
URI uri = Urls.from("::1/wd/hub");
assertThat(uri).isEqualTo(URI.create("http://[::1]/wd/hub"));
}
}
| apache-2.0 |
siosio/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/UIThemeProvider.java | 2100 | // 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.ide.ui;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.PluginAware;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.RequiredElement;
import com.intellij.util.xmlb.annotations.Attribute;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.InputStream;
import java.util.function.Function;
/**
* @author Konstantin Bulenkov
*/
public final class UIThemeProvider implements PluginAware {
public static final ExtensionPointName<UIThemeProvider> EP_NAME = new ExtensionPointName<>("com.intellij.themeProvider");
private PluginDescriptor myPluginDescriptor;
@Attribute("path")
@RequiredElement
public String path;
@Attribute("id")
@RequiredElement
public String id;
@ApiStatus.Internal
public @Nullable InputStream getThemeJsonStream() {
return myPluginDescriptor.getPluginClassLoader().getResourceAsStream(path.charAt(0) == '/' ? path.substring(1) : path);
}
public @Nullable UITheme createTheme() {
try {
ClassLoader classLoader = myPluginDescriptor.getPluginClassLoader();
InputStream stream = getThemeJsonStream();
if (stream == null) {
Logger.getInstance(getClass()).warn("Cannot find theme resource: " + path + " (classLoader=" + classLoader + ", pluginDescriptor=" + myPluginDescriptor + ")");
return null;
}
return UITheme.loadFromJson(stream, id, classLoader, Function.identity());
}
catch (Exception e) {
Logger.getInstance(getClass()).warn("error loading UITheme '" + path + "', pluginDescriptor=" + myPluginDescriptor, e);
return null;
}
}
@Override
public void setPluginDescriptor(@NotNull PluginDescriptor pluginDescriptor) {
myPluginDescriptor = pluginDescriptor;
}
}
| apache-2.0 |
AndroidX/androidx | camera/camera-extensions/src/main/java/androidx/camera/extensions/internal/VersionName.java | 1886 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.extensions.internal;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
/**
* The version of CameraX extension releases.
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
public class VersionName {
// Current version of vendor library implementation that the CameraX extension supports. This
// needs to be increased along with the version of vendor library interface.
private static final VersionName CURRENT = new VersionName("1.1.0");
@NonNull
public static VersionName getCurrentVersion() {
return CURRENT;
}
private final Version mVersion;
@NonNull
public Version getVersion() {
return mVersion;
}
public VersionName(@NonNull String versionString) {
mVersion = Version.parse(versionString);
}
VersionName(int major, int minor, int patch, String description) {
mVersion = Version.create(major, minor, patch, description);
}
/**
* Gets this version number as string.
*
* @return the string of the version in a form of MAJOR.MINOR.PATCH-description.
*/
@NonNull
public String toVersionString() {
return mVersion.toString();
}
}
| apache-2.0 |
ultratendency/hbase | hbase-client/src/main/java/org/apache/hadoop/hbase/quotas/QuotaSettingsFactory.java | 21922 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.quotas;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.hbase.TableName;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetQuotaRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos;
import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.Quotas;
import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos.SpaceQuota;
@InterfaceAudience.Public
public class QuotaSettingsFactory {
static class QuotaGlobalsSettingsBypass extends QuotaSettings {
private final boolean bypassGlobals;
QuotaGlobalsSettingsBypass(final String userName, final TableName tableName,
final String namespace, final String regionServer, final boolean bypassGlobals) {
super(userName, tableName, namespace, regionServer);
this.bypassGlobals = bypassGlobals;
}
@Override
public QuotaType getQuotaType() {
return QuotaType.GLOBAL_BYPASS;
}
@Override
protected void setupSetQuotaRequest(SetQuotaRequest.Builder builder) {
builder.setBypassGlobals(bypassGlobals);
}
@Override
public String toString() {
return "GLOBAL_BYPASS => " + bypassGlobals;
}
protected boolean getBypass() {
return bypassGlobals;
}
@Override
protected QuotaGlobalsSettingsBypass merge(QuotaSettings newSettings) throws IOException {
if (newSettings instanceof QuotaGlobalsSettingsBypass) {
QuotaGlobalsSettingsBypass other = (QuotaGlobalsSettingsBypass) newSettings;
validateQuotaTarget(other);
if (getBypass() != other.getBypass()) {
return other;
}
}
return this;
}
}
/* ==========================================================================
* QuotaSettings from the Quotas object
*/
static List<QuotaSettings> fromUserQuotas(final String userName, final Quotas quotas) {
return fromQuotas(userName, null, null, null, quotas);
}
static List<QuotaSettings> fromUserQuotas(final String userName, final TableName tableName,
final Quotas quotas) {
return fromQuotas(userName, tableName, null, null, quotas);
}
static List<QuotaSettings> fromUserQuotas(final String userName, final String namespace,
final Quotas quotas) {
return fromQuotas(userName, null, namespace, null, quotas);
}
static List<QuotaSettings> fromTableQuotas(final TableName tableName, final Quotas quotas) {
return fromQuotas(null, tableName, null, null, quotas);
}
static List<QuotaSettings> fromNamespaceQuotas(final String namespace, final Quotas quotas) {
return fromQuotas(null, null, namespace, null, quotas);
}
static List<QuotaSettings> fromRegionServerQuotas(final String regionServer,
final Quotas quotas) {
return fromQuotas(null, null, null, regionServer, quotas);
}
private static List<QuotaSettings> fromQuotas(final String userName, final TableName tableName,
final String namespace, final String regionServer, final Quotas quotas) {
List<QuotaSettings> settings = new ArrayList<>();
if (quotas.hasThrottle()) {
settings
.addAll(fromThrottle(userName, tableName, namespace, regionServer, quotas.getThrottle()));
}
if (quotas.getBypassGlobals() == true) {
settings
.add(new QuotaGlobalsSettingsBypass(userName, tableName, namespace, regionServer, true));
}
if (quotas.hasSpace()) {
settings.add(fromSpace(tableName, namespace, quotas.getSpace()));
}
return settings;
}
protected static List<QuotaSettings> fromThrottle(final String userName,
final TableName tableName, final String namespace, final String regionServer,
final QuotaProtos.Throttle throttle) {
List<QuotaSettings> settings = new ArrayList<>();
if (throttle.hasReqNum()) {
settings.add(ThrottleSettings.fromTimedQuota(userName, tableName, namespace, regionServer,
ThrottleType.REQUEST_NUMBER, throttle.getReqNum()));
}
if (throttle.hasReqSize()) {
settings.add(ThrottleSettings.fromTimedQuota(userName, tableName, namespace, regionServer,
ThrottleType.REQUEST_SIZE, throttle.getReqSize()));
}
if (throttle.hasWriteNum()) {
settings.add(ThrottleSettings.fromTimedQuota(userName, tableName, namespace, regionServer,
ThrottleType.WRITE_NUMBER, throttle.getWriteNum()));
}
if (throttle.hasWriteSize()) {
settings.add(ThrottleSettings.fromTimedQuota(userName, tableName, namespace, regionServer,
ThrottleType.WRITE_SIZE, throttle.getWriteSize()));
}
if (throttle.hasReadNum()) {
settings.add(ThrottleSettings.fromTimedQuota(userName, tableName, namespace, regionServer,
ThrottleType.READ_NUMBER, throttle.getReadNum()));
}
if (throttle.hasReadSize()) {
settings.add(ThrottleSettings.fromTimedQuota(userName, tableName, namespace, regionServer,
ThrottleType.READ_SIZE, throttle.getReadSize()));
}
if (throttle.hasReqCapacityUnit()) {
settings.add(ThrottleSettings.fromTimedQuota(userName, tableName, namespace, regionServer,
ThrottleType.REQUEST_CAPACITY_UNIT, throttle.getReqCapacityUnit()));
}
if (throttle.hasReadCapacityUnit()) {
settings.add(ThrottleSettings.fromTimedQuota(userName, tableName, namespace, regionServer,
ThrottleType.READ_CAPACITY_UNIT, throttle.getReadCapacityUnit()));
}
if (throttle.hasWriteCapacityUnit()) {
settings.add(ThrottleSettings.fromTimedQuota(userName, tableName, namespace, regionServer,
ThrottleType.WRITE_CAPACITY_UNIT, throttle.getWriteCapacityUnit()));
}
return settings;
}
static QuotaSettings fromSpace(TableName table, String namespace, SpaceQuota protoQuota) {
if (protoQuota == null) {
return null;
}
if ((table == null && namespace == null) || (table != null && namespace != null)) {
throw new IllegalArgumentException(
"Can only construct SpaceLimitSettings for a table or namespace.");
}
if (table != null) {
if (protoQuota.getRemove()) {
return new SpaceLimitSettings(table);
}
return SpaceLimitSettings.fromSpaceQuota(table, protoQuota);
} else {
if (protoQuota.getRemove()) {
return new SpaceLimitSettings(namespace);
}
// namespace must be non-null
return SpaceLimitSettings.fromSpaceQuota(namespace, protoQuota);
}
}
/* ==========================================================================
* RPC Throttle
*/
/**
* Throttle the specified user.
*
* @param userName the user to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @return the quota settings
*/
public static QuotaSettings throttleUser(final String userName, final ThrottleType type,
final long limit, final TimeUnit timeUnit) {
return throttleUser(userName, type, limit, timeUnit, QuotaScope.MACHINE);
}
/**
* Throttle the specified user.
* @param userName the user to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @param scope the scope of throttling
* @return the quota settings
*/
public static QuotaSettings throttleUser(final String userName, final ThrottleType type,
final long limit, final TimeUnit timeUnit, QuotaScope scope) {
return throttle(userName, null, null, null, type, limit, timeUnit, scope);
}
/**
* Throttle the specified user on the specified table.
*
* @param userName the user to throttle
* @param tableName the table to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @return the quota settings
*/
public static QuotaSettings throttleUser(final String userName, final TableName tableName,
final ThrottleType type, final long limit, final TimeUnit timeUnit) {
return throttleUser(userName, tableName, type, limit, timeUnit, QuotaScope.MACHINE);
}
/**
* Throttle the specified user on the specified table.
* @param userName the user to throttle
* @param tableName the table to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @param scope the scope of throttling
* @return the quota settings
*/
public static QuotaSettings throttleUser(final String userName, final TableName tableName,
final ThrottleType type, final long limit, final TimeUnit timeUnit, QuotaScope scope) {
return throttle(userName, tableName, null, null, type, limit, timeUnit, scope);
}
/**
* Throttle the specified user on the specified namespace.
*
* @param userName the user to throttle
* @param namespace the namespace to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @return the quota settings
*/
public static QuotaSettings throttleUser(final String userName, final String namespace,
final ThrottleType type, final long limit, final TimeUnit timeUnit) {
return throttleUser(userName, namespace, type, limit, timeUnit, QuotaScope.MACHINE);
}
/**
* Throttle the specified user on the specified namespace.
* @param userName the user to throttle
* @param namespace the namespace to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @param scope the scope of throttling
* @return the quota settings
*/
public static QuotaSettings throttleUser(final String userName, final String namespace,
final ThrottleType type, final long limit, final TimeUnit timeUnit, QuotaScope scope) {
return throttle(userName, null, namespace, null, type, limit, timeUnit, scope);
}
/**
* Remove the throttling for the specified user.
*
* @param userName the user
* @return the quota settings
*/
public static QuotaSettings unthrottleUser(final String userName) {
return throttle(userName, null, null, null, null, 0, null, QuotaScope.MACHINE);
}
/**
* Remove the throttling for the specified user.
*
* @param userName the user
* @param type the type of throttling
* @return the quota settings
*/
public static QuotaSettings unthrottleUserByThrottleType(final String userName,
final ThrottleType type) {
return throttle(userName, null, null, null, type, 0, null, QuotaScope.MACHINE);
}
/**
* Remove the throttling for the specified user on the specified table.
*
* @param userName the user
* @param tableName the table
* @return the quota settings
*/
public static QuotaSettings unthrottleUser(final String userName, final TableName tableName) {
return throttle(userName, tableName, null, null, null, 0, null, QuotaScope.MACHINE);
}
/**
* Remove the throttling for the specified user on the specified table.
*
* @param userName the user
* @param tableName the table
* @param type the type of throttling
* @return the quota settings
*/
public static QuotaSettings unthrottleUserByThrottleType(final String userName,
final TableName tableName, final ThrottleType type) {
return throttle(userName, tableName, null, null, type, 0, null, QuotaScope.MACHINE);
}
/**
* Remove the throttling for the specified user on the specified namespace.
*
* @param userName the user
* @param namespace the namespace
* @return the quota settings
*/
public static QuotaSettings unthrottleUser(final String userName, final String namespace) {
return throttle(userName, null, namespace, null, null, 0, null, QuotaScope.MACHINE);
}
/**
* Remove the throttling for the specified user on the specified namespace.
*
* @param userName the user
* @param namespace the namespace
* @param type the type of throttling
* @return the quota settings
*/
public static QuotaSettings unthrottleUserByThrottleType(final String userName,
final String namespace, final ThrottleType type) {
return throttle(userName, null, namespace, null, type, 0, null, QuotaScope.MACHINE);
}
/**
* Throttle the specified table.
*
* @param tableName the table to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @return the quota settings
*/
public static QuotaSettings throttleTable(final TableName tableName, final ThrottleType type,
final long limit, final TimeUnit timeUnit) {
return throttleTable(tableName, type, limit, timeUnit, QuotaScope.MACHINE);
}
/**
* Throttle the specified table.
* @param tableName the table to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @param scope the scope of throttling
* @return the quota settings
*/
public static QuotaSettings throttleTable(final TableName tableName, final ThrottleType type,
final long limit, final TimeUnit timeUnit, QuotaScope scope) {
return throttle(null, tableName, null, null, type, limit, timeUnit, scope);
}
/**
* Remove the throttling for the specified table.
*
* @param tableName the table
* @return the quota settings
*/
public static QuotaSettings unthrottleTable(final TableName tableName) {
return throttle(null, tableName, null, null, null, 0, null, QuotaScope.MACHINE);
}
/**
* Remove the throttling for the specified table.
*
* @param tableName the table
* @param type the type of throttling
* @return the quota settings
*/
public static QuotaSettings unthrottleTableByThrottleType(final TableName tableName,
final ThrottleType type) {
return throttle(null, tableName, null, null, type, 0, null, QuotaScope.MACHINE);
}
/**
* Throttle the specified namespace.
*
* @param namespace the namespace to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @return the quota settings
*/
public static QuotaSettings throttleNamespace(final String namespace, final ThrottleType type,
final long limit, final TimeUnit timeUnit) {
return throttleNamespace(namespace, type, limit, timeUnit, QuotaScope.MACHINE);
}
/**
* Throttle the specified namespace.
* @param namespace the namespace to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @param scope the scope of throttling
* @return the quota settings
*/
public static QuotaSettings throttleNamespace(final String namespace, final ThrottleType type,
final long limit, final TimeUnit timeUnit, QuotaScope scope) {
return throttle(null, null, namespace, null, type, limit, timeUnit, scope);
}
/**
* Remove the throttling for the specified namespace.
*
* @param namespace the namespace
* @return the quota settings
*/
public static QuotaSettings unthrottleNamespace(final String namespace) {
return throttle(null, null, namespace, null, null, 0, null, QuotaScope.MACHINE);
}
/**
* Remove the throttling for the specified namespace by throttle type.
*
* @param namespace the namespace
* @param type the type of throttling
* @return the quota settings
*/
public static QuotaSettings unthrottleNamespaceByThrottleType(final String namespace,
final ThrottleType type) {
return throttle(null, null, namespace, null, type, 0, null, QuotaScope.MACHINE);
}
/**
* Throttle the specified region server.
*
* @param regionServer the region server to throttle
* @param type the type of throttling
* @param limit the allowed number of request/data per timeUnit
* @param timeUnit the limit time unit
* @return the quota settings
*/
public static QuotaSettings throttleRegionServer(final String regionServer,
final ThrottleType type, final long limit, final TimeUnit timeUnit) {
return throttle(null, null, null, regionServer, type, limit, timeUnit, QuotaScope.MACHINE);
}
/**
* Remove the throttling for the specified region server.
*
* @param regionServer the region Server
* @return the quota settings
*/
public static QuotaSettings unthrottleRegionServer(final String regionServer) {
return throttle(null, null, null, regionServer, null, 0, null, QuotaScope.MACHINE);
}
/**
* Remove the throttling for the specified region server by throttle type.
*
* @param regionServer the region Server
* @param type the type of throttling
* @return the quota settings
*/
public static QuotaSettings unthrottleRegionServerByThrottleType(final String regionServer,
final ThrottleType type) {
return throttle(null, null, null, regionServer, type, 0, null, QuotaScope.MACHINE);
}
/* Throttle helper */
private static QuotaSettings throttle(final String userName, final TableName tableName,
final String namespace, final String regionServer, final ThrottleType type, final long limit,
final TimeUnit timeUnit, QuotaScope scope) {
QuotaProtos.ThrottleRequest.Builder builder = QuotaProtos.ThrottleRequest.newBuilder();
if (type != null) {
builder.setType(ProtobufUtil.toProtoThrottleType(type));
}
if (timeUnit != null) {
builder.setTimedQuota(ProtobufUtil.toTimedQuota(limit, timeUnit, scope));
}
return new ThrottleSettings(userName, tableName, namespace, regionServer, builder.build());
}
/* ==========================================================================
* Global Settings
*/
/**
* Set the "bypass global settings" for the specified user
*
* @param userName the user to throttle
* @param bypassGlobals true if the global settings should be bypassed
* @return the quota settings
*/
public static QuotaSettings bypassGlobals(final String userName, final boolean bypassGlobals) {
return new QuotaGlobalsSettingsBypass(userName, null, null, null, bypassGlobals);
}
/* ==========================================================================
* FileSystem Space Settings
*/
/**
* Creates a {@link QuotaSettings} object to limit the FileSystem space usage for the given table
* to the given size in bytes. When the space usage is exceeded by the table, the provided
* {@link SpaceViolationPolicy} is enacted on the table.
*
* @param tableName The name of the table on which the quota should be applied.
* @param sizeLimit The limit of a table's size in bytes.
* @param violationPolicy The action to take when the quota is exceeded.
* @return An {@link QuotaSettings} object.
*/
public static QuotaSettings limitTableSpace(
final TableName tableName, long sizeLimit, final SpaceViolationPolicy violationPolicy) {
return new SpaceLimitSettings(tableName, sizeLimit, violationPolicy);
}
/**
* Creates a {@link QuotaSettings} object to remove the FileSystem space quota for the given
* table.
*
* @param tableName The name of the table to remove the quota for.
* @return A {@link QuotaSettings} object.
*/
public static QuotaSettings removeTableSpaceLimit(TableName tableName) {
return new SpaceLimitSettings(tableName);
}
/**
* Creates a {@link QuotaSettings} object to limit the FileSystem space usage for the given
* namespace to the given size in bytes. When the space usage is exceeded by all tables in the
* namespace, the provided {@link SpaceViolationPolicy} is enacted on all tables in the namespace.
*
* @param namespace The namespace on which the quota should be applied.
* @param sizeLimit The limit of the namespace's size in bytes.
* @param violationPolicy The action to take when the the quota is exceeded.
* @return An {@link QuotaSettings} object.
*/
public static QuotaSettings limitNamespaceSpace(
final String namespace, long sizeLimit, final SpaceViolationPolicy violationPolicy) {
return new SpaceLimitSettings(namespace, sizeLimit, violationPolicy);
}
/**
* Creates a {@link QuotaSettings} object to remove the FileSystem space quota for the given
* namespace.
*
* @param namespace The namespace to remove the quota on.
* @return A {@link QuotaSettings} object.
*/
public static QuotaSettings removeNamespaceSpaceLimit(String namespace) {
return new SpaceLimitSettings(namespace);
}
}
| apache-2.0 |
jgarman/autopsy | KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchConfigurationPanel.java | 3945 | /*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.keywordsearch;
import java.util.logging.Level;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.corecomponents.OptionsPanel;
/**
* Container panel for keyword search advanced configuration options
*/
final class KeywordSearchConfigurationPanel extends javax.swing.JPanel implements OptionsPanel {
private static final Logger logger = Logger.getLogger(KeywordSearchConfigurationPanel.class.getName());
private KeywordSearchConfigurationPanel1 listsPanel;
private KeywordSearchConfigurationPanel3 languagesPanel;
private KeywordSearchConfigurationPanel2 generalPanel;
KeywordSearchConfigurationPanel() {
initComponents();
customizeComponents();
}
private void customizeComponents() {
setName("Advanced Keyword Search Configuration");
listsPanel = new KeywordSearchConfigurationPanel1();
languagesPanel = new KeywordSearchConfigurationPanel3();
generalPanel = new KeywordSearchConfigurationPanel2();
tabbedPane.insertTab("Lists", null, listsPanel, "List configuration", 0);
tabbedPane.insertTab("String Extraction", null, languagesPanel, "String extraction configuration for Keyword Search Ingest", 1);
tabbedPane.insertTab("General", null, generalPanel, "General configuration", 2);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
/**
* Load each of the tabs and reload the XML.
*/
@Override
public void load() {
// Deselect all table rows
listsPanel.load();
languagesPanel.load();
generalPanel.load();
// Reload the XML to avoid 'ghost' vars
KeywordSearchListsXML.getCurrent().reload();
}
/**
* Store each panel's settings.
*/
@Override
public void store() {
listsPanel.store();
languagesPanel.store();
generalPanel.store();
}
boolean valid() {
// TODO check whether form is consistent and complete
return true;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration//GEN-END:variables
}
| apache-2.0 |
project-ncl/pnc | notifications/src/test/java/org/jboss/pnc/notification/SessionBasedAttachedClientTest.java | 1334 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.notification;
import org.junit.Test;
import javax.websocket.Session;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
public class SessionBasedAttachedClientTest {
@Test
public void shouldTwoInstancesCreatedTheSameWayBeEqual() throws Exception {
// given
Session session = mock(Session.class);
SessionBasedAttachedClient client1 = new SessionBasedAttachedClient(session);
SessionBasedAttachedClient client2 = new SessionBasedAttachedClient(session);
// when//then
assertEquals(client1, client2);
}
} | apache-2.0 |
siosio/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/ui/split/SplitFileEditor.java | 13440 | // 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.intellij.plugins.markdown.ui.split;
import com.intellij.codeHighlighting.BackgroundEditorHighlighter;
import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.*;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.JBSplitter;
import com.intellij.util.ui.JBEmptyBorder;
import org.intellij.plugins.markdown.MarkdownBundle;
import org.intellij.plugins.markdown.settings.MarkdownApplicationSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Map;
/**
* @deprecated Use {@link TextEditorWithPreview}
*/
@Deprecated
public abstract class SplitFileEditor<E1 extends FileEditor, E2 extends FileEditor> extends UserDataHolderBase implements FileEditor {
public static final Key<SplitFileEditor> PARENT_SPLIT_KEY = Key.create("parentSplit");
private static final String MY_PROPORTION_KEY = "SplitFileEditor.Proportion";
@NotNull
protected final E1 myMainEditor;
@NotNull
protected final E2 mySecondEditor;
@NotNull
private final JComponent myComponent;
@NotNull
private TextEditorWithPreview.Layout mySplitEditorLayout =
MarkdownApplicationSettings.getInstance().getMarkdownPreviewSettings().getSplitEditorLayout();
private boolean myVerticalSplitOption = MarkdownApplicationSettings.getInstance().getMarkdownPreviewSettings().isVerticalSplit();
@NotNull
private final MyListenersMultimap myListenersGenerator = new MyListenersMultimap();
private SplitEditorToolbar myToolbarWrapper;
private JBSplitter mySplitter;
public SplitFileEditor(@NotNull E1 mainEditor, @NotNull E2 secondEditor) {
myMainEditor = mainEditor;
mySecondEditor = secondEditor;
adjustDefaultLayout(mainEditor);
myComponent = createComponent();
if (myMainEditor instanceof TextEditor) {
myMainEditor.putUserData(PARENT_SPLIT_KEY, this);
}
if (mySecondEditor instanceof TextEditor) {
mySecondEditor.putUserData(PARENT_SPLIT_KEY, this);
}
MarkdownApplicationSettings.SettingsChangedListener settingsChangedListener =
new MarkdownApplicationSettings.SettingsChangedListener() {
@Override
public void beforeSettingsChanged(@NotNull MarkdownApplicationSettings newSettings) {
TextEditorWithPreview.Layout oldSplitEditorLayout =
MarkdownApplicationSettings.getInstance().getMarkdownPreviewSettings().getSplitEditorLayout();
boolean oldVerticalSplitOption =
MarkdownApplicationSettings.getInstance().getMarkdownPreviewSettings().isVerticalSplit();
ApplicationManager.getApplication().invokeLater(() -> {
if (oldSplitEditorLayout == mySplitEditorLayout) {
triggerLayoutChange(newSettings.getMarkdownPreviewSettings().getSplitEditorLayout(), false);
}
if (oldVerticalSplitOption == myVerticalSplitOption) {
triggerSplitOrientationChange(newSettings.getMarkdownPreviewSettings().isVerticalSplit());
}
});
}
};
ApplicationManager.getApplication().getMessageBus().connect(this)
.subscribe(MarkdownApplicationSettings.SettingsChangedListener.TOPIC, settingsChangedListener);
}
private void adjustDefaultLayout(E1 editor) {
}
private void triggerSplitOrientationChange(boolean isVerticalSplit) {
if (myVerticalSplitOption == isVerticalSplit) {
return;
}
myVerticalSplitOption = isVerticalSplit;
myToolbarWrapper.refresh();
mySplitter.setOrientation(!myVerticalSplitOption);
myComponent.repaint();
}
@NotNull
private JComponent createComponent() {
mySplitter =
new JBSplitter(!MarkdownApplicationSettings.getInstance().getMarkdownPreviewSettings().isVerticalSplit(), 0.5f, 0.15f, 0.85f);
mySplitter.setSplitterProportionKey(MY_PROPORTION_KEY);
mySplitter.setFirstComponent(myMainEditor.getComponent());
mySplitter.setSecondComponent(mySecondEditor.getComponent());
mySplitter.setDividerWidth(3);
myToolbarWrapper = createMarkdownToolbarWrapper(mySplitter);
final JPanel result = new JPanel(new BorderLayout());
result.add(myToolbarWrapper, BorderLayout.NORTH);
result.add(mySplitter, BorderLayout.CENTER);
adjustEditorsVisibility();
return result;
}
@NotNull
private static SplitEditorToolbar createMarkdownToolbarWrapper(@NotNull JComponent targetComponentForActions) {
ActionToolbar leftToolbar = createToolbarFromGroupId("Markdown.Toolbar.Left");
leftToolbar.setTargetComponent(targetComponentForActions);
leftToolbar.setReservePlaceAutoPopupIcon(false);
ActionToolbar rightToolbar = createToolbarFromGroupId("Markdown.Toolbar.Right");
rightToolbar.setTargetComponent(targetComponentForActions);
rightToolbar.setReservePlaceAutoPopupIcon(false);
return new SplitEditorToolbar(leftToolbar, rightToolbar);
}
@NotNull
private static ActionToolbar createToolbarFromGroupId(@NotNull String groupId) {
final ActionManager actionManager = ActionManager.getInstance();
if (!actionManager.isGroup(groupId)) {
throw new IllegalStateException(groupId + " should have been a group");
}
final ActionGroup group = ((ActionGroup)actionManager.getAction(groupId));
final ActionToolbarImpl editorToolbar =
((ActionToolbarImpl)actionManager.createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, group, true));
editorToolbar.setBorder(new JBEmptyBorder(0, 2, 0, 2));
return editorToolbar;
}
public void triggerLayoutChange(@NotNull TextEditorWithPreview.Layout newLayout, boolean requestFocus) {
if (mySplitEditorLayout == newLayout) {
return;
}
mySplitEditorLayout = newLayout;
invalidateLayout(requestFocus);
}
private void invalidateLayout(boolean requestFocus) {
adjustEditorsVisibility();
myToolbarWrapper.refresh();
myComponent.repaint();
if (!requestFocus) return;
final JComponent focusComponent = getPreferredFocusedComponent();
if (focusComponent != null) {
IdeFocusManager.findInstanceByComponent(focusComponent).requestFocus(focusComponent, true);
}
}
private void adjustEditorsVisibility() {
}
@NotNull
public E1 getMainEditor() {
return myMainEditor;
}
@NotNull
public E2 getSecondEditor() {
return mySecondEditor;
}
@NotNull
@Override
public JComponent getComponent() {
return myComponent;
}
@Nullable
@Override
public JComponent getPreferredFocusedComponent() {
return null;
}
@NotNull
@Override
public FileEditorState getState(@NotNull FileEditorStateLevel level) {
return new MyFileEditorState(mySplitEditorLayout.name(), myMainEditor.getState(level), mySecondEditor.getState(level));
}
@Override
public void setState(@NotNull FileEditorState state) {
}
@Override
public boolean isModified() {
return myMainEditor.isModified() || mySecondEditor.isModified();
}
@Override
public boolean isValid() {
return myMainEditor.isValid() && mySecondEditor.isValid();
}
@Override
public void selectNotify() {
myMainEditor.selectNotify();
mySecondEditor.selectNotify();
}
@Override
public void deselectNotify() {
myMainEditor.deselectNotify();
mySecondEditor.deselectNotify();
}
@Override
public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) {
myMainEditor.addPropertyChangeListener(listener);
mySecondEditor.addPropertyChangeListener(listener);
final DoublingEventListenerDelegate delegate = myListenersGenerator.addListenerAndGetDelegate(listener);
myMainEditor.addPropertyChangeListener(delegate);
mySecondEditor.addPropertyChangeListener(delegate);
}
@Override
public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) {
myMainEditor.removePropertyChangeListener(listener);
mySecondEditor.removePropertyChangeListener(listener);
final DoublingEventListenerDelegate delegate = myListenersGenerator.removeListenerAndGetDelegate(listener);
if (delegate != null) {
myMainEditor.removePropertyChangeListener(delegate);
mySecondEditor.removePropertyChangeListener(delegate);
}
}
@Nullable
@Override
public BackgroundEditorHighlighter getBackgroundHighlighter() {
return myMainEditor.getBackgroundHighlighter();
}
@Nullable
@Override
public FileEditorLocation getCurrentLocation() {
return myMainEditor.getCurrentLocation();
}
@Nullable
@Override
public StructureViewBuilder getStructureViewBuilder() {
return myMainEditor.getStructureViewBuilder();
}
@Override
public void dispose() {
Disposer.dispose(myMainEditor);
Disposer.dispose(mySecondEditor);
}
public static class MyFileEditorState implements FileEditorState {
@Nullable
private final String mySplitLayout;
@Nullable
private final FileEditorState myFirstState;
@Nullable
private final FileEditorState mySecondState;
public MyFileEditorState(@Nullable String splitLayout, @Nullable FileEditorState firstState, @Nullable FileEditorState secondState) {
mySplitLayout = splitLayout;
myFirstState = firstState;
mySecondState = secondState;
}
@Nullable
public String getSplitLayout() {
return mySplitLayout;
}
@Nullable
public FileEditorState getFirstState() {
return myFirstState;
}
@Nullable
public FileEditorState getSecondState() {
return mySecondState;
}
@Override
public boolean canBeMergedWith(@NotNull FileEditorState otherState, @NotNull FileEditorStateLevel level) {
return otherState instanceof MyFileEditorState
&& (myFirstState == null || myFirstState.canBeMergedWith(((MyFileEditorState)otherState).myFirstState, level))
&& (mySecondState == null || mySecondState.canBeMergedWith(((MyFileEditorState)otherState).mySecondState, level));
}
}
private final class DoublingEventListenerDelegate implements PropertyChangeListener {
@NotNull
private final PropertyChangeListener myDelegate;
private DoublingEventListenerDelegate(@NotNull PropertyChangeListener delegate) {
myDelegate = delegate;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
myDelegate.propertyChange(new PropertyChangeEvent(SplitFileEditor.this, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()));
}
}
private class MyListenersMultimap {
private final Map<PropertyChangeListener, Pair<Integer, DoublingEventListenerDelegate>> myMap = new HashMap<>();
@NotNull
public DoublingEventListenerDelegate addListenerAndGetDelegate(@NotNull PropertyChangeListener listener) {
if (!myMap.containsKey(listener)) {
myMap.put(listener, Pair.create(1, new DoublingEventListenerDelegate(listener)));
}
else {
final Pair<Integer, DoublingEventListenerDelegate> oldPair = myMap.get(listener);
myMap.put(listener, Pair.create(oldPair.getFirst() + 1, oldPair.getSecond()));
}
return myMap.get(listener).getSecond();
}
@Nullable
public DoublingEventListenerDelegate removeListenerAndGetDelegate(@NotNull PropertyChangeListener listener) {
final Pair<Integer, DoublingEventListenerDelegate> oldPair = myMap.get(listener);
if (oldPair == null) {
return null;
}
if (oldPair.getFirst() == 1) {
myMap.remove(listener);
}
else {
myMap.put(listener, Pair.create(oldPair.getFirst() - 1, oldPair.getSecond()));
}
return oldPair.getSecond();
}
}
/**
* @deprecated Use {@link TextEditorWithPreview.Layout}
*/
@Deprecated
public enum SplitEditorLayout {
FIRST(true, false, MarkdownBundle.message("markdown.layout.editor.only")),
SECOND(false, true, MarkdownBundle.message("markdown.layout.preview.only")),
SPLIT(true, true, MarkdownBundle.message("markdown.layout.editor.and.preview"));
public final boolean showFirst;
public final boolean showSecond;
public final String presentationName;
SplitEditorLayout(boolean showFirst, boolean showSecond, String presentationName) {
this.showFirst = showFirst;
this.showSecond = showSecond;
this.presentationName = presentationName;
}
public String getPresentationText() {
return StringUtil.capitalize(presentationName);
}
@Override
public String toString() {
return MarkdownBundle.message("markdown.layout.show", presentationName);
}
}
}
| apache-2.0 |
hxf0801/droolsjbpm-integration | kie-infinispan/jbpm-infinispan-persistence/src/main/java/org/jbpm/persistence/processinstance/InfinispanSignalManager.java | 1462 | package org.jbpm.persistence.processinstance;
import java.util.List;
import org.drools.core.common.InternalKnowledgeRuntime;
import org.jbpm.persistence.ProcessPersistenceContext;
import org.jbpm.persistence.ProcessPersistenceContextManager;
import org.jbpm.process.instance.event.DefaultSignalManager;
import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl;
import org.kie.api.runtime.EnvironmentName;
public class InfinispanSignalManager extends DefaultSignalManager {
public InfinispanSignalManager(InternalKnowledgeRuntime kruntime) {
super(kruntime);
}
public void signalEvent(String type,
Object event) {
for ( long id : getProcessInstancesForEvent( type ) ) {
try {
getKnowledgeRuntime().getProcessInstance( id );
} catch (IllegalStateException e) {
// IllegalStateException can be thrown when using RuntimeManager
// and invalid ksession was used for given context
}
}
super.signalEvent( type,
event );
}
private List<Long> getProcessInstancesForEvent(String type) {
ProcessPersistenceContext context = ((ProcessPersistenceContextManager) getKnowledgeRuntime().getEnvironment().get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER )).getProcessPersistenceContext();
return context.getProcessInstancesWaitingForEvent(type);
}
}
| apache-2.0 |
strapdata/elassandra | client/client-benchmark-noop-api-plugin/src/main/java/org/elasticsearch/plugin/noop/action/search/NoopSearchRequestBuilder.java | 16703 | /*
* 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.plugin.noop.action.search;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.PipelineAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.rescore.RescorerBuilder;
import org.elasticsearch.search.slice.SliceBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import java.util.Arrays;
import java.util.List;
public class NoopSearchRequestBuilder extends ActionRequestBuilder<SearchRequest, SearchResponse, NoopSearchRequestBuilder> {
public NoopSearchRequestBuilder(ElasticsearchClient client, NoopSearchAction action) {
super(client, action, new SearchRequest());
}
/**
* Sets the indices the search will be executed on.
*/
public NoopSearchRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
/**
* The document types to execute the search against. Defaults to be executed against
* all types.
*/
public NoopSearchRequestBuilder setTypes(String... types) {
request.types(types);
return this;
}
/**
* The search type to execute, defaults to {@link org.elasticsearch.action.search.SearchType#DEFAULT}.
*/
public NoopSearchRequestBuilder setSearchType(SearchType searchType) {
request.searchType(searchType);
return this;
}
/**
* The a string representation search type to execute, defaults to {@link org.elasticsearch.action.search.SearchType#DEFAULT}. Can be
* one of "dfs_query_then_fetch"/"dfsQueryThenFetch", "dfs_query_and_fetch"/"dfsQueryAndFetch",
* "query_then_fetch"/"queryThenFetch", and "query_and_fetch"/"queryAndFetch".
*/
public NoopSearchRequestBuilder setSearchType(String searchType) {
request.searchType(searchType);
return this;
}
/**
* If set, will enable scrolling of the search request.
*/
public NoopSearchRequestBuilder setScroll(Scroll scroll) {
request.scroll(scroll);
return this;
}
/**
* If set, will enable scrolling of the search request for the specified timeout.
*/
public NoopSearchRequestBuilder setScroll(TimeValue keepAlive) {
request.scroll(keepAlive);
return this;
}
/**
* If set, will enable scrolling of the search request for the specified timeout.
*/
public NoopSearchRequestBuilder setScroll(String keepAlive) {
request.scroll(keepAlive);
return this;
}
/**
* An optional timeout to control how long search is allowed to take.
*/
public NoopSearchRequestBuilder setTimeout(TimeValue timeout) {
sourceBuilder().timeout(timeout);
return this;
}
/**
* An optional document count, upon collecting which the search
* query will early terminate
*/
public NoopSearchRequestBuilder setTerminateAfter(int terminateAfter) {
sourceBuilder().terminateAfter(terminateAfter);
return this;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public NoopSearchRequestBuilder setRouting(String routing) {
request.routing(routing);
return this;
}
/**
* The routing values to control the shards that the search will be executed on.
*/
public NoopSearchRequestBuilder setRouting(String... routing) {
request.routing(routing);
return this;
}
/**
* Sets the preference to execute the search. Defaults to randomize across shards. Can be set to
* {@code _local} to prefer local shards, {@code _primary} to execute only on primary shards, or
* a custom value, which guarantees that the same order will be used across different requests.
*/
public NoopSearchRequestBuilder setPreference(String preference) {
request.preference(preference);
return this;
}
/**
* Specifies what type of requested indices to ignore and wildcard indices expressions.
* <p>
* For example indices that don't exist.
*/
public NoopSearchRequestBuilder setIndicesOptions(IndicesOptions indicesOptions) {
request().indicesOptions(indicesOptions);
return this;
}
/**
* Constructs a new search source builder with a search query.
*
* @see org.elasticsearch.index.query.QueryBuilders
*/
public NoopSearchRequestBuilder setQuery(QueryBuilder queryBuilder) {
sourceBuilder().query(queryBuilder);
return this;
}
/**
* Sets a filter that will be executed after the query has been executed and only has affect on the search hits
* (not aggregations). This filter is always executed as last filtering mechanism.
*/
public NoopSearchRequestBuilder setPostFilter(QueryBuilder postFilter) {
sourceBuilder().postFilter(postFilter);
return this;
}
/**
* Sets the minimum score below which docs will be filtered out.
*/
public NoopSearchRequestBuilder setMinScore(float minScore) {
sourceBuilder().minScore(minScore);
return this;
}
/**
* From index to start the search from. Defaults to {@code 0}.
*/
public NoopSearchRequestBuilder setFrom(int from) {
sourceBuilder().from(from);
return this;
}
/**
* The number of search hits to return. Defaults to {@code 10}.
*/
public NoopSearchRequestBuilder setSize(int size) {
sourceBuilder().size(size);
return this;
}
/**
* Should each {@link org.elasticsearch.search.SearchHit} be returned with an
* explanation of the hit (ranking).
*/
public NoopSearchRequestBuilder setExplain(boolean explain) {
sourceBuilder().explain(explain);
return this;
}
/**
* Should each {@link org.elasticsearch.search.SearchHit} be returned with its
* version.
*/
public NoopSearchRequestBuilder setVersion(boolean version) {
sourceBuilder().version(version);
return this;
}
/**
* Sets the boost a specific index will receive when the query is executed against it.
*
* @param index The index to apply the boost against
* @param indexBoost The boost to apply to the index
*/
public NoopSearchRequestBuilder addIndexBoost(String index, float indexBoost) {
sourceBuilder().indexBoost(index, indexBoost);
return this;
}
/**
* The stats groups this request will be aggregated under.
*/
public NoopSearchRequestBuilder setStats(String... statsGroups) {
sourceBuilder().stats(Arrays.asList(statsGroups));
return this;
}
/**
* The stats groups this request will be aggregated under.
*/
public NoopSearchRequestBuilder setStats(List<String> statsGroups) {
sourceBuilder().stats(statsGroups);
return this;
}
/**
* Indicates whether the response should contain the stored _source for every hit
*/
public NoopSearchRequestBuilder setFetchSource(boolean fetch) {
sourceBuilder().fetchSource(fetch);
return this;
}
/**
* Indicate that _source should be returned with every hit, with an "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param include An optional include (optionally wildcarded) pattern to filter the returned _source
* @param exclude An optional exclude (optionally wildcarded) pattern to filter the returned _source
*/
public NoopSearchRequestBuilder setFetchSource(@Nullable String include, @Nullable String exclude) {
sourceBuilder().fetchSource(include, exclude);
return this;
}
/**
* Indicate that _source should be returned with every hit, with an "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param includes An optional list of include (optionally wildcarded) pattern to filter the returned _source
* @param excludes An optional list of exclude (optionally wildcarded) pattern to filter the returned _source
*/
public NoopSearchRequestBuilder setFetchSource(@Nullable String[] includes, @Nullable String[] excludes) {
sourceBuilder().fetchSource(includes, excludes);
return this;
}
/**
* Adds a docvalue based field to load and return. The field does not have to be stored,
* but its recommended to use non analyzed or numeric fields.
*
* @param name The field to get from the docvalue
*/
public NoopSearchRequestBuilder addDocValueField(String name) {
sourceBuilder().docValueField(name);
return this;
}
/**
* Adds a stored field to load and return (note, it must be stored) as part of the search request.
* If none are specified, the source of the document will be return.
*/
public NoopSearchRequestBuilder addStoredField(String field) {
sourceBuilder().storedField(field);
return this;
}
/**
* Adds a script based field to load and return. The field does not have to be stored,
* but its recommended to use non analyzed or numeric fields.
*
* @param name The name that will represent this value in the return hit
* @param script The script to use
*/
public NoopSearchRequestBuilder addScriptField(String name, Script script) {
sourceBuilder().scriptField(name, script);
return this;
}
/**
* Adds a sort against the given field name and the sort ordering.
*
* @param field The name of the field
* @param order The sort ordering
*/
public NoopSearchRequestBuilder addSort(String field, SortOrder order) {
sourceBuilder().sort(field, order);
return this;
}
/**
* Adds a generic sort builder.
*
* @see org.elasticsearch.search.sort.SortBuilders
*/
public NoopSearchRequestBuilder addSort(SortBuilder sort) {
sourceBuilder().sort(sort);
return this;
}
/**
* Set the sort values that indicates which docs this request should "search after".
*/
public NoopSearchRequestBuilder searchAfter(Object[] values) {
sourceBuilder().searchAfter(values);
return this;
}
public NoopSearchRequestBuilder slice(SliceBuilder builder) {
sourceBuilder().slice(builder);
return this;
}
/**
* Applies when sorting, and controls if scores will be tracked as well. Defaults to
* {@code false}.
*/
public NoopSearchRequestBuilder setTrackScores(boolean trackScores) {
sourceBuilder().trackScores(trackScores);
return this;
}
/**
* Sets the fields to load and return as part of the search request. If none
* are specified, the source of the document will be returned.
*/
public NoopSearchRequestBuilder storedFields(String... fields) {
sourceBuilder().storedFields(Arrays.asList(fields));
return this;
}
/**
* Adds an aggregation to the search operation.
*/
public NoopSearchRequestBuilder addAggregation(AggregationBuilder aggregation) {
sourceBuilder().aggregation(aggregation);
return this;
}
/**
* Adds an aggregation to the search operation.
*/
public NoopSearchRequestBuilder addAggregation(PipelineAggregationBuilder aggregation) {
sourceBuilder().aggregation(aggregation);
return this;
}
public NoopSearchRequestBuilder highlighter(HighlightBuilder highlightBuilder) {
sourceBuilder().highlighter(highlightBuilder);
return this;
}
/**
* Delegates to {@link org.elasticsearch.search.builder.SearchSourceBuilder#suggest(SuggestBuilder)}
*/
public NoopSearchRequestBuilder suggest(SuggestBuilder suggestBuilder) {
sourceBuilder().suggest(suggestBuilder);
return this;
}
/**
* Clears all rescorers on the builder and sets the first one. To use multiple rescore windows use
* {@link #addRescorer(org.elasticsearch.search.rescore.RescorerBuilder, int)}.
*
* @param rescorer rescorer configuration
* @return this for chaining
*/
public NoopSearchRequestBuilder setRescorer(RescorerBuilder<?> rescorer) {
sourceBuilder().clearRescorers();
return addRescorer(rescorer);
}
/**
* Clears all rescorers on the builder and sets the first one. To use multiple rescore windows use
* {@link #addRescorer(org.elasticsearch.search.rescore.RescorerBuilder, int)}.
*
* @param rescorer rescorer configuration
* @param window rescore window
* @return this for chaining
*/
public NoopSearchRequestBuilder setRescorer(RescorerBuilder rescorer, int window) {
sourceBuilder().clearRescorers();
return addRescorer(rescorer.windowSize(window));
}
/**
* Adds a new rescorer.
*
* @param rescorer rescorer configuration
* @return this for chaining
*/
public NoopSearchRequestBuilder addRescorer(RescorerBuilder<?> rescorer) {
sourceBuilder().addRescorer(rescorer);
return this;
}
/**
* Adds a new rescorer.
*
* @param rescorer rescorer configuration
* @param window rescore window
* @return this for chaining
*/
public NoopSearchRequestBuilder addRescorer(RescorerBuilder<?> rescorer, int window) {
sourceBuilder().addRescorer(rescorer.windowSize(window));
return this;
}
/**
* Clears all rescorers from the builder.
*
* @return this for chaining
*/
public NoopSearchRequestBuilder clearRescorers() {
sourceBuilder().clearRescorers();
return this;
}
/**
* Sets the source of the request as a SearchSourceBuilder.
*/
public NoopSearchRequestBuilder setSource(SearchSourceBuilder source) {
request.source(source);
return this;
}
/**
* Sets if this request should use the request cache or not, assuming that it can (for
* example, if "now" is used, it will never be cached). By default (not set, or null,
* will default to the index level setting if request cache is enabled or not).
*/
public NoopSearchRequestBuilder setRequestCache(Boolean requestCache) {
request.requestCache(requestCache);
return this;
}
/**
* Should the query be profiled. Defaults to <code>false</code>
*/
public NoopSearchRequestBuilder setProfile(boolean profile) {
sourceBuilder().profile(profile);
return this;
}
@Override
public String toString() {
if (request.source() != null) {
return request.source().toString();
}
return new SearchSourceBuilder().toString();
}
private SearchSourceBuilder sourceBuilder() {
if (request.source() == null) {
request.source(new SearchSourceBuilder());
}
return request.source();
}
}
| apache-2.0 |
adlnet/xAPI-Android-Roses | app/src/main/java/org/adl/roses/SlideFragment.java | 4544 | package org.adl.roses;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SlideFragment extends Fragment {
public SlideFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myInflatedView = inflater.inflate(R.layout.fragment_slide, container, false);
// Grab current activity and retrieve its moduleId and slideId
ContentActivity activity = (ContentActivity)getActivity();
int android_act_id = activity.getAndroidId();
int slide_id = activity.getCurrentSlide();
// Set the fragment's textview based on which module and slide is currently active
TextView txt = (TextView)myInflatedView.findViewById(R.id.fragText);
switch (android_act_id){
case 0:
switch (slide_id){
case 0:
txt.setText(getString(R.string.mod_what_1));
break;
case 1:
txt.setText(getString(R.string.mod_what_2));
break;
case 2:
txt.setText(getString(R.string.mod_what_3));
break;
}
break;
case 1:
switch (slide_id){
case 0:
txt.setText(getString(R.string.mod_pruning_1));
break;
case 1:
txt.setText(getString(R.string.mod_pruning_2));
break;
case 2:
txt.setText(getString(R.string.mod_pruning_3));
break;
}
break;
case 2:
switch (slide_id){
case 0:
txt.setText(getString(R.string.mod_deadheading_1));
break;
case 1:
txt.setText(getString(R.string.mod_deadheading_2));
break;
case 2:
txt.setText(getString(R.string.mod_deadheading_3));
break;
}
break;
case 3:
switch (slide_id){
case 0:
txt.setText(getString(R.string.mod_shearing_1));
break;
case 1:
txt.setText(getString(R.string.mod_shearing_2));
break;
case 2:
txt.setText(getString(R.string.mod_shearing_3));
break;
}
break;
case 4:
switch (slide_id){
case 0:
txt.setText(getString(R.string.mod_hybrids_1));
break;
case 1:
txt.setText(getString(R.string.mod_hybrids_2));
break;
case 2:
txt.setText(getString(R.string.mod_hybrids_3));
break;
}
break;
case 5:
switch (slide_id){
case 0:
txt.setText(getString(R.string.mod_styles_1));
break;
case 1:
txt.setText(getString(R.string.mod_styles_2));
break;
case 2:
txt.setText(getString(R.string.mod_styles_3));
break;
}
break;
case 6:
switch (slide_id){
case 0:
txt.setText(getString(R.string.mod_symbolism_1));
break;
case 1:
txt.setText(getString(R.string.mod_symbolism_2));
break;
case 2:
txt.setText(getString(R.string.mod_symbolism_3));
break;
}
break;
}
// Inflate the layout for this fragment
return myInflatedView;
}
}
| apache-2.0 |
jonathanchristison/fabric8 | tooling/rh-support/support-core/src/main/java/io/fabric8/support/impl/ResourceFactoryImpl.java | 1341 | /**
* Copyright 2005-2015 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.support.impl;
import io.fabric8.support.api.Resource;
import io.fabric8.support.api.ResourceFactory;
import java.io.File;
/**
* Default implementation for {@link io.fabric8.support.api.ResourceFactory}
*/
public class ResourceFactoryImpl implements ResourceFactory {
private final SupportServiceImpl service;
ResourceFactoryImpl(SupportServiceImpl service) {
this.service = service;
}
@Override
public Resource createCommandResource(String command) {
return new CommandResource(service.getCommandProcessor(), command);
}
@Override
public Resource createFileResource(File file) {
return new FileResource(file);
}
}
| apache-2.0 |
trustin/armeria | core/src/main/java/com/linecorp/armeria/common/StringValueConverter.java | 5875 | /*
* Copyright 2016 LINE Corporation
*
* LINE Corporation 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.common;
import java.time.Instant;
import java.time.temporal.TemporalAccessor;
import java.util.Calendar;
import java.util.Date;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.internal.common.util.StringUtil;
import io.netty.handler.codec.DateFormatter;
import io.netty.handler.codec.ValueConverter;
/**
* Converts to/from native types, general {@link Object}, and {@link CharSequence}s.
*/
final class StringValueConverter implements ValueConverter<String> {
// Forked from Netty 4.1.34 at 1611acf4cee4481b89a2cf024ccf821de2dbf13c (CharSequenceValueConverter) and
// 4c64c98f348131e0792ba4a92ce3d0003237d56a (DefaultHttpHeaders.HeaderValueConverter)
static final StringValueConverter INSTANCE = new StringValueConverter();
private StringValueConverter() {}
@Nullable
@Override
@SuppressWarnings("UseOfObsoleteDateTimeApi")
public String convertObject(@Nullable Object value) {
if (value == null) {
return null;
}
// Try the types that appears more often first.
if (value instanceof CharSequence ||
value instanceof Number ||
value instanceof MediaType) {
return value.toString();
}
if (value instanceof Instant) {
return DateFormatter.format(new Date(((Instant) value).toEpochMilli()));
}
if (value instanceof TemporalAccessor) {
return DateFormatter.format(new Date(Instant.from((TemporalAccessor) value).toEpochMilli()));
}
if (value instanceof CacheControl) {
return ((CacheControl) value).asHeaderValue();
}
if (value instanceof ContentDisposition) {
return ((ContentDisposition) value).asHeaderValue();
}
// Obsolete types.
if (value instanceof Date) {
return DateFormatter.format((Date) value);
}
if (value instanceof Calendar) {
return DateFormatter.format(((Calendar) value).getTime());
}
return value.toString();
}
@Override
public String convertInt(int value) {
return StringUtil.toString(value);
}
@Override
public String convertLong(long value) {
return StringUtil.toString(value);
}
@Override
public String convertDouble(double value) {
return String.valueOf(value);
}
@Override
public String convertChar(char value) {
return String.valueOf(value);
}
@Override
public String convertBoolean(boolean value) {
return String.valueOf(value);
}
@Override
public String convertFloat(float value) {
return String.valueOf(value);
}
@Override
public boolean convertToBoolean(String value) {
return Boolean.parseBoolean(value);
}
@Override
public String convertByte(byte value) {
return StringUtil.toString(value & 0xFF);
}
@Override
public byte convertToByte(String value) {
if (!value.isEmpty()) {
return (byte) value.charAt(0);
}
return Byte.parseByte(value);
}
@Override
public char convertToChar(String value) {
return value.charAt(0);
}
@Override
public String convertShort(short value) {
return StringUtil.toString(value);
}
@Override
public short convertToShort(String value) {
return Short.valueOf(value);
}
@Override
public int convertToInt(String value) {
return Integer.parseInt(value);
}
@Override
public long convertToLong(String value) {
return Long.parseLong(value);
}
@Override
public String convertTimeMillis(long value) {
return DateFormatter.format(new Date(value));
}
@Override
public long convertToTimeMillis(String value) {
@SuppressWarnings("UseOfObsoleteDateTimeApi")
Date date = null;
try {
date = DateFormatter.parseHttpDate(value);
} catch (Exception ignored) {
// `parseHttpDate()` can raise an exception rather than returning `null`
// when the given value has more than 64 characters.
}
if (date == null) {
throw new IllegalArgumentException("not a date: " + value);
}
return date.getTime();
}
@Override
public float convertToFloat(String value) {
return Float.valueOf(value);
}
@Override
public double convertToDouble(String value) {
return Double.valueOf(value);
}
}
| apache-2.0 |
nurkiewicz/async-retry | src/test/java/com/nurkiewicz/asyncretry/AsyncRetryJobTest.java | 5786 | package com.nurkiewicz.asyncretry;
import com.nurkiewicz.asyncretry.policy.AbortRetryException;
import org.assertj.core.api.Assertions;
import org.mockito.InOrder;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.SocketException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static com.nurkiewicz.asyncretry.backoff.FixedIntervalBackoff.DEFAULT_PERIOD_MILLIS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.times;
/**
* @author Tomasz Nurkiewicz
* @since 7/21/13, 7:07 PM
*/
public class AsyncRetryJobTest extends AbstractBaseTestCase {
@Test
public void shouldUnwrapUserFutureAndReturnIt() throws Exception {
//given
final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock);
given(serviceMock.safeAsync()).willReturn(CompletableFuture.completedFuture("42"));
//when
final CompletableFuture<String> future = executor.getFutureWithRetry(ctx -> serviceMock.safeAsync());
//then
assertThat(future.get()).isEqualTo("42");
}
@Test
public void shouldSucceedAfterFewAsynchronousRetries() throws Exception {
//given
final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock);
given(serviceMock.safeAsync()).willReturn(
failedAsync(new SocketException("First")),
failedAsync(new IOException("Second")),
CompletableFuture.completedFuture("42")
);
//when
final CompletableFuture<String> future = executor.getFutureWithRetry(ctx -> serviceMock.safeAsync());
//then
assertThat(future.get()).isEqualTo("42");
}
@Test
public void shouldScheduleTwoTimesWhenRetries() throws Exception {
//given
final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock);
given(serviceMock.safeAsync()).willReturn(
failedAsync(new SocketException("First")),
failedAsync(new IOException("Second")),
CompletableFuture.completedFuture("42")
);
//when
final CompletableFuture<String> future = executor.getFutureWithRetry(ctx -> serviceMock.safeAsync());
//then
future.get();
final InOrder order = inOrder(schedulerMock);
order.verify(schedulerMock).schedule(notNullRunnable(), eq(0L), millis());
order.verify(schedulerMock, times(2)).schedule(notNullRunnable(), eq(DEFAULT_PERIOD_MILLIS), millis());
}
private CompletableFuture<String> failedAsync(Throwable throwable) {
final CompletableFuture<String> future = new CompletableFuture<>();
future.completeExceptionally(throwable);
return future;
}
@Test
public void shouldRethrowOriginalExceptionFromUserFutureCompletion() throws Exception {
//given
final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock).
abortOn(SocketException.class);
given(serviceMock.safeAsync()).willReturn(
failedAsync(new SocketException(DON_T_PANIC))
);
//when
final CompletableFuture<String> future = executor.getFutureWithRetry(ctx -> serviceMock.safeAsync());
//then
assertThat(future.isCompletedExceptionally()).isTrue();
try {
future.get();
failBecauseExceptionWasNotThrown(ExecutionException.class);
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
assertThat(cause).isInstanceOf(SocketException.class);
assertThat(cause).hasMessage(DON_T_PANIC);
}
}
@Test
public void shouldRethrowOriginalExceptionFromUserFutureCompletionAndAbortWhenTestFails() throws Exception {
//given
final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock).
abortIf(t -> { throw new RuntimeException("test invalid"); });
given(serviceMock.safeAsync()).willReturn(
failedAsync(new SocketException(DON_T_PANIC))
);
//when
final CompletableFuture<String> future = executor.getFutureWithRetry(ctx -> serviceMock.safeAsync());
//then
assertThat(future.isCompletedExceptionally()).isTrue();
try {
future.get();
failBecauseExceptionWasNotThrown(ExecutionException.class);
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
assertThat(cause).isInstanceOf(SocketException.class);
assertThat(cause).hasMessage(DON_T_PANIC);
}
}
@Test
public void shouldAbortWhenTargetFutureWantsToAbort() throws Exception {
//given
final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock);
given(serviceMock.safeAsync()).willReturn(
failedAsync(new AbortRetryException())
);
//when
final CompletableFuture<String> future = executor.getFutureWithRetry(ctx -> serviceMock.safeAsync());
//then
assertThat(future.isCompletedExceptionally()).isTrue();
try {
future.get();
failBecauseExceptionWasNotThrown(ExecutionException.class);
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
assertThat(cause).isInstanceOf(AbortRetryException.class);
}
}
@Test
public void shouldRethrowExceptionThatWasThrownFromUserTaskBeforeReturningFuture() throws Exception {
//given
final RetryExecutor executor = new AsyncRetryExecutor(schedulerMock).
abortOn(IllegalArgumentException.class);
given(serviceMock.safeAsync()).willThrow(new IllegalArgumentException(DON_T_PANIC));
//when
final CompletableFuture<String> future = executor.getFutureWithRetry(ctx -> serviceMock.safeAsync());
//then
assertThat(future.isCompletedExceptionally()).isTrue();
try {
future.get();
Assertions.failBecauseExceptionWasNotThrown(ExecutionException.class);
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class);
assertThat(e.getCause()).hasMessage(DON_T_PANIC);
}
}
}
| apache-2.0 |
ThiagoGarciaAlves/intellij-community | platform/core-api/src/com/intellij/openapi/application/ApplicationInfo.java | 3592 | /*
* 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.openapi.application;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.BuildNumber;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.util.Calendar;
public abstract class ApplicationInfo {
public abstract Calendar getBuildDate();
public abstract BuildNumber getBuild();
public abstract String getApiVersion();
public abstract String getMajorVersion();
public abstract String getMinorVersion();
public abstract String getMicroVersion();
public abstract String getPatchVersion();
public abstract String getVersionName();
/**
* Returns the first number from 'minor' part of the version. This method is temporary added because some products specify composite number (like '1.3')
* in 'minor version' attribute instead of using 'micro version' (i.e. set minor='1' micro='3').
* @see org.jetbrains.intellij.build.ApplicationInfoProperties#minorVersionMainPart
*/
public final String getMinorVersionMainPart() {
return ObjectUtils.notNull(StringUtil.substringBefore(getMinorVersion(), "."), getMinorVersion());
}
@Nullable
public abstract String getHelpURL();
/**
* Use this method to refer to the company in official contexts where it may have any legal implications.
* @see #getShortCompanyName()
* @return full name of the product vendor, e.g. 'JetBrains s.r.o.' for JetBrains products
*/
public abstract String getCompanyName();
/**
* Use this method to refer to the company in a less formal way, e.g. in UI messages or directory names.
* @see #getCompanyName()
* @return shortened name of the product vendor without 'Inc.' or similar suffixes, e.g. 'JetBrains' for JetBrains products
*/
public abstract String getShortCompanyName();
public abstract String getCompanyURL();
@Nullable
public abstract String getThirdPartySoftwareURL();
public abstract String getJetbrainsTvUrl();
public abstract String getEvalLicenseUrl();
public abstract String getKeyConversionUrl();
@Nullable
public abstract Rectangle getAboutLogoRect();
public abstract boolean hasHelp();
public abstract boolean hasContextHelp();
public abstract String getFullVersion();
public abstract String getStrictVersion();
public static ApplicationInfo getInstance() {
return ServiceManager.getService(ApplicationInfo.class);
}
public static boolean helpAvailable() {
return ApplicationManager.getApplication() != null && getInstance() != null && getInstance().hasHelp();
}
public static boolean contextHelpAvailable() {
return ApplicationManager.getApplication() != null && getInstance() != null && getInstance().hasContextHelp();
}
/** @deprecated use {@link #getBuild()} instead (to remove in IDEA 16) */
@SuppressWarnings("UnusedDeclaration")
public String getBuildNumber() {
return getBuild().asString();
}
}
| apache-2.0 |
roberthafner/flowable-engine | modules/flowable-engine/src/main/java/org/activiti/engine/impl/persistence/entity/TaskEntityManager.java | 1953 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.persistence.entity;
import java.util.List;
import java.util.Map;
import org.activiti.engine.impl.TaskQueryImpl;
import org.activiti.engine.task.Task;
public interface TaskEntityManager extends EntityManager<TaskEntity> {
void insert(TaskEntity taskEntity, ExecutionEntity execution);
void changeTaskAssignee(TaskEntity taskEntity, String assignee);
void changeTaskOwner(TaskEntity taskEntity, String owner);
List<TaskEntity> findTasksByExecutionId(String executionId);
List<TaskEntity> findTasksByProcessInstanceId(String processInstanceId);
List<Task> findTasksByQueryCriteria(TaskQueryImpl taskQuery);
List<Task> findTasksAndVariablesByQueryCriteria(TaskQueryImpl taskQuery);
long findTaskCountByQueryCriteria(TaskQueryImpl taskQuery);
List<Task> findTasksByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults);
long findTaskCountByNativeQuery(Map<String, Object> parameterMap);
List<Task> findTasksByParentTaskId(String parentTaskId);
void updateTaskTenantIdForDeployment(String deploymentId, String newTenantId);
void deleteTask(String taskId, String deleteReason, boolean cascade);
void deleteTasksByProcessInstanceId(String processInstanceId, String deleteReason, boolean cascade);
void deleteTask(TaskEntity task, String deleteReason, boolean cascade, boolean cancel);
} | apache-2.0 |
quann169/MotownBlueCurrent | ocpp/v15-soap/src/main/java/io/motown/ocpp/v15/soap/centralsystem/LocationTranslator.java | 1887 | /**
* Copyright (C) 2013 Motown.IO (info@motown.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.motown.ocpp.v15.soap.centralsystem;
import io.motown.domain.api.chargingstation.Location;
import javax.annotation.Nullable;
/**
* Adapter which translates a {@code io.motown.ocpp.v15.soap.centralsystem.schema.Location} to a {@code Location}.
*/
class LocationTranslator implements Translator<Location> {
private final io.motown.ocpp.v15.soap.centralsystem.schema.Location location;
/**
* Creates a {@code LocationTranslationAdapter}.
*
* @param location the location to translate.
*/
public LocationTranslator(@Nullable io.motown.ocpp.v15.soap.centralsystem.schema.Location location) {
this.location = location;
}
/**
* {@inheritDoc}
*/
@Override
public Location translate() {
if (this.location == null) {
// In OCPP 1.5, OUTLET is the default value.
return Location.OUTLET;
}
switch (this.location) {
case INLET:
return Location.INLET;
case OUTLET:
return Location.OUTLET;
case BODY:
return Location.BODY;
default:
throw new AssertionError(String.format("Unknown value for Location: '%s'", location));
}
}
}
| apache-2.0 |
darionyaphet/flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/TypeInferenceExtractor.java | 10427 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.types.extraction;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.catalog.DataTypeFactory;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.AsyncTableFunction;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.table.functions.UserDefinedFunction;
import org.apache.flink.table.functions.UserDefinedFunctionHelper;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.inference.InputTypeStrategies;
import org.apache.flink.table.types.inference.InputTypeStrategy;
import org.apache.flink.table.types.inference.TypeInference;
import org.apache.flink.table.types.inference.TypeStrategies;
import org.apache.flink.table.types.inference.TypeStrategy;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static org.apache.flink.table.types.extraction.ExtractionUtils.extractionError;
import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createGenericResultExtraction;
import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createParameterAndReturnTypeVerification;
import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createParameterSignatureExtraction;
import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createParameterVerification;
import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createParameterWithAccumulatorVerification;
import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createParameterWithArgumentVerification;
import static org.apache.flink.table.types.extraction.FunctionMappingExtractor.createReturnTypeResultExtraction;
/**
* Reflection-based utility for extracting a {@link TypeInference} from a supported subclass of
* {@link UserDefinedFunction}.
*
* <p>The behavior of this utility can be influenced by {@link DataTypeHint}s and {@link FunctionHint}s
* which have higher precedence than the reflective information.
*
* <p>Note: This utility assumes that functions have been validated before regarding accessibility of
* class/methods and serializability.
*/
@Internal
public final class TypeInferenceExtractor {
/**
* Extracts a type inference from a {@link ScalarFunction}.
*/
public static TypeInference forScalarFunction(
DataTypeFactory typeFactory,
Class<? extends ScalarFunction> function) {
final FunctionMappingExtractor mappingExtractor = new FunctionMappingExtractor(
typeFactory,
function,
UserDefinedFunctionHelper.SCALAR_EVAL,
createParameterSignatureExtraction(0),
null,
createReturnTypeResultExtraction(),
createParameterAndReturnTypeVerification());
return extractTypeInference(mappingExtractor);
}
/**
* Extracts a type inference from a {@link AggregateFunction}.
*/
public static TypeInference forAggregateFunction(
DataTypeFactory typeFactory,
Class<? extends AggregateFunction<?, ?>> function) {
final FunctionMappingExtractor mappingExtractor = new FunctionMappingExtractor(
typeFactory,
function,
UserDefinedFunctionHelper.AGGREGATE_ACCUMULATE,
createParameterSignatureExtraction(1),
createGenericResultExtraction(AggregateFunction.class, 1, false),
createGenericResultExtraction(AggregateFunction.class, 0, true),
createParameterWithAccumulatorVerification());
return extractTypeInference(mappingExtractor);
}
/**
* Extracts a type inference from a {@link TableFunction}.
*/
public static TypeInference forTableFunction(
DataTypeFactory typeFactory,
Class<? extends TableFunction<?>> function) {
final FunctionMappingExtractor mappingExtractor = new FunctionMappingExtractor(
typeFactory,
function,
UserDefinedFunctionHelper.TABLE_EVAL,
createParameterSignatureExtraction(0),
null,
createGenericResultExtraction(TableFunction.class, 0, true),
createParameterVerification());
return extractTypeInference(mappingExtractor);
}
/**
* Extracts a type inference from a {@link TableAggregateFunction}.
*/
public static TypeInference forTableAggregateFunction(
DataTypeFactory typeFactory,
Class<? extends TableAggregateFunction<?, ?>> function) {
final FunctionMappingExtractor mappingExtractor = new FunctionMappingExtractor(
typeFactory,
function,
UserDefinedFunctionHelper.TABLE_AGGREGATE_ACCUMULATE,
createParameterSignatureExtraction(1),
createGenericResultExtraction(TableAggregateFunction.class, 1, false),
createGenericResultExtraction(TableAggregateFunction.class, 0, true),
createParameterWithAccumulatorVerification());
return extractTypeInference(mappingExtractor);
}
/**
* Extracts a type inference from a {@link AsyncTableFunction}.
*/
public static TypeInference forAsyncTableFunction(
DataTypeFactory typeFactory,
Class<? extends AsyncTableFunction<?>> function) {
final FunctionMappingExtractor mappingExtractor = new FunctionMappingExtractor(
typeFactory,
function,
UserDefinedFunctionHelper.ASYNC_TABLE_EVAL,
createParameterSignatureExtraction(1),
null,
createGenericResultExtraction(AsyncTableFunction.class, 0, true),
createParameterWithArgumentVerification(CompletableFuture.class));
return extractTypeInference(mappingExtractor);
}
private static TypeInference extractTypeInference(FunctionMappingExtractor mappingExtractor) {
try {
return extractTypeInferenceOrError(mappingExtractor);
} catch (Throwable t) {
throw extractionError(
t,
"Could not extract a valid type inference for function class '%s'. " +
"Please check for implementation mistakes and/or provide a corresponding hint.",
mappingExtractor.getFunction().getName());
}
}
private static TypeInference extractTypeInferenceOrError(FunctionMappingExtractor mappingExtractor) {
final Map<FunctionSignatureTemplate, FunctionResultTemplate> outputMapping =
mappingExtractor.extractOutputMapping();
if (!mappingExtractor.hasAccumulator()) {
return buildInference(null, outputMapping);
}
final Map<FunctionSignatureTemplate, FunctionResultTemplate> accumulatorMapping =
mappingExtractor.extractAccumulatorMapping();
return buildInference(accumulatorMapping, outputMapping);
}
private static TypeInference buildInference(
@Nullable Map<FunctionSignatureTemplate, FunctionResultTemplate> accumulatorMapping,
Map<FunctionSignatureTemplate, FunctionResultTemplate> outputMapping) {
final TypeInference.Builder builder = TypeInference.newBuilder();
configureNamedArguments(builder, outputMapping);
configureTypedArguments(builder, outputMapping);
builder.inputTypeStrategy(translateInputTypeStrategy(outputMapping));
if (accumulatorMapping != null) {
// verify that accumulator and output are derived from the same input strategy
if (!accumulatorMapping.keySet().equals(outputMapping.keySet())) {
throw extractionError(
"Mismatch between accumulator signature and output signature. " +
"Both intermediate and output results must be derived from the same input strategy.");
}
builder.accumulatorTypeStrategy(translateResultTypeStrategy(accumulatorMapping));
}
builder.outputTypeStrategy(translateResultTypeStrategy(outputMapping));
return builder.build();
}
private static void configureNamedArguments(
TypeInference.Builder builder,
Map<FunctionSignatureTemplate, FunctionResultTemplate> outputMapping) {
final Set<FunctionSignatureTemplate> signatures = outputMapping.keySet();
if (signatures.stream().anyMatch(s -> s.isVarArgs || s.argumentNames == null)) {
return;
}
final Set<List<String>> argumentNames = signatures.stream()
.map(s -> {
assert s.argumentNames != null;
return Arrays.asList(s.argumentNames);
})
.collect(Collectors.toSet());
if (argumentNames.size() != 1) {
return;
}
builder.namedArguments(argumentNames.iterator().next());
}
private static void configureTypedArguments(
TypeInference.Builder builder,
Map<FunctionSignatureTemplate, FunctionResultTemplate> outputMapping) {
if (outputMapping.size() != 1) {
return;
}
final FunctionSignatureTemplate signature = outputMapping.keySet().iterator().next();
final List<DataType> dataTypes = signature.argumentTemplates.stream()
.map(a -> a.dataType)
.collect(Collectors.toList());
if (!signature.isVarArgs && dataTypes.stream().allMatch(Objects::nonNull)) {
builder.typedArguments(dataTypes);
}
}
private static TypeStrategy translateResultTypeStrategy(Map<FunctionSignatureTemplate, FunctionResultTemplate> resultMapping) {
final Map<InputTypeStrategy, TypeStrategy> mappings = resultMapping.entrySet()
.stream()
.collect(
Collectors.toMap(
e -> e.getKey().toInputTypeStrategy(),
e -> e.getValue().toTypeStrategy()));
return TypeStrategies.mapping(mappings);
}
private static InputTypeStrategy translateInputTypeStrategy(Map<FunctionSignatureTemplate, FunctionResultTemplate> outputMapping) {
return outputMapping.keySet().stream()
.map(FunctionSignatureTemplate::toInputTypeStrategy)
.reduce(InputTypeStrategies::or)
.orElse(InputTypeStrategies.sequence());
}
}
| apache-2.0 |
maduhu/mifos-head | application/src/test/java/org/mifos/accounts/struts/actionforms/ApplyChargeActionFormTest.java | 3220 | /*
* Copyright (c) 2005-2010 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.accounts.struts.actionforms;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import org.apache.struts.action.ActionErrors;
import org.junit.Test;
import org.mifos.framework.TestUtils;
public class ApplyChargeActionFormTest {
// for constructing the ChargeType member
private static final String FEE_ID = "-1";
private static final String IS_RATE_TYPE = "1";
private static final String IS_NOT_RATE_TYPE = "0";
private static final String CHARGE_TYPE_SEPARATOR = ":";
private String constructChargeType(String feeId, String isRateType) {
return feeId + CHARGE_TYPE_SEPARATOR + isRateType;
}
/**
* Test method for <b>ApplyChargeActionForm#validateAmount(ActionErrors, Locale)</b>.
*/
@Test
public void testValidateValidRate() {
ApplyChargeActionForm form = new ApplyChargeActionForm();
form.setCharge("1.12345");
form.setChargeType(constructChargeType(FEE_ID, IS_RATE_TYPE));
ActionErrors errors = new ActionErrors();
Locale locale = TestUtils.ukLocale();
form.validateAmount(errors, locale);
assertEquals(0,errors.size());
}
@Test
public void testValidateInvalidRateWithTooMuchPrecision() {
ApplyChargeActionForm form = new ApplyChargeActionForm();
form.setCharge("1.123456");
form.setChargeType(constructChargeType(FEE_ID, IS_RATE_TYPE));
ActionErrors errors = new ActionErrors();
Locale locale = TestUtils.ukLocale();
form.validateAmount(errors, locale);
assertEquals(1,errors.size());
}
@Test
public void testValidateValidAmount() {
ApplyChargeActionForm form = new ApplyChargeActionForm();
form.setCharge("1.1");
form.setChargeType(constructChargeType(FEE_ID, IS_NOT_RATE_TYPE));
ActionErrors errors = new ActionErrors();
Locale locale = TestUtils.ukLocale();
form.validateAmount(errors, locale);
assertEquals(0,errors.size());
}
@Test
public void testValidateInvalidAmount() {
ApplyChargeActionForm form = new ApplyChargeActionForm();
form.setCharge("1.12345");
form.setChargeType(constructChargeType(FEE_ID, IS_NOT_RATE_TYPE));
ActionErrors errors = new ActionErrors();
Locale locale = TestUtils.ukLocale();
form.validateAmount(errors, locale);
assertEquals(1,errors.size());
}
}
| apache-2.0 |
yulang/Modified-Parquet | parquet-hadoop/src/main/java/org/apache/parquet/hadoop/ColumnChunkPageWriteStore.java | 9654 | /*
* 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.parquet.hadoop;
import static org.apache.parquet.Log.INFO;
import static org.apache.parquet.column.statistics.Statistics.getStatsBasedOnType;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.parquet.Log;
import org.apache.parquet.bytes.BytesInput;
import org.apache.parquet.bytes.ConcatenatingByteArrayCollector;
import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.column.Encoding;
import org.apache.parquet.column.page.DictionaryPage;
import org.apache.parquet.column.page.PageWriteStore;
import org.apache.parquet.column.page.PageWriter;
import org.apache.parquet.column.statistics.Statistics;
import org.apache.parquet.format.converter.ParquetMetadataConverter;
import org.apache.parquet.hadoop.CodecFactory.BytesCompressor;
import org.apache.parquet.io.ParquetEncodingException;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.bytes.ByteBufferAllocator;
class ColumnChunkPageWriteStore implements PageWriteStore {
private static final Log LOG = Log.getLog(ColumnChunkPageWriteStore.class);
private static ParquetMetadataConverter parquetMetadataConverter = new ParquetMetadataConverter();
private static final class ColumnChunkPageWriter implements PageWriter {
private final ColumnDescriptor path;
private final BytesCompressor compressor;
private final ByteArrayOutputStream tempOutputStream = new ByteArrayOutputStream();
private final ConcatenatingByteArrayCollector buf;
private DictionaryPage dictionaryPage;
private long uncompressedLength;
private long compressedLength;
private long totalValueCount;
private int pageCount;
private Set<Encoding> encodings = new HashSet<Encoding>();
private Statistics totalStatistics;
private final ByteBufferAllocator allocator;
private ColumnChunkPageWriter(ColumnDescriptor path,
BytesCompressor compressor,
ByteBufferAllocator allocator) {
this.path = path;
this.compressor = compressor;
this.allocator = allocator;
this.buf = new ConcatenatingByteArrayCollector();
this.totalStatistics = getStatsBasedOnType(this.path.getType());
}
@Override
public void writePage(BytesInput bytes,
int valueCount,
Statistics statistics,
Encoding rlEncoding,
Encoding dlEncoding,
Encoding valuesEncoding) throws IOException {
long uncompressedSize = bytes.size();
if (uncompressedSize > Integer.MAX_VALUE) {
throw new ParquetEncodingException(
"Cannot write page larger than Integer.MAX_VALUE bytes: " +
uncompressedSize);
}
BytesInput compressedBytes = compressor.compress(bytes);
long compressedSize = compressedBytes.size();
if (compressedSize > Integer.MAX_VALUE) {
throw new ParquetEncodingException(
"Cannot write compressed page larger than Integer.MAX_VALUE bytes: "
+ compressedSize);
}
tempOutputStream.reset();
parquetMetadataConverter.writeDataPageHeader(
(int)uncompressedSize,
(int)compressedSize,
valueCount,
statistics,
rlEncoding,
dlEncoding,
valuesEncoding,
tempOutputStream);
this.uncompressedLength += uncompressedSize;
this.compressedLength += compressedSize;
this.totalValueCount += valueCount;
this.pageCount += 1;
this.totalStatistics.mergeStatistics(statistics);
// by concatenating before collecting instead of collecting twice,
// we only allocate one buffer to copy into instead of multiple.
buf.collect(BytesInput.concat(BytesInput.from(tempOutputStream), compressedBytes));
encodings.add(rlEncoding);
encodings.add(dlEncoding);
encodings.add(valuesEncoding);
}
@Override
public void writePageV2(
int rowCount, int nullCount, int valueCount,
BytesInput repetitionLevels, BytesInput definitionLevels,
Encoding dataEncoding, BytesInput data,
Statistics<?> statistics) throws IOException {
int rlByteLength = toIntWithCheck(repetitionLevels.size());
int dlByteLength = toIntWithCheck(definitionLevels.size());
int uncompressedSize = toIntWithCheck(
data.size() + repetitionLevels.size() + definitionLevels.size()
);
// TODO: decide if we compress
BytesInput compressedData = compressor.compress(data);
int compressedSize = toIntWithCheck(
compressedData.size() + repetitionLevels.size() + definitionLevels.size()
);
tempOutputStream.reset();
parquetMetadataConverter.writeDataPageV2Header(
uncompressedSize, compressedSize,
valueCount, nullCount, rowCount,
statistics,
dataEncoding,
rlByteLength,
dlByteLength,
tempOutputStream);
this.uncompressedLength += uncompressedSize;
this.compressedLength += compressedSize;
this.totalValueCount += valueCount;
this.pageCount += 1;
this.totalStatistics.mergeStatistics(statistics);
// by concatenating before collecting instead of collecting twice,
// we only allocate one buffer to copy into instead of multiple.
buf.collect(
BytesInput.concat(
BytesInput.from(tempOutputStream),
repetitionLevels,
definitionLevels,
compressedData)
);
encodings.add(dataEncoding);
}
private int toIntWithCheck(long size) {
if (size > Integer.MAX_VALUE) {
throw new ParquetEncodingException(
"Cannot write page larger than " + Integer.MAX_VALUE + " bytes: " +
size);
}
return (int)size;
}
@Override
public long getMemSize() {
return buf.size();
}
public void writeToFileWriter(ParquetFileWriter writer) throws IOException {
writer.startColumn(path, totalValueCount, compressor.getCodecName());
if (dictionaryPage != null) {
writer.writeDictionaryPage(dictionaryPage);
encodings.add(dictionaryPage.getEncoding());
}
writer.writeDataPages(buf, uncompressedLength, compressedLength, totalStatistics, new ArrayList<Encoding>(encodings));
writer.endColumn();
if (INFO) {
LOG.info(
String.format(
"written %,dB for %s: %,d values, %,dB raw, %,dB comp, %d pages, encodings: %s",
buf.size(), path, totalValueCount, uncompressedLength, compressedLength, pageCount, encodings)
+ (dictionaryPage != null ? String.format(
", dic { %,d entries, %,dB raw, %,dB comp}",
dictionaryPage.getDictionarySize(), dictionaryPage.getUncompressedSize(), dictionaryPage.getDictionarySize())
: ""));
}
encodings.clear();
pageCount = 0;
}
@Override
public long allocatedSize() {
return buf.size();
}
@Override
public void writeDictionaryPage(DictionaryPage dictionaryPage) throws IOException {
if (this.dictionaryPage != null) {
throw new ParquetEncodingException("Only one dictionary page is allowed");
}
BytesInput dictionaryBytes = dictionaryPage.getBytes();
int uncompressedSize = (int)dictionaryBytes.size();
BytesInput compressedBytes = compressor.compress(dictionaryBytes);
this.dictionaryPage = new DictionaryPage(BytesInput.copy(compressedBytes), uncompressedSize, dictionaryPage.getDictionarySize(), dictionaryPage.getEncoding());
}
@Override
public String memUsageString(String prefix) {
return buf.memUsageString(prefix + " ColumnChunkPageWriter");
}
}
private final Map<ColumnDescriptor, ColumnChunkPageWriter> writers = new HashMap<ColumnDescriptor, ColumnChunkPageWriter>();
private final MessageType schema;
public ColumnChunkPageWriteStore(BytesCompressor compressor, MessageType schema, ByteBufferAllocator allocator) {
this.schema = schema;
for (ColumnDescriptor path : schema.getColumns()) {
writers.put(path, new ColumnChunkPageWriter(path, compressor, allocator));
}
}
@Override
public PageWriter getPageWriter(ColumnDescriptor path) {
return writers.get(path);
}
public void flushToFileWriter(ParquetFileWriter writer) throws IOException {
for (ColumnDescriptor path : schema.getColumns()) {
ColumnChunkPageWriter pageWriter = writers.get(path);
pageWriter.writeToFileWriter(writer);
}
}
}
| apache-2.0 |
zhenxiao/presto | presto-hive/src/main/java/com/facebook/presto/hive/ParquetRecordCursorProvider.java | 3284 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.hive;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.TupleDomain;
import com.facebook.presto.spi.type.TypeManager;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe;
import org.apache.hadoop.hive.serde2.Deserializer;
import org.joda.time.DateTimeZone;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import static com.facebook.presto.hive.HiveUtil.getDeserializer;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Iterables.filter;
public class ParquetRecordCursorProvider
implements HiveRecordCursorProvider
{
@Override
public Optional<HiveRecordCursor> createHiveRecordCursor(
String clientId,
Configuration configuration,
ConnectorSession session,
Path path,
long start,
long length,
Properties schema,
List<HiveColumnHandle> columns,
List<HivePartitionKey> partitionKeys,
TupleDomain<HiveColumnHandle> effectivePredicate,
DateTimeZone hiveStorageTimeZone,
TypeManager typeManager)
{
@SuppressWarnings("deprecation")
Deserializer deserializer = getDeserializer(schema);
if (!(deserializer instanceof ParquetHiveSerDe)) {
return Optional.empty();
}
// are all columns supported by Parquet code
List<HiveColumnHandle> unsupportedColumns = ImmutableList.copyOf(filter(columns, not(isParquetSupportedType())));
if (!unsupportedColumns.isEmpty()) {
throw new IllegalArgumentException("Can not read Parquet column: " + unsupportedColumns);
}
return Optional.<HiveRecordCursor>of(new ParquetHiveRecordCursor(
configuration,
path,
start,
length,
schema,
partitionKeys,
columns,
typeManager));
}
private static Predicate<HiveColumnHandle> isParquetSupportedType()
{
return new Predicate<HiveColumnHandle>()
{
@Override
public boolean apply(HiveColumnHandle columnHandle)
{
HiveType hiveType = columnHandle.getHiveType();
return hiveType != HiveType.HIVE_TIMESTAMP &&
hiveType != HiveType.HIVE_DATE &&
hiveType != HiveType.HIVE_BINARY;
}
};
}
}
| apache-2.0 |
chizou/geowave | core/index/src/main/java/mil/nga/giat/geowave/core/index/simple/SimpleLongIndexStrategy.java | 879 | package mil.nga.giat.geowave.core.index.simple;
import mil.nga.giat.geowave.core.index.lexicoder.Lexicoders;
/**
* A simple 1-dimensional NumericIndexStrategy that represents an index of
* signed long values. The strategy doesn't use any binning. The ids are simply
* the byte arrays of the value. This index strategy will not perform well for
* inserting ranges because there will be too much replication of data.
*
*/
public class SimpleLongIndexStrategy extends
SimpleNumericIndexStrategy<Long>
{
public SimpleLongIndexStrategy() {
super(
Lexicoders.LONG);
}
@Override
public byte[] toBinary() {
return new byte[] {};
}
@Override
public void fromBinary(
final byte[] bytes ) {}
@Override
protected Long cast(
final double value ) {
return (long) value;
}
@Override
public int getByteOffsetFromDimensionalIndex() {
return 0;
}
}
| apache-2.0 |
dcrankshaw/giraph | giraph-gora/src/main/java/org/apache/giraph/io/gora/GoraEdgeInputFormat.java | 12128 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.giraph.io.gora;
import static org.apache.giraph.io.gora.constants.GiraphGoraConstants.GIRAPH_GORA_DATASTORE_CLASS;
import static org.apache.giraph.io.gora.constants.GiraphGoraConstants.GIRAPH_GORA_END_KEY;
import static org.apache.giraph.io.gora.constants.GiraphGoraConstants.GIRAPH_GORA_KEYS_FACTORY_CLASS;
import static org.apache.giraph.io.gora.constants.GiraphGoraConstants.GIRAPH_GORA_KEY_CLASS;
import static org.apache.giraph.io.gora.constants.GiraphGoraConstants.GIRAPH_GORA_PERSISTENT_CLASS;
import static org.apache.giraph.io.gora.constants.GiraphGoraConstants.GIRAPH_GORA_START_KEY;
import java.io.IOException;
import java.util.List;
import org.apache.giraph.edge.Edge;
import org.apache.giraph.io.EdgeInputFormat;
import org.apache.giraph.io.EdgeReader;
import org.apache.giraph.io.gora.utils.ExtraGoraInputFormat;
import org.apache.giraph.io.gora.utils.GoraUtils;
import org.apache.giraph.io.gora.utils.KeyFactory;
import org.apache.gora.persistency.Persistent;
import org.apache.gora.query.Query;
import org.apache.gora.query.Result;
import org.apache.gora.store.DataStore;
import org.apache.gora.util.GoraException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.log4j.Logger;
/**
* Class which wraps the GoraInputFormat. It's designed
* as an extension point to EdgeInputFormat subclasses who wish
* to read from Gora data sources.
*
* Works with
* {@link GoraVertexOutputFormat}
*
* @param <I> vertex id type
* @param <E> edge type
*/
public abstract class GoraEdgeInputFormat
<I extends WritableComparable, E extends Writable>
extends EdgeInputFormat<I, E> {
/** Start key for querying Gora data store. */
private static Object START_KEY;
/** End key for querying Gora data store. */
private static Object END_KEY;
/** Logger for Gora's vertex input format. */
private static final Logger LOG =
Logger.getLogger(GoraEdgeInputFormat.class);
/** KeyClass used for getting data. */
private static Class<?> KEY_CLASS;
/** The vertex itself will be used as a value inside Gora. */
private static Class<? extends Persistent> PERSISTENT_CLASS;
/** Data store class to be used as backend. */
private static Class<? extends DataStore> DATASTORE_CLASS;
/** Class used to transform strings into Keys */
private static Class<?> KEY_FACTORY_CLASS;
/** Data store used for querying data. */
private static DataStore DATA_STORE;
/** counter for iinput records */
private static int RECORD_COUNTER = 0;
/** Delegate Gora input format */
private static ExtraGoraInputFormat GORA_INPUT_FORMAT =
new ExtraGoraInputFormat();
/**
* @param conf configuration parameters
*/
public void checkInputSpecs(Configuration conf) {
String sDataStoreType =
GIRAPH_GORA_DATASTORE_CLASS.get(getConf());
String sKeyType =
GIRAPH_GORA_KEY_CLASS.get(getConf());
String sPersistentType =
GIRAPH_GORA_PERSISTENT_CLASS.get(getConf());
String sKeyFactoryClass =
GIRAPH_GORA_KEYS_FACTORY_CLASS.get(getConf());
try {
Class<?> keyClass = Class.forName(sKeyType);
Class<?> persistentClass = Class.forName(sPersistentType);
Class<?> dataStoreClass = Class.forName(sDataStoreType);
Class<?> keyFactoryClass = Class.forName(sKeyFactoryClass);
setKeyClass(keyClass);
setPersistentClass((Class<? extends Persistent>) persistentClass);
setDatastoreClass((Class<? extends DataStore>) dataStoreClass);
setKeyFactoryClass(keyFactoryClass);
setDataStore(createDataStore());
GORA_INPUT_FORMAT.setDataStore(getDataStore());
} catch (ClassNotFoundException e) {
LOG.error("Error while reading Gora Input parameters");
e.printStackTrace();
}
}
/**
* Gets the splits for a data store.
* @param context JobContext
* @param minSplitCountHint Hint for a minimum split count
* @return List<InputSplit> A list of splits
*/
@Override
public List<InputSplit> getSplits(JobContext context, int minSplitCountHint)
throws IOException, InterruptedException {
KeyFactory kFact = null;
try {
kFact = (KeyFactory) getKeyFactoryClass().newInstance();
} catch (InstantiationException e) {
LOG.error("Key factory was not instantiated. Please verify.");
LOG.error(e.getMessage());
e.printStackTrace();
} catch (IllegalAccessException e) {
LOG.error("Key factory was not instantiated. Please verify.");
LOG.error(e.getMessage());
e.printStackTrace();
}
String sKey = GIRAPH_GORA_START_KEY.get(getConf());
String eKey = GIRAPH_GORA_END_KEY.get(getConf());
if (sKey == null || sKey.isEmpty()) {
LOG.warn("No start key has been defined.");
LOG.warn("Querying all the data store.");
sKey = null;
eKey = null;
}
kFact.setDataStore(getDataStore());
setStartKey(kFact.buildKey(sKey));
setEndKey(kFact.buildKey(eKey));
Query tmpQuery = GoraUtils.getQuery(
getDataStore(), getStartKey(), getEndKey());
GORA_INPUT_FORMAT.setQuery(tmpQuery);
List<InputSplit> splits = GORA_INPUT_FORMAT.getSplits(context);
return splits;
}
@Override
public abstract GoraEdgeReader createEdgeReader(InputSplit split,
TaskAttemptContext context) throws IOException;
/**
* Abstract class to be implemented by the user based on their specific
* vertex input. Easiest to ignore the key value separator and only use
* key instead.
*/
protected abstract class GoraEdgeReader extends EdgeReader<I, E> {
/** current edge obtained from Rexster */
private Edge<I, E> edge;
/** Results gotten from Gora data store. */
private Result readResults;
@Override
public void initialize(InputSplit inputSplit, TaskAttemptContext context)
throws IOException, InterruptedException {
getResults();
RECORD_COUNTER = 0;
}
/**
* Gets the next edge from Gora data store.
* @return true/false depending on the existence of vertices.
* @throws IOException exceptions passed along.
* @throws InterruptedException exceptions passed along.
*/
@Override
// CHECKSTYLE: stop IllegalCatch
public boolean nextEdge() throws IOException, InterruptedException {
boolean flg = false;
try {
flg = this.getReadResults().next();
this.edge = transformEdge(this.getReadResults().get());
RECORD_COUNTER++;
} catch (Exception e) {
LOG.debug("Error transforming vertices.");
flg = false;
}
LOG.debug(RECORD_COUNTER + " were transformed.");
return flg;
}
// CHECKSTYLE: resume IllegalCatch
/**
* Gets the progress of reading results from Gora.
* @return the progress of reading results from Gora.
*/
@Override
public float getProgress() throws IOException, InterruptedException {
float progress = 0.0f;
if (getReadResults() != null) {
progress = getReadResults().getProgress();
}
return progress;
}
/**
* Gets current edge.
*
* @return The edge object represented by a Gora object
*/
@Override
public Edge<I, E> getCurrentEdge()
throws IOException, InterruptedException {
return this.edge;
}
/**
* Parser for a single Gora object
*
* @param goraObject vertex represented as a GoraObject
* @return The edge object represented by a Gora object
*/
protected abstract Edge<I, E> transformEdge(Object goraObject);
/**
* Performs a range query to a Gora data store.
*/
protected void getResults() {
setReadResults(GoraUtils.getRequest(getDataStore(),
getStartKey(), getEndKey()));
}
/**
* Finishes the reading process.
* @throws IOException.
*/
@Override
public void close() throws IOException {
}
/**
* Gets the results read.
* @return results read.
*/
Result getReadResults() {
return readResults;
}
/**
* Sets the results read.
* @param readResults results read.
*/
void setReadResults(Result readResults) {
this.readResults = readResults;
}
}
/**
* Gets the data store object initialized.
* @return DataStore created
*/
public DataStore createDataStore() {
DataStore dsCreated = null;
try {
dsCreated = GoraUtils.createSpecificDataStore(getDatastoreClass(),
getKeyClass(), getPersistentClass());
} catch (GoraException e) {
LOG.error("Error creating data store.");
e.printStackTrace();
}
return dsCreated;
}
/**
* Gets the persistent Class
* @return persistentClass used
*/
static Class<? extends Persistent> getPersistentClass() {
return PERSISTENT_CLASS;
}
/**
* Sets the persistent Class
* @param persistentClassUsed to be set
*/
static void setPersistentClass
(Class<? extends Persistent> persistentClassUsed) {
PERSISTENT_CLASS = persistentClassUsed;
}
/**
* Gets the key class used.
* @return the key class used.
*/
static Class<?> getKeyClass() {
return KEY_CLASS;
}
/**
* Sets the key class used.
* @param keyClassUsed key class used.
*/
static void setKeyClass(Class<?> keyClassUsed) {
KEY_CLASS = keyClassUsed;
}
/**
* @return Class the DATASTORE_CLASS
*/
public static Class<? extends DataStore> getDatastoreClass() {
return DATASTORE_CLASS;
}
/**
* @param dataStoreClass the dataStore class to set
*/
public static void setDatastoreClass(
Class<? extends DataStore> dataStoreClass) {
DATASTORE_CLASS = dataStoreClass;
}
/**
* Gets the start key for querying.
* @return the start key.
*/
public Object getStartKey() {
return START_KEY;
}
/**
* Gets the start key for querying.
* @param startKey start key.
*/
public static void setStartKey(Object startKey) {
START_KEY = startKey;
}
/**
* Gets the end key for querying.
* @return the end key.
*/
static Object getEndKey() {
return END_KEY;
}
/**
* Sets the end key for querying.
* @param pEndKey start key.
*/
static void setEndKey(Object pEndKey) {
END_KEY = pEndKey;
}
/**
* Gets the key factory class.
* @return the kEY_FACTORY_CLASS
*/
static Class<?> getKeyFactoryClass() {
return KEY_FACTORY_CLASS;
}
/**
* Sets the key factory class.
* @param keyFactoryClass the keyFactoryClass to set.
*/
static void setKeyFactoryClass(Class<?> keyFactoryClass) {
KEY_FACTORY_CLASS = keyFactoryClass;
}
/**
* Gets the data store.
* @return DataStore
*/
public static DataStore getDataStore() {
return DATA_STORE;
}
/**
* Sets the data store
* @param dStore the dATA_STORE to set
*/
public static void setDataStore(DataStore dStore) {
DATA_STORE = dStore;
}
/**
* Returns a logger.
* @return the log for the output format.
*/
public static Logger getLogger() {
return LOG;
}
}
| apache-2.0 |
mkambol/pentaho-hadoop-shims | common-fragment-V1/src/main/java/com/pentaho/big/data/bundles/impl/shim/hbase/meta/HBaseValueMetaInterfaceImpl.java | 5090 | /*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2019 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package com.pentaho.big.data.bundles.impl.shim.hbase.meta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.hadoop.shim.api.hbase.meta.HBaseValueMetaInterface;
import org.pentaho.hadoop.shim.api.internal.hbase.HBaseBytesUtilShim;
import org.pentaho.hadoop.shim.api.internal.hbase.HBaseValueMeta;
/**
* Created by bryan on 1/22/16.
*/
public class HBaseValueMetaInterfaceImpl extends HBaseValueMeta implements HBaseValueMetaInterface {
private final HBaseBytesUtilShim hBaseBytesUtilShim;
public HBaseValueMetaInterfaceImpl( String name, int type, int length, int precision,
HBaseBytesUtilShim hBaseBytesUtilShim )
throws IllegalArgumentException {
super( name, type, length, precision );
this.hBaseBytesUtilShim = hBaseBytesUtilShim;
}
@Override public Object decodeColumnValue( byte[] rawColValue ) throws KettleException {
return HBaseValueMeta.decodeColumnValue( rawColValue, this, hBaseBytesUtilShim );
}
@Override public byte[] encodeColumnValue( Object o, ValueMetaInterface valueMetaInterface ) throws KettleException {
return HBaseValueMeta.encodeColumnValue( o, valueMetaInterface, this, hBaseBytesUtilShim );
}
@Override public void getXml( StringBuilder retval ) {
retval.append( "\n " ).append( XMLHandler.openTag( "field" ) );
retval.append( "\n " ).append( XMLHandler.addTagValue( "table_name", getTableName() ) );
retval.append( "\n " ).append( XMLHandler.addTagValue( "mapping_name", getMappingName() ) );
retval.append( "\n " ).append( XMLHandler.addTagValue( "alias", getAlias() ) );
retval.append( "\n " ).append( XMLHandler.addTagValue( "family", getColumnFamily() ) );
retval.append( "\n " ).append( XMLHandler.addTagValue( "column", getColumnName() ) );
retval.append( "\n " ).append( XMLHandler.addTagValue( "key", isKey() ) );
retval.append( "\n " ).append(
XMLHandler.addTagValue( "type", ValueMeta.getTypeDesc( getType() ) ) );
String format = getConversionMask();
retval.append( "\n " ).append( XMLHandler.addTagValue( "format", format ) );
if ( getStorageType() == ValueMetaInterface.STORAGE_TYPE_INDEXED ) {
retval.append( "\n " ).append( XMLHandler.addTagValue( "index_values", getIndexValues() ) );
}
retval.append( "\n " ).append( XMLHandler.closeTag( "field" ) );
}
@Override public void saveRep( Repository rep, ObjectId id_transformation, ObjectId id_step, int i )
throws KettleException {
rep.saveStepAttribute( id_transformation, id_step, i, "table_name", getTableName() );
rep.saveStepAttribute( id_transformation, id_step, i, "mapping_name", getMappingName() );
rep.saveStepAttribute( id_transformation, id_step, i, "alias", getAlias() );
rep.saveStepAttribute( id_transformation, id_step, i, "family", getColumnFamily() );
rep.saveStepAttribute( id_transformation, id_step, i, "column", getColumnName() );
rep.saveStepAttribute( id_transformation, id_step, i, "key", isKey() );
rep.saveStepAttribute( id_transformation, id_step, i, "type", ValueMeta.getTypeDesc( getType() ) );
String format = getConversionMask();
rep.saveStepAttribute( id_transformation, id_step, i, "format", format );
if ( getStorageType() == ValueMetaInterface.STORAGE_TYPE_INDEXED ) {
rep.saveStepAttribute( id_transformation, id_step, i, "index_values", getIndexValues() );
}
}
private String getIndexValues() {
Object[] labels = getIndex();
StringBuffer vals = new StringBuffer();
vals.append( "{" );
for ( int i = 0; i < labels.length; i++ ) {
if ( i != labels.length - 1 ) {
vals.append( labels[ i ].toString().trim() ).append( "," );
} else {
vals.append( labels[ i ].toString().trim() ).append( "}" );
}
}
return vals.toString();
}
}
| apache-2.0 |
myoneray/Spring-Examples | ng-spring-chat/src/main/java/com/javachen/model/Message.java | 456 | package com.javachen.model;
public class Message {
private String message;
private int id;
public Message() {
}
public Message(int id, String message) {
this.id = id;
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| apache-2.0 |
michalklempa/nifi | nifi-commons/nifi-record/src/main/java/org/apache/nifi/serialization/record/MapRecord.java | 13878 | /*
* 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.serialization.record;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import org.apache.nifi.serialization.SchemaValidationException;
import org.apache.nifi.serialization.record.type.ArrayDataType;
import org.apache.nifi.serialization.record.type.MapDataType;
import org.apache.nifi.serialization.record.util.DataTypeUtils;
import org.apache.nifi.serialization.record.util.IllegalTypeConversionException;
public class MapRecord implements Record {
private RecordSchema schema;
private final Map<String, Object> values;
private Optional<SerializedForm> serializedForm;
private final boolean checkTypes;
private final boolean dropUnknownFields;
public MapRecord(final RecordSchema schema, final Map<String, Object> values) {
this(schema, values, false, false);
}
public MapRecord(final RecordSchema schema, final Map<String, Object> values, final boolean checkTypes, final boolean dropUnknownFields) {
Objects.requireNonNull(values);
this.schema = Objects.requireNonNull(schema);
this.values = checkTypes ? checkTypes(values, schema) : values;
this.serializedForm = Optional.empty();
this.checkTypes = checkTypes;
this.dropUnknownFields = dropUnknownFields;
}
public MapRecord(final RecordSchema schema, final Map<String, Object> values, final SerializedForm serializedForm) {
this(schema, values, serializedForm, false, false);
}
public MapRecord(final RecordSchema schema, final Map<String, Object> values, final SerializedForm serializedForm, final boolean checkTypes, final boolean dropUnknownFields) {
Objects.requireNonNull(values);
this.schema = Objects.requireNonNull(schema);
this.values = checkTypes ? checkTypes(values, schema) : values;
this.serializedForm = Optional.ofNullable(serializedForm);
this.checkTypes = checkTypes;
this.dropUnknownFields = dropUnknownFields;
}
private Map<String, Object> checkTypes(final Map<String, Object> values, final RecordSchema schema) {
for (final RecordField field : schema.getFields()) {
final Object value = getExplicitValue(field, values);
if (value == null) {
if (field.isNullable()) {
continue;
}
throw new SchemaValidationException("Field " + field.getFieldName() + " cannot be null");
}
if (!DataTypeUtils.isCompatibleDataType(value, field.getDataType())) {
throw new SchemaValidationException("Field " + field.getFieldName() + " has a value of " + value
+ ", which cannot be coerced into the appropriate data type of " + field.getDataType());
}
}
return values;
}
@Override
public boolean isDropUnknownFields() {
return dropUnknownFields;
}
@Override
public boolean isTypeChecked() {
return checkTypes;
}
@Override
public RecordSchema getSchema() {
return schema;
}
@Override
public Object[] getValues() {
final Object[] values = new Object[schema.getFieldCount()];
int i = 0;
for (final RecordField recordField : schema.getFields()) {
values[i++] = getValue(recordField);
}
return values;
}
@Override
public Object getValue(final String fieldName) {
final Optional<RecordField> fieldOption = schema.getField(fieldName);
if (fieldOption.isPresent()) {
return getValue(fieldOption.get());
}
if (dropUnknownFields) {
return null;
}
return this.values.get(fieldName);
}
@Override
public Object getValue(final RecordField field) {
Object explicitValue = getExplicitValue(field);
if (explicitValue != null) {
return explicitValue;
}
final Optional<RecordField> resolvedField = resolveField(field);
final boolean resolvedFieldDifferent = resolvedField.isPresent() && !resolvedField.get().equals(field);
if (resolvedFieldDifferent) {
explicitValue = getExplicitValue(resolvedField.get());
if (explicitValue != null) {
return explicitValue;
}
}
Object defaultValue = field.getDefaultValue();
if (defaultValue != null) {
return defaultValue;
}
if (resolvedFieldDifferent) {
return resolvedField.get().getDefaultValue();
}
return null;
}
private Optional<RecordField> resolveField(final RecordField field) {
Optional<RecordField> resolved = schema.getField(field.getFieldName());
if (resolved.isPresent()) {
return resolved;
}
for (final String alias : field.getAliases()) {
resolved = schema.getField(alias);
if (resolved.isPresent()) {
return resolved;
}
}
return Optional.empty();
}
private Object getExplicitValue(final RecordField field) {
return getExplicitValue(field, this.values);
}
private Object getExplicitValue(final RecordField field, final Map<String, Object> values) {
final String canonicalFieldName = field.getFieldName();
// We use containsKey here instead of just calling get() and checking for a null value
// because if the true field name is set to null, we want to return null, rather than
// what the alias points to. Likewise for a specific alias, since aliases are defined
// in a List with a specific ordering.
Object value = values.get(canonicalFieldName);
if (value != null) {
return value;
}
for (final String alias : field.getAliases()) {
value = values.get(alias);
if (value != null) {
return value;
}
}
return null;
}
@Override
public String getAsString(final String fieldName) {
final Optional<DataType> dataTypeOption = schema.getDataType(fieldName);
if (dataTypeOption.isPresent()) {
return convertToString(getValue(fieldName), dataTypeOption.get().getFormat());
}
return DataTypeUtils.toString(getValue(fieldName), (Supplier<DateFormat>) null);
}
@Override
public String getAsString(final String fieldName, final String format) {
return convertToString(getValue(fieldName), format);
}
@Override
public String getAsString(final RecordField field, final String format) {
return convertToString(getValue(field), format);
}
private String convertToString(final Object value, final String format) {
if (value == null) {
return null;
}
return DataTypeUtils.toString(value, format);
}
@Override
public Long getAsLong(final String fieldName) {
return DataTypeUtils.toLong(getValue(fieldName), fieldName);
}
@Override
public Integer getAsInt(final String fieldName) {
return DataTypeUtils.toInteger(getValue(fieldName), fieldName);
}
@Override
public Double getAsDouble(final String fieldName) {
return DataTypeUtils.toDouble(getValue(fieldName), fieldName);
}
@Override
public Float getAsFloat(final String fieldName) {
return DataTypeUtils.toFloat(getValue(fieldName), fieldName);
}
@Override
public Record getAsRecord(String fieldName, final RecordSchema schema) {
return DataTypeUtils.toRecord(getValue(fieldName), schema, fieldName);
}
@Override
public Boolean getAsBoolean(final String fieldName) {
return DataTypeUtils.toBoolean(getValue(fieldName), fieldName);
}
@Override
public Date getAsDate(final String fieldName, final String format) {
return DataTypeUtils.toDate(getValue(fieldName), () -> DataTypeUtils.getDateFormat(format), fieldName);
}
@Override
public Object[] getAsArray(final String fieldName) {
return DataTypeUtils.toArray(getValue(fieldName), fieldName);
}
@Override
public int hashCode() {
return 31 + 41 * values.hashCode() + 7 * schema.hashCode();
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MapRecord)) {
return false;
}
final MapRecord other = (MapRecord) obj;
return schema.equals(other.schema) && values.equals(other.values);
}
@Override
public String toString() {
return "MapRecord[" + values + "]";
}
@Override
public Optional<SerializedForm> getSerializedForm() {
return serializedForm;
}
@Override
public void setValue(final String fieldName, final Object value) {
final Optional<RecordField> field = getSchema().getField(fieldName);
if (!field.isPresent()) {
if (dropUnknownFields) {
return;
}
final Object previousValue = values.put(fieldName, value);
if (!Objects.equals(value, previousValue)) {
serializedForm = Optional.empty();
}
return;
}
final RecordField recordField = field.get();
final Object coerced = isTypeChecked() ? DataTypeUtils.convertType(value, recordField.getDataType(), fieldName) : value;
final Object previousValue = values.put(recordField.getFieldName(), coerced);
if (!Objects.equals(coerced, previousValue)) {
serializedForm = Optional.empty();
}
}
@Override
public void setArrayValue(final String fieldName, final int arrayIndex, final Object value) {
final Optional<RecordField> field = getSchema().getField(fieldName);
if (!field.isPresent()) {
return;
}
final RecordField recordField = field.get();
final DataType dataType = recordField.getDataType();
if (dataType.getFieldType() != RecordFieldType.ARRAY) {
throw new IllegalTypeConversionException("Cannot set the value of an array index on Record because the field '" + fieldName
+ "' is of type '" + dataType + "' and cannot be coerced into an ARRAY type");
}
final Object arrayObject = values.get(recordField.getFieldName());
if (arrayObject == null) {
return;
}
if (!(arrayObject instanceof Object[])) {
return;
}
final Object[] array = (Object[]) arrayObject;
if (arrayIndex >= array.length) {
return;
}
final ArrayDataType arrayDataType = (ArrayDataType) dataType;
final DataType elementType = arrayDataType.getElementType();
final Object coerced = DataTypeUtils.convertType(value, elementType, fieldName);
final boolean update = !Objects.equals(coerced, array[arrayIndex]);
if (update) {
array[arrayIndex] = coerced;
serializedForm = Optional.empty();
}
}
@Override
@SuppressWarnings("unchecked")
public void setMapValue(final String fieldName, final String mapKey, final Object value) {
final Optional<RecordField> field = getSchema().getField(fieldName);
if (!field.isPresent()) {
return;
}
final RecordField recordField = field.get();
final DataType dataType = recordField.getDataType();
if (dataType.getFieldType() != RecordFieldType.MAP) {
throw new IllegalTypeConversionException("Cannot set the value of map entry on Record because the field '" + fieldName
+ "' is of type '" + dataType + "' and cannot be coerced into an MAP type");
}
Object mapObject = values.get(recordField.getFieldName());
if (mapObject == null) {
mapObject = new HashMap<String, Object>();
}
if (!(mapObject instanceof Map)) {
return;
}
final Map<String, Object> map = (Map<String, Object>) mapObject;
final MapDataType mapDataType = (MapDataType) dataType;
final DataType valueDataType = mapDataType.getValueType();
final Object coerced = DataTypeUtils.convertType(value, valueDataType, fieldName);
final Object replaced = map.put(mapKey, coerced);
if (replaced == null || !replaced.equals(coerced)) {
serializedForm = Optional.empty();
}
}
@Override
public void incorporateSchema(RecordSchema other) {
this.schema = DataTypeUtils.merge(this.schema, other);
}
@Override
public Set<String> getRawFieldNames() {
return values.keySet();
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-videointelligence/v1p1beta1/1.28.0/com/google/api/services/videointelligence/v1p1beta1/model/GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative.java | 5154 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.videointelligence.v1p1beta1.model;
/**
* Alternative hypotheses (a.k.a. n-best list).
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Video Intelligence API. For a detailed
* explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative extends com.google.api.client.json.GenericJson {
/**
* The confidence estimate between 0.0 and 1.0. A higher number indicates an estimated greater
* likelihood that the recognized words are correct. This field is typically provided only for the
* top hypothesis, and only for `is_final=true` results. Clients should not rely on the
* `confidence` field as it is not guaranteed to be accurate or consistent. The default of 0.0 is
* a sentinel value indicating `confidence` was not set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float confidence;
/**
* Transcript text representing the words that the user spoke.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String transcript;
/**
* A list of word-specific information for each recognized word.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudVideointelligenceV1p1beta1WordInfo> words;
/**
* The confidence estimate between 0.0 and 1.0. A higher number indicates an estimated greater
* likelihood that the recognized words are correct. This field is typically provided only for the
* top hypothesis, and only for `is_final=true` results. Clients should not rely on the
* `confidence` field as it is not guaranteed to be accurate or consistent. The default of 0.0 is
* a sentinel value indicating `confidence` was not set.
* @return value or {@code null} for none
*/
public java.lang.Float getConfidence() {
return confidence;
}
/**
* The confidence estimate between 0.0 and 1.0. A higher number indicates an estimated greater
* likelihood that the recognized words are correct. This field is typically provided only for the
* top hypothesis, and only for `is_final=true` results. Clients should not rely on the
* `confidence` field as it is not guaranteed to be accurate or consistent. The default of 0.0 is
* a sentinel value indicating `confidence` was not set.
* @param confidence confidence or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative setConfidence(java.lang.Float confidence) {
this.confidence = confidence;
return this;
}
/**
* Transcript text representing the words that the user spoke.
* @return value or {@code null} for none
*/
public java.lang.String getTranscript() {
return transcript;
}
/**
* Transcript text representing the words that the user spoke.
* @param transcript transcript or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative setTranscript(java.lang.String transcript) {
this.transcript = transcript;
return this;
}
/**
* A list of word-specific information for each recognized word.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudVideointelligenceV1p1beta1WordInfo> getWords() {
return words;
}
/**
* A list of word-specific information for each recognized word.
* @param words words or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative setWords(java.util.List<GoogleCloudVideointelligenceV1p1beta1WordInfo> words) {
this.words = words;
return this;
}
@Override
public GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative set(String fieldName, Object value) {
return (GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative) super.set(fieldName, value);
}
@Override
public GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative clone() {
return (GoogleCloudVideointelligenceV1p1beta1SpeechRecognitionAlternative) super.clone();
}
}
| apache-2.0 |
binfalse/incubator-taverna-language | taverna-scufl2-api/src/test/java/org/apache/taverna/scufl2/validation/correctness/TestConfiguration.java | 5869 | /**
*
*/
package org.apache.taverna.scufl2.validation.correctness;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;
import org.apache.taverna.scufl2.api.activity.Activity;
import org.apache.taverna.scufl2.api.configurations.Configuration;
import org.apache.taverna.scufl2.validation.correctness.CorrectnessValidator;
import org.apache.taverna.scufl2.validation.correctness.ReportCorrectnessValidationListener;
import org.apache.taverna.scufl2.validation.correctness.report.MismatchConfigurableTypeProblem;
import org.apache.taverna.scufl2.validation.correctness.report.NullFieldProblem;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author alanrw
*
*/
public class TestConfiguration {
@Test
public void testIdenticalConfigurableTypes() {
Configuration configuration = new Configuration();
Activity a = new Activity();
URI tavernaUri = null;
try {
tavernaUri = new URI("http://www.taverna.org.uk");
} catch (URISyntaxException e) {
return;
}
configuration.setConfigures(a);
configuration.setType(tavernaUri);
a.setType(tavernaUri);
CorrectnessValidator cv = new CorrectnessValidator();
ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();
cv.checkCorrectness(configuration, false, rcvl);
Set<MismatchConfigurableTypeProblem> mismatchConfigurableTypeProblems = rcvl.getMismatchConfigurableTypeProblems();
assertEquals(0, mismatchConfigurableTypeProblems.size());
}
@Ignore
public void testEqualConfigurableTypes() {
Configuration configuration = new Configuration();
Activity a = new Activity();
URI tavernaUri = null;
URI tavernaUri2 = null;
try {
tavernaUri = new URI("http://www.taverna.org.uk");
tavernaUri2 = new URI("http://www.taverna.org.uk");
} catch (URISyntaxException e) {
return;
}
configuration.setConfigures(a);
configuration.setType(tavernaUri);
a.setType(tavernaUri2);
CorrectnessValidator cv = new CorrectnessValidator();
ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();
cv.checkCorrectness(configuration, false, rcvl);
Set<MismatchConfigurableTypeProblem> mismatchConfigurableTypeProblems = rcvl.getMismatchConfigurableTypeProblems();
assertEquals(0, mismatchConfigurableTypeProblems.size());
}
@Ignore
public void testMismatchingConfigurableTypes() {
Configuration configuration = new Configuration();
Activity a = new Activity();
URI tavernaUri = null;
URI myGridUri = null;
try {
tavernaUri = new URI("http://www.taverna.org.uk");
myGridUri = new URI("http://www.mygrid.org.uk");
} catch (URISyntaxException e) {
return;
}
configuration.setConfigures(a);
configuration.setType(tavernaUri);
a.setType(myGridUri);
CorrectnessValidator cv = new CorrectnessValidator();
ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();
cv.checkCorrectness(configuration, false, rcvl);
Set<MismatchConfigurableTypeProblem> mismatchConfigurableTypeProblems = rcvl.getMismatchConfigurableTypeProblems();
assertEquals(1, mismatchConfigurableTypeProblems.size());
boolean mismatchProblem = false;
for (MismatchConfigurableTypeProblem nlp : mismatchConfigurableTypeProblems) {
if (nlp.getBean().equals(configuration) && nlp.getConfigurable().equals(a)) {
mismatchProblem = true;
}
}
assertTrue(mismatchProblem);
}
@Test
public void testCorrectnessOfMissingConfigures() {
Configuration configuration = new Configuration();
configuration.setType(URI.create("http://www.example.com/"));
configuration.setJson("{ \"hello\": 1337 }");
CorrectnessValidator cv = new CorrectnessValidator();
ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();
cv.checkCorrectness(configuration, false, rcvl);
Set<NullFieldProblem> nullFieldProblems = rcvl.getNullFieldProblems();
assertEquals(0, nullFieldProblems.size()); // only done when completeness check
}
@Test
public void testCompletenessOfMissingConfigures() {
Configuration configuration = new Configuration();
configuration.setType(URI.create("http://www.example.com/"));
configuration.setJson("{ \"hello\": 1337 }");
CorrectnessValidator cv = new CorrectnessValidator();
ReportCorrectnessValidationListener rcvl = new ReportCorrectnessValidationListener();
cv.checkCorrectness(configuration, true, rcvl);
Set<NullFieldProblem> nullFieldProblems = rcvl.getNullFieldProblems();
assertFalse(nullFieldProblems.isEmpty()); // only done when completeness check
boolean fieldProblem = false;
for (NullFieldProblem nlp : nullFieldProblems) {
if (nlp.getBean().equals(configuration) && nlp.getFieldName().equals("configures")) {
fieldProblem = true;
}
}
assertTrue(fieldProblem);
}
// Cannot check propertyResource because of SCUFL2-97
}
| apache-2.0 |
itsallvoodoo/csci-school | CSCI362/schfiftyFive_TESTING/project/org/openremote/controller/protocol/knx/ApplicationProtocolDataUnit.java | 22824 | /*
* OpenRemote, the Home of the Digital Home.
* Copyright 2008-2010, OpenRemote Inc.
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* 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.openremote.controller.protocol.knx;
import org.apache.log4j.Logger;
import org.openremote.controller.utils.Strings;
import org.openremote.controller.protocol.knx.datatype.DataPointType;
import org.openremote.controller.protocol.knx.datatype.DataType;
import org.openremote.controller.protocol.knx.datatype.Bool;
import org.openremote.controller.protocol.knx.datatype.Controlled3Bit;
import org.openremote.controller.protocol.knx.datatype.Unsigned8Bit;
import org.openremote.controller.exception.ConversionException;
import org.openremote.controller.command.CommandParameter;
import java.util.ArrayList;
import java.util.List;
/**
* This class represents application protocol data unit (APDU) in KNX specification. <p>
*
* APDU is defined in KNX 1.1 Volume 3: System Specifications, Part 3 Communication,
* Chapter 7, Application Layer. <p>
*
* In the Common EMI frame, the APDU payload is defined as follows:
*
* <pre>{@code
*
* +--------+--------+--------+--------+--------+
* | TPCI + | APCI + | Data | Data | Data |
* | APCI | Data | | | |
* +--------+--------+--------+--------+--------+
* byte 1 byte 2 byte 3 ... byte 16
*
*}</pre>
*
* For data that is 6 bits or less in length, only the first two bytes are used in a Common EMI
* frame. Common EMI frame also carries the information of the expected length of the Protocol
* Data Unit (PDU). Data payload can be at most 14 bytes long. <p>
*
* The first byte is a combination of transport layer control information (TPCI) and application
* layer control information (APCI). First 6 bits are dedicated for TPCI while the two least
* significant bits of first byte hold the two most significant bits of APCI field, as follows:
*
* <pre>{@code
*
* Bit 1 Bit 2 Bit 3 Bit 4 Bit 5 Bit 6 Bit 7 Bit 8 Bit 1 Bit 2
* +--------+--------+--------+--------+--------+--------+--------+--------++--------+----....
* | | | | | | | | || |
* | TPCI | TPCI | TPCI | TPCI | TPCI | TPCI | APCI | APCI || APCI |
* | | | | | | |(bit 1) |(bit 2) ||(bit 3) |
* +--------+--------+--------+--------+--------+--------+--------+--------++--------+----....
* + B Y T E 1 || B Y T E 2
* +-----------------------------------------------------------------------++-------------....
*
* }</pre>
*
* Total number of APCI control bits can be either 4 or 10, depending on which
* {@link org.openremote.controller.protocol.knx.ApplicationLayer.Service
* application layer service} is being used. The second byte bit structure is as follows:
*
* <pre>{@code
*
* Bit 1 Bit 2 Bit 3 Bit 4 Bit 5 Bit 6 Bit 7 Bit 8 Bit 1 Bit 2
* +--------+--------+--------+--------+--------+--------+--------+--------++--------+----....
* | | | | | | | | || |
* | APCI | APCI | APCI/ | APCI/ | APCI/ | APCI/ | APCI/ | APCI/ || Data | Data
* |(bit 3) |(bit 4) | Data | Data | Data | Data | Data | Data || |
* +--------+--------+--------+--------+--------+--------+--------+--------++--------+----....
* + B Y T E 2 || B Y T E 3
* +-----------------------------------------------------------------------++-------------....
*
* }</pre>
*
* @see DataType
*
* @author <a href="mailto:juha@openremote.org">Juha Lindfors</a>
*/
class ApplicationProtocolDataUnit
{
// Constants ------------------------------------------------------------------------------------
/**
* Represents the full APDU (APCI + data) for Group Value Write service request with DPT 1.001
* (Switch) to state 'ON'.
*
* @see org.openremote.controller.protocol.knx.ApplicationLayer.Service#GROUPVALUE_WRITE_6BIT
* @see org.openremote.controller.protocol.knx.datatype.Bool#ON
*/
final static ApplicationProtocolDataUnit WRITE_SWITCH_ON = new ApplicationProtocolDataUnit
(
ApplicationLayer.Service.GROUPVALUE_WRITE_6BIT,
Bool.ON
);
/**
* Represents the full APDU (APCI + data) for Group Value Write service request with
* DPT 1.001 (Switch) to state 'OFF'.
*
* @see ApplicationLayer.Service#GROUPVALUE_WRITE_6BIT
* @see org.openremote.controller.protocol.knx.datatype.Bool#OFF
*/
final static ApplicationProtocolDataUnit WRITE_SWITCH_OFF = new ApplicationProtocolDataUnit
(
ApplicationLayer.Service.GROUPVALUE_WRITE_6BIT,
Bool.OFF
);
/**
* Represents the full APDU (APCI bits) for Group Value Read request for data points with
* DPT 1.001 (Switch) type.
*
* @see ApplicationLayer.Service#GROUPVALUE_READ
* @see org.openremote.controller.protocol.knx.datatype.Bool#READ_SWITCH
*/
final static ApplicationProtocolDataUnit READ_SWITCH_STATE = new ApplicationProtocolDataUnit
(
ApplicationLayer.Service.GROUPVALUE_READ,
Bool.READ_SWITCH
);
// Class Members --------------------------------------------------------------------------------
/**
* KNX logger. Uses a common category for all KNX related logging.
*/
private final static Logger log = Logger.getLogger(KNXCommandBuilder.KNX_LOG_CATEGORY);
/**
* Determines from the Application Protocol Control Information (APCI) bits in an application
* protocol data unit (APDU) bytes whether the application level service corresponds to Group
* Value Response service.
*
* @see org.openremote.controller.protocol.knx.ApplicationLayer.Service#GROUPVALUE_RESPONSE_6BIT
*
* @param apdu Byte array containing the application protocol data unit payload. Only the first
* two bytes are inspected. This parameter can therefore contain only a partial
* APDU with only the first two bytes of APCI information or the entire APDU with
* data included.
*
* @return true if the APDU corresponds to Group Value Response service; false otherwise
*/
static boolean isGroupValueResponse(byte[] apdu)
{
// Expected bit structure :
//
// Byte 1 : bits xxxxxx00 - first six bits are part of TPCI
// Byte 2 : bits 01xxxxxx - last six bits are either data (6 bit return values)
// or zero for larger than 6 bit return values
return ((apdu[0] & 0x3) == 0x00 && (apdu[1] & 0xC0) == 0x40);
}
/**
* Constructs an APDU corresponding to a Group Value Write service for a device expecting
* a 3-bit dim control data point type (DPT 3.007). <p>
*
* The control bit value must correspond to DPT 1.007, 1.008 or 1.014
* ({@link org.openremote.controller.protocol.knx.datatype.Bool#INCREASE}/
* {@link org.openremote.controller.protocol.knx.datatype.Bool#DECREASE},
* {@link org.openremote.controller.protocol.knx.datatype.Bool#UP}/
* {@link org.openremote.controller.protocol.knx.datatype.Bool#DOWN},
* {@link org.openremote.controller.protocol.knx.datatype.Bool#FIXED}/
* {@link org.openremote.controller.protocol.knx.datatype.Bool#CALCULATED}, respectively). <p>
*
* The dim value must be a 3-bit value in the range of [0-7].
*
* @see org.openremote.controller.protocol.knx.datatype.DataPointType.Control3BitDataPointType#CONTROL_DIMMING
* @see org.openremote.controller.protocol.knx.datatype.Controlled3Bit
*
* @param controlValue must be one of DataType.Boolean.INCREASE, DataType.Boolean.DECREASE,
* DataType.Boolean.UP, DataType.Boolean.DOWN, DataType.Boolean.FIXED
* or DataType.Boolean.CALCULATED
*
* @param dimValue must be in range of [0-7]
*
* @return APDU instance for a 3-bit dim control Group Value Write service with a given control
* bit and range bits
*/
static ApplicationProtocolDataUnit create3BitDimControl(Bool controlValue,
int dimValue)
{
return new ApplicationProtocolDataUnit(
ApplicationLayer.Service.GROUPVALUE_WRITE_6BIT,
new Controlled3Bit(
DataPointType.Control3BitDataPointType.CONTROL_DIMMING,
controlValue,
dimValue)
);
}
/**
* Constructs an APDU corresponding to a Group Value Write service for a device expecting
* an 8-bit unsigned scaling value (DPT 5.001). <p>
*
* Valid parameter value range is [0-100]. This is interpreted as a percentage value.
*
* @param parameter scaling value for percentage range
*
* @return APDU instance for a 8-bit unsigned scaling value
*
* @throws ConversionException if the value is not in a given range or cannot be scaled to the
* desired range
*/
static ApplicationProtocolDataUnit createScaling(CommandParameter parameter)
throws ConversionException
{
int value = parameter.getValue();
if (value < 0 || value > 100)
{
throw new ConversionException(
"Expected value is in range [0-100] (percentage), received " + value
);
}
// scale it up to [0-255] range of the unsigned byte that is sent on the wire...
value = (int)Math.round(value * 2.55);
return new ApplicationProtocolDataUnit(
ApplicationLayer.Service.GROUPVALUE_WRITE,
new Unsigned8Bit(
DataPointType.Unsigned8BitValue.SCALING,
value)
);
}
// Private Instance Fields ----------------------------------------------------------------------
/**
* Datatype associated with this APDU.
*
* @see DataType
*/
private DataType datatype;
/**
* Application Layer Service associated with this APDU.
*
* @see ApplicationLayer
*/
private ApplicationLayer.Service applicationLayerService;
// Constructors ---------------------------------------------------------------------------------
/**
* Constructs a new APDU with a given application layer service and datatype.
*
* @see org.openremote.controller.protocol.knx.ApplicationLayer.Service
* @see DataType
*
* @param service application layer service as defined in
* {@link org.openremote.controller.protocol.knx.ApplicationLayer.Service}
* @param datatype KNX data type
*/
private ApplicationProtocolDataUnit(ApplicationLayer.Service service, DataType datatype)
{
this.applicationLayerService = service;
this.datatype = datatype;
}
// Object Overrides -----------------------------------------------------------------------------
/**
* Returns a string representation of this APDU including the TPCI & APCI bits and data payload.
*
* @return application layer service name associated with this APDU and the contents of this
* APDU as unsigned hex values.
*/
@Override public String toString()
{
StringBuffer buffer = new StringBuffer(256);
buffer.append(applicationLayerService.name());
buffer.append(" ");
Byte[] pdu = getProtocolDataUnit();
for (byte b : pdu)
{
buffer.append(Strings.byteToUnsignedHexString(b));
buffer.append(" ");
}
return buffer.toString().trim();
}
// Package-Private Instance Methods ------------------------------------------------------------
/**
* Returns the actual data payload without application protocol control information (APCI) bits
* as a string value. The bytes in the payload are formatted as unsigned hex strings. An example
* output could look like:
*
* <pre>{@code
*
* 0x00 0x0F
*
* }</pre>
*
* @return APDU data payload formatted as a sequence of unsigned hex strings
*/
String dataAsString()
{
byte[] data = datatype.getData();
StringBuffer buffer = new StringBuffer(256);
for (byte b : data)
{
buffer.append(Strings.byteToUnsignedHexString(b));
buffer.append(" ");
}
return buffer.toString().trim();
}
/**
* Returns the data length of the data type associated with this APDU.
* See {@link DataType#getDataLength()} for details.
*
* @see DataType#getDataLength()
*
* @return returns the APDU data payload length in bytes, as specified in
* {@link DataType#getDataLength()}
*/
int getDataLength()
{
return datatype.getDataLength();
}
/**
* Returns the KNX datatype associated with this APDU.
*
* @see DataType
*
* @return KNX datatype
*/
DataType getDataType()
{
return datatype;
}
/**
* Returns the KNX datapoint type associated with this APDU.
*
* @see DataPointType
*
* @return KNX datapoint type
*/
DataPointType getDataPointType()
{
return datatype.getDataPointType();
}
/**
* Returns the application layer service associated with this application protocol data unit.
*
* @see ApplicationLayer.Service
*
* @return application layer service
*/
ApplicationLayer.Service getApplicationLayerService()
{
return applicationLayerService;
}
/**
* Attempts to convert the data payload of this APDU into a KNX Boolean datatype value. <p>
*
* Integer value 0 is encoded as FALSE, integer value 1 is encoded as TRUE.
*
* @see org.openremote.controller.protocol.knx.datatype.Bool#TRUE
* @see org.openremote.controller.protocol.knx.datatype.Bool#FALSE
*
* @return {@link org.openremote.controller.protocol.knx.datatype.Bool#TRUE} for value 1, {@link org.openremote.controller.protocol.knx.datatype.Bool#FALSE} for value 0.
*
* @throws ConversionException if the data payload cannot be converted to KNX Boolean type.
*/
Bool convertToBooleanDataType() throws ConversionException
{
byte[] data = datatype.getData();
if (data.length == 1)
{
if (data[0] == 1)
{
return Bool.TRUE;
}
else if (data[0] == 0)
{
return Bool.FALSE;
}
else
{
throw new ConversionException("Expected boolean value 0x0 or 0x1 but found " + data[0]);
}
}
else
{
throw new ConversionException(
"Was expecting 6-bit boolean datatype in payload but data was " +
data.length + " bytes long."
);
}
}
/**
* Returns the application protocol data unit (APDU) including the Control Information (ACPI)
* bits and data value. <p>
*
* Returned byte array is at minimum 2 bytes long (for 6-bit data values), and maximum of 16
* bytes long (with a largest possible 14 byte data value). <p>
*
* The six most significant bits of the first byte in the array are Transport Protocol Control
* Information (TCPI) bits which are all set to zero.
*
* @return full APDU as byte array with APCI bits and data value set
*/
Byte[] getProtocolDataUnit()
{
final int TRANSPORT_LAYER_CONTROL_FIELDS = 0x00;
byte[] apduData = datatype.getData();
List<Byte> pdu = new ArrayList<Byte>(20);
pdu.add((byte)(TRANSPORT_LAYER_CONTROL_FIELDS + applicationLayerService.getTPCIAPCI()));
// TODO : fix the brittle if statement with isSixBit() method on app layer service instance
if (applicationLayerService == ApplicationLayer.Service.GROUPVALUE_WRITE_6BIT ||
applicationLayerService == ApplicationLayer.Service.GROUPVALUE_RESPONSE_6BIT ||
applicationLayerService == ApplicationLayer.Service.GROUPVALUE_READ)
{
pdu.add((byte)(applicationLayerService.getAPCIData() + apduData[0]));
}
else
{
pdu.add((byte)applicationLayerService.getAPCIData());
for (byte data : apduData)
{
pdu.add(data);
}
}
Byte[] pduBytes = new Byte[pdu.size()];
return pdu.toArray(pduBytes);
}
// Nested Classes -------------------------------------------------------------------------------
/**
* TODO
*/
static class ResponseAPDU extends ApplicationProtocolDataUnit
{
/**
* TODO
*
* @param apdu
* @return
*/
static ResponseAPDU create6BitResponse(final byte[] apdu)
{
return new ResponseAPDU(
ApplicationLayer.Service.GROUPVALUE_RESPONSE_6BIT,
1 /* data length */,
new byte[] { (byte)(apdu[1] & 0x3F)}
);
}
/**
* TODO
*
* @param apdu
* @return
*/
static ResponseAPDU create8BitResponse(final byte[] apdu)
{
return new ResponseAPDU(
ApplicationLayer.Service.GROUPVALUE_RESPONSE,
2, /* Data length */
new byte[] { apdu[2] }
);
}
/**
* TODO
*
* @param apdu
* @return
*/
static ResponseAPDU createTwoByteResponse(final byte[] apdu)
{
return new ResponseAPDU(
ApplicationLayer.Service.GROUPVALUE_RESPONSE,
3, /* Data length */
new byte[] { apdu[2], apdu[3] }
);
}
/**
* TODO
*
* @param apdu
* @return
*/
static ResponseAPDU createThreeByteResponse(final byte[] apdu)
{
return new ResponseAPDU(
ApplicationLayer.Service.GROUPVALUE_RESPONSE,
4, /* Data length */
new byte[] { apdu[2], apdu[3], apdu[4] }
);
}
/**
* TODO
*
* @param apdu
* @return
*/
static ResponseAPDU createFourByteResponse(final byte[] apdu)
{
return new ResponseAPDU(
ApplicationLayer.Service.GROUPVALUE_RESPONSE,
5, /* Data length */
new byte[] { apdu[2], apdu[3], apdu[4], apdu[5] }
);
}
/**
* TODO
*
* @param apdu
* @return
*/
static ResponseAPDU createStringResponse(final byte[] apdu)
{
int len = apdu.length;
byte[] stringData = new byte[len - 2];
System.arraycopy(apdu, 2, stringData, 0, stringData.length);
return new ResponseAPDU(
ApplicationLayer.Service.GROUPVALUE_RESPONSE,
stringData.length + 1, /* Data length */
stringData
);
}
/**
* TODO
*
* @param service
* @param dataLen
* @param data
*/
private ResponseAPDU(ApplicationLayer.Service service, final int dataLen, final byte[] data)
{
super(service, new DataType()
{
public int getDataLength()
{
return dataLen;
}
public byte[] getData()
{
return data;
}
public DataPointType getDataPointType()
{
throw new Error("Response APDU must be resolved to a datapoint type first.");
}
});
}
/**
* TODO
*
* @param dpt
* @return
*/
ApplicationProtocolDataUnit resolve(DataPointType dpt)
{
if (dpt instanceof DataPointType.BooleanDataPointType)
{
DataPointType.BooleanDataPointType bool = (DataPointType.BooleanDataPointType)dpt;
return new ApplicationProtocolDataUnit(
getApplicationLayerService(),
resolveToBoolean(bool, getDataType().getData() [0])
);
}
else if (dpt instanceof DataPointType.Unsigned8BitValue)
{
DataPointType.Unsigned8BitValue value = (DataPointType.Unsigned8BitValue)dpt;
return new ApplicationProtocolDataUnit(
getApplicationLayerService(),
resolveTo8BitValue(value, getDataType().getData() [0])
);
}
else
{
throw new Error("Unrecognized datapoint type " + dpt);
}
}
/**
* TODO
*
* @param dpt
* @param value
* @return
*/
private Unsigned8Bit resolveTo8BitValue(DataPointType.Unsigned8BitValue dpt, int value)
{
return new Unsigned8Bit(dpt, value);
}
/**
* TODO
*
* @param value
* @return
*/
private Bool resolveToBoolean(DataPointType.BooleanDataPointType dpt, int value)
{
if (dpt == DataPointType.BooleanDataPointType.SWITCH)
return (value == 0) ? Bool.OFF : Bool.ON;
else if (dpt == DataPointType.BooleanDataPointType.BOOL)
return (value == 0) ? Bool.FALSE : Bool.TRUE;
else if (dpt == DataPointType.BooleanDataPointType.ENABLE)
return (value == 0) ? Bool.DISABLE : Bool.ENABLE;
else if (dpt == DataPointType.BooleanDataPointType.RAMP)
return (value == 0) ? Bool.NO_RAMP : Bool.RAMP;
else if (dpt == DataPointType.BooleanDataPointType.ALARM)
return (value == 0) ? Bool.NO_ALARM : Bool.ALARM;
else if (dpt == DataPointType.BooleanDataPointType.BINARY_VALUE)
return (value == 0) ? Bool.LOW : Bool.HIGH;
else if (dpt == DataPointType.BooleanDataPointType.STEP)
return (value == 0) ? Bool.DECREASE : Bool.INCREASE;
else if (dpt == DataPointType.BooleanDataPointType.UP_DOWN)
return (value == 0) ? Bool.UP : Bool.DOWN;
else if (dpt == DataPointType.BooleanDataPointType.OPEN_CLOSE)
return (value == 0) ? Bool.OPEN : Bool.CLOSE;
else if (dpt == DataPointType.BooleanDataPointType.START)
return (value == 0) ? Bool.STOP : Bool.START;
else if (dpt == DataPointType.BooleanDataPointType.STATE)
return (value == 0) ? Bool.INACTIVE : Bool.ACTIVE;
else if (dpt == DataPointType.BooleanDataPointType.INVERT)
return (value == 0) ? Bool.NOT_INVERTED : Bool.INVERTED;
else if (dpt == DataPointType.BooleanDataPointType.DIM_SEND_STYLE)
return (value == 0) ? Bool.START_STOP : Bool.CYCLICALLY;
else if (dpt == DataPointType.BooleanDataPointType.INPUT_SOURCE)
return (value == 0) ? Bool.FIXED : Bool.CALCULATED;
else
{
throw new Error("Unrecognized datapoint type : " + dpt);
}
}
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-compute/v1/1.31.0/com/google/api/services/compute/model/SSLHealthCheck.java | 8278 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Model definition for SSLHealthCheck.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class SSLHealthCheck extends com.google.api.client.json.GenericJson {
/**
* The TCP port number for the health check request. The default value is 443. Valid values are 1
* through 65535.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer port;
/**
* Port name as defined in InstanceGroup#NamedPort#name. If both port and port_name are defined,
* port takes precedence.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String portName;
/**
* Specifies how port is selected for health checking, can be one of following values:
* USE_FIXED_PORT: The port number in port is used for health checking. USE_NAMED_PORT: The
* portName is used for health checking. USE_SERVING_PORT: For NetworkEndpointGroup, the port
* specified for each network endpoint is used for health checking. For other backends, the port
* or named port specified in the Backend Service is used for health checking. If not specified,
* SSL health check follows behavior specified in port and portName fields.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String portSpecification;
/**
* Specifies the type of proxy header to append before sending data to the backend, either NONE or
* PROXY_V1. The default is NONE.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String proxyHeader;
/**
* The application data to send once the SSL connection has been established (default value is
* empty). If both request and response are empty, the connection establishment alone will
* indicate health. The request data can only be ASCII.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String request;
/**
* The bytes to match against the beginning of the response data. If left empty (the default
* value), any response will indicate health. The response data can only be ASCII.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String response;
/**
* The TCP port number for the health check request. The default value is 443. Valid values are 1
* through 65535.
* @return value or {@code null} for none
*/
public java.lang.Integer getPort() {
return port;
}
/**
* The TCP port number for the health check request. The default value is 443. Valid values are 1
* through 65535.
* @param port port or {@code null} for none
*/
public SSLHealthCheck setPort(java.lang.Integer port) {
this.port = port;
return this;
}
/**
* Port name as defined in InstanceGroup#NamedPort#name. If both port and port_name are defined,
* port takes precedence.
* @return value or {@code null} for none
*/
public java.lang.String getPortName() {
return portName;
}
/**
* Port name as defined in InstanceGroup#NamedPort#name. If both port and port_name are defined,
* port takes precedence.
* @param portName portName or {@code null} for none
*/
public SSLHealthCheck setPortName(java.lang.String portName) {
this.portName = portName;
return this;
}
/**
* Specifies how port is selected for health checking, can be one of following values:
* USE_FIXED_PORT: The port number in port is used for health checking. USE_NAMED_PORT: The
* portName is used for health checking. USE_SERVING_PORT: For NetworkEndpointGroup, the port
* specified for each network endpoint is used for health checking. For other backends, the port
* or named port specified in the Backend Service is used for health checking. If not specified,
* SSL health check follows behavior specified in port and portName fields.
* @return value or {@code null} for none
*/
public java.lang.String getPortSpecification() {
return portSpecification;
}
/**
* Specifies how port is selected for health checking, can be one of following values:
* USE_FIXED_PORT: The port number in port is used for health checking. USE_NAMED_PORT: The
* portName is used for health checking. USE_SERVING_PORT: For NetworkEndpointGroup, the port
* specified for each network endpoint is used for health checking. For other backends, the port
* or named port specified in the Backend Service is used for health checking. If not specified,
* SSL health check follows behavior specified in port and portName fields.
* @param portSpecification portSpecification or {@code null} for none
*/
public SSLHealthCheck setPortSpecification(java.lang.String portSpecification) {
this.portSpecification = portSpecification;
return this;
}
/**
* Specifies the type of proxy header to append before sending data to the backend, either NONE or
* PROXY_V1. The default is NONE.
* @return value or {@code null} for none
*/
public java.lang.String getProxyHeader() {
return proxyHeader;
}
/**
* Specifies the type of proxy header to append before sending data to the backend, either NONE or
* PROXY_V1. The default is NONE.
* @param proxyHeader proxyHeader or {@code null} for none
*/
public SSLHealthCheck setProxyHeader(java.lang.String proxyHeader) {
this.proxyHeader = proxyHeader;
return this;
}
/**
* The application data to send once the SSL connection has been established (default value is
* empty). If both request and response are empty, the connection establishment alone will
* indicate health. The request data can only be ASCII.
* @return value or {@code null} for none
*/
public java.lang.String getRequest() {
return request;
}
/**
* The application data to send once the SSL connection has been established (default value is
* empty). If both request and response are empty, the connection establishment alone will
* indicate health. The request data can only be ASCII.
* @param request request or {@code null} for none
*/
public SSLHealthCheck setRequest(java.lang.String request) {
this.request = request;
return this;
}
/**
* The bytes to match against the beginning of the response data. If left empty (the default
* value), any response will indicate health. The response data can only be ASCII.
* @return value or {@code null} for none
*/
public java.lang.String getResponse() {
return response;
}
/**
* The bytes to match against the beginning of the response data. If left empty (the default
* value), any response will indicate health. The response data can only be ASCII.
* @param response response or {@code null} for none
*/
public SSLHealthCheck setResponse(java.lang.String response) {
this.response = response;
return this;
}
@Override
public SSLHealthCheck set(String fieldName, Object value) {
return (SSLHealthCheck) super.set(fieldName, value);
}
@Override
public SSLHealthCheck clone() {
return (SSLHealthCheck) super.clone();
}
}
| apache-2.0 |
RLDevOps/Demo | src/main/java/org/olat/commons/info/portlet/InfoMessagePortlet.java | 2191 | package org.olat.commons.info.portlet;
import java.util.Map;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.generic.portal.AbstractPortlet;
import org.olat.core.gui.control.generic.portal.Portlet;
import org.olat.core.gui.control.generic.portal.PortletToolController;
import org.olat.core.gui.translator.Translator;
import org.olat.core.util.Util;
/**
* Description:<br>
* TODO: srosse Class Description for InfoMessagePortlet
* <P>
* Initial Date: 27 juil. 2010 <br>
*
* @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
*/
public class InfoMessagePortlet extends AbstractPortlet {
private InfoMessagePortletRunController runCtrl;
@Override
public String getTitle() {
return getTranslator().translate("portlet.title");
}
@Override
public String getDescription() {
return getTranslator().translate("portlet.title");
}
@Override
public Portlet createInstance(final WindowControl wControl, final UserRequest ureq, final Map portletConfig) {
final Translator translator = Util.createPackageTranslator(InfoMessagePortlet.class, ureq.getLocale());
final Portlet p = new InfoMessagePortlet();
p.setName(getName());
p.setTranslator(translator);
return p;
}
@Override
public Component getInitialRunComponent(final WindowControl wControl, final UserRequest ureq) {
if (runCtrl != null) {
runCtrl.dispose();
}
runCtrl = new InfoMessagePortletRunController(wControl, ureq, getTranslator(), getName());
return runCtrl.getInitialComponent();
}
@Override
public void dispose() {
disposeRunComponent();
}
@Override
public void disposeRunComponent() {
if (this.runCtrl != null) {
this.runCtrl.dispose();
this.runCtrl = null;
}
}
@Override
public String getCssClass() {
return "o_portlet_infomessages";
}
@Override
public PortletToolController getTools(final UserRequest ureq, final WindowControl wControl) {
if (runCtrl == null) {
runCtrl = new InfoMessagePortletRunController(wControl, ureq, getTranslator(), getName());
}
return runCtrl.createSortingTool(ureq, wControl);
}
}
| apache-2.0 |
HidemotoNakada/cassandra-udf | test/unit/org/apache/cassandra/cli/CliTest.java | 15381 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.cli;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.service.EmbeddedCassandraService;
import org.apache.cassandra.thrift.*;
import org.apache.thrift.TException;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CliTest extends SchemaLoader
{
// please add new statements here so they could be auto-runned by this test.
private String[] statements = {
"use TestKeySpace;",
"create column family SecondaryIndicesWithoutIdxName" +
" with comparator = UTF8Type" +
" and default_validation_class = UTF8Type" +
" and column_metadata = [{column_name: profileId, validation_class: UTF8Type, index_type: KEYS}];",
"update column family SecondaryIndicesWithoutIdxName" +
" with column_metadata = " +
"[{column_name: profileId, validation_class: UTF8Type, index_type: KEYS}," +
"{column_name: postedDate, validation_class: LongType}];",
"create column family 123 with comparator=UTF8Type and column_metadata=[{ column_name:world, validation_class:IntegerType, index_type:0, index_name:IdxName }, " +
"{ column_name:world2, validation_class:LongType, index_type:KEYS, index_name:LongIdxName}, " +
"{ column_name:617070, validation_class:UTF8Type, index_type:KEYS }, " +
"{ column_name:'-617071', validation_class:UTF8Type, index_type:KEYS }," +
"{ column_name:time_spent_uuid, validation_class:TimeUUIDType}] and default_validation_class=UTF8Type;",
"assume 123 keys as utf8;",
"set 123[hello][world] = 123848374878933948398384;",
"set 123[hello][test_quote] = 'value\\'';",
"set 123['k\\'ey'][VALUE] = 'VAL';",
"set 123['k\\'ey'][VALUE] = 'VAL\\'';",
"set 123[hello][-31337] = 'some string value';",
"list 123;",
"list 123[:];",
"list 123[456:];",
"list 123 limit 5;",
"list 123[12:15] limit 20;",
"list 123[12:15] columns 2;",
"list 123 columns 2 reversed;",
"list 123 limit 10 columns 2 reversed;",
"get 123[hello][-31337];",
"get 123[hello][world];",
"get 123[hello][test_quote];",
"get 123['k\\'ey'][VALUE]",
"set 123[hello][-31337] = -23876;",
"set 123[hello][world2] = 15;",
"get 123 where world2 = long(15);",
"get 123 where world2 = long(15);",
"get 123 where world2 = long(15);",
"del 123[utf8('hello')][utf8('world')];",
"del 123[hello][world2];",
"set 123['hello'][time_spent_uuid] = timeuuid(a8098c1a-f86e-11da-bd1a-00112444be1e);",
"create column family CF2 with comparator=IntegerType and default_validation_class=AsciiType;",
"assume CF2 keys as utf8;",
"set CF2['key'][98349387493847748398334] = 'some text';",
"get CF2['key'][98349387493847748398334];",
"set CF2['key'][98349387493] = 'some text other';",
"get CF2['key'][98349387493];",
"create column family CF3 with comparator=UTF8Type and column_metadata=[{column_name:'big world', validation_class:LongType, index_type:KEYS, index_name:WorldIdx}];",
"assume CF3 keys as utf8;",
"set CF3['hello']['big world'] = 3748;",
"get CF3['hello']['big world'];",
"list CF3;",
"list CF3[:];",
"list CF3[h:];",
"list CF3 limit 10;",
"list CF3[h:] limit 10;",
"create column family CF4 with comparator=IntegerType and column_metadata=[{column_name:9999, validation_class:LongType}];",
"assume CF4 keys as utf8;",
"set CF4['hello'][9999] = 1234;",
"get CF4['hello'][9999];",
"get CF4['hello'][9999] as Long;",
"get CF4['hello'][9999] as Bytes;",
"set CF4['hello'][9999] = Long(1234);",
"get CF4['hello'][9999];",
"get CF4['hello'][9999] as Long;",
"del CF4['hello'][9999];",
"get CF4['hello'][9999];",
"create column family sCf1 with column_type=Super and comparator=IntegerType and subcomparator=LongType and column_metadata=[{column_name:9999, validation_class:LongType}];",
"assume sCf1 keys as utf8;",
"set sCf1['hello'][1][9999] = 1234;",
"get sCf1['hello'][1][9999];",
"get sCf1['hello'][1][9999] as Long;",
"get sCf1['hello'][1][9999] as Bytes;",
"set sCf1['hello'][1][9999] = Long(1234);",
"set sCf1['hello'][-1][-12] = Long(5678);",
"get sCf1['hello'][-1][-12];",
"set sCf1['hello'][-1][-12] = -340897;",
"set sCf1['hello'][-1][-12] = integer(-340897);",
"get sCf1['hello'][1][9999];",
"get sCf1['hello'][1][9999] as Long;",
"del sCf1['hello'][1][9999];",
"get sCf1['hello'][1][9999];",
"set sCf1['hello'][1][9999] = Long(1234);",
"del sCf1['hello'][9999];",
"get sCf1['hello'][1][9999];",
"create column family 'Counter1' with comparator=UTF8Type and default_validation_class=CounterColumnType;",
"assume Counter1 keys as utf8;",
"incr Counter1['hello']['cassandra'];",
"incr Counter1['hello']['cassandra'] by 3;",
"incr Counter1['hello']['cassandra'] by -2;",
"decr Counter1['hello']['cassandra'];",
"decr Counter1['hello']['cassandra'] by 3;",
"decr Counter1['hello']['cassandra'] by -2;",
"get Counter1['hello']['cassandra'];",
"get Counter1['hello'];",
"truncate 123;",
"drop index on '123'.world2;",
"drop index on '123'.617070;",
"drop index on '123'.'-617071';",
"drop index on CF3.'big world';",
"update keyspace TestKeySpace with durable_writes = false;",
"assume 123 comparator as utf8;",
"assume 123 sub_comparator as integer;",
"assume 123 validator as lexicaluuid;",
"assume 123 keys as timeuuid;",
"create column family CF7;",
"assume CF7 keys as utf8;",
"set CF7[1][timeuuid()] = utf8(test1);",
"set CF7[2][lexicaluuid()] = utf8('hello world!');",
"set CF7[3][lexicaluuid(550e8400-e29b-41d4-a716-446655440000)] = utf8(test2);",
"set CF7[key2][timeuuid()] = utf8(test3);",
"assume CF7 comparator as lexicaluuid;",
"assume CF7 keys as utf8;",
"list CF7;",
"get CF7[3];",
"get CF7[3][lexicaluuid(550e8400-e29b-41d4-a716-446655440000)];",
"get sCf1['hello'][1][9999];",
"set sCf1['hello'][1][9999] = 938;",
"set sCf1['hello'][1][9999] = 938 with ttl = 30;",
"set sCf1['hello'][1][9999] = 938 with ttl = 560;",
"count sCf1[hello];",
"count sCf1[utf8('hello')];",
"count sCf1[utf8('hello')][integer(1)];",
"count sCf1[hello][1];",
"list sCf1;",
"del sCf1['hello'][1][9999];",
"assume sCf1 comparator as utf8;",
"create column family CF8;",
"drop column family cF8;",
"create keyspace TESTIN;",
"drop keyspace tesTIN;",
"update column family 123 with comparator=UTF8Type and column_metadata=[];",
"drop column family 123;",
"create column family myCF with column_type='Super' and comparator='UTF8Type' AND subcomparator='UTF8Type' AND default_validation_class=AsciiType;",
"assume myCF keys as utf8;",
"create column family Countries with comparator=UTF8Type and column_metadata=[ {column_name: name, validation_class: UTF8Type} ];",
"set Countries[11][name] = USA;",
"get Countries[11][name];",
"update column family Countries with compaction_strategy = 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy';",
"create column family Cities with compaction_strategy = 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy' and compaction_strategy_options = {min_sstable_size:1024};",
"set myCF['key']['scName']['firstname'] = 'John';",
"get myCF['key']['scName']",
"assume CF3 keys as utf8;",
"use TestKEYSpace;",
"update keyspace TestKeySpace with placement_strategy='org.apache.cassandra.locator.NetworkTopologyStrategy';",
"update keyspace TestKeySpace with strategy_options=[{DC1:3, DC2:4, DC5:1}];",
"describe cluster;",
"help describe cluster;",
"show cluster name",
"show api version",
"help help",
"help connect",
"help use",
"help describe",
"HELP exit",
"help QUIT",
"help show cluster name",
"help show keyspaces",
"help show schema",
"help show api version",
"help create keyspace",
"HELP update KEYSPACE",
"HELP CREATE column FAMILY",
"HELP UPDATE COLUMN family",
"HELP drop keyspace",
"help drop column family",
"HELP GET",
"HELP set",
"HELP DEL",
"HELP count",
"HELP list",
"HELP TRUNCATE",
"help assume",
"HELP",
"?",
"show schema",
"show schema TestKeySpace"
};
@Test
public void testCli() throws IOException, TException, ConfigurationException, ClassNotFoundException, TimedOutException, NotFoundException, SchemaDisagreementException, NoSuchFieldException, InvalidRequestException, UnavailableException, InstantiationException, IllegalAccessException
{
Schema.instance.clear(); // Schema are now written on disk and will be reloaded
new EmbeddedCassandraService().start();
// new error/output streams for CliSessionState
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// checking if we can connect to the running cassandra node on localhost
CliMain.connect("127.0.0.1", 9170);
// setting new output stream
CliMain.sessionState.setOut(new PrintStream(outStream));
CliMain.sessionState.setErr(new PrintStream(errStream));
// re-creating keyspace for tests
try
{
// dropping in case it exists e.g. could be left from previous run
CliMain.processStatement("drop keyspace TestKeySpace;");
}
catch (Exception e)
{
// TODO check before drop so we don't have this fragile ignored exception block
}
CliMain.processStatement("create keyspace TestKeySpace;");
for (String statement : statements)
{
errStream.reset();
// System.out.println("Executing statement: " + statement);
CliMain.processStatement(statement);
String result = outStream.toString();
// System.out.println("Result:\n" + result);
if (statement.startsWith("show schema"))
assertEquals(errStream.toString() + "processing" + statement,
"\nWARNING: CQL3 tables are intentionally omitted from 'show schema' output.\n"
+ "See https://issues.apache.org/jira/browse/CASSANDRA-4377 for details.\n\n",
errStream.toString());
else
assertEquals(errStream.toString() + " processing " + statement, "", errStream.toString());
if (statement.startsWith("drop ") || statement.startsWith("create ") || statement.startsWith("update "))
{
assert Pattern.compile("(.{8})-(.{4})-(.{4})-(.{4})-(.{12}).*", Pattern.DOTALL).matcher(result).matches()
: String.format("\"%s\" failed: %s", statement, result);
}
else if (statement.startsWith("set "))
{
assertTrue(result.contains("Value inserted."));
assertTrue(result.contains("Elapsed time:"));
}
else if (statement.startsWith("incr "))
{
assertTrue(result.contains("Value incremented."));
}
else if (statement.startsWith("decr "))
{
assertTrue(result.contains("Value decremented."));
}
else if (statement.startsWith("get "))
{
if (statement.contains("where"))
{
assertTrue(result.startsWith("-------------------" + System.getProperty("line.separator") + "RowKey:"));
}
else if (statement.contains("Counter"))
{
assertTrue(result.startsWith("=> (counter=") || result.startsWith("Value was not found"));
}
else
{
assertTrue(result.startsWith("=> (column=") || result.startsWith("Value was not found"));
}
assertTrue(result.contains("Elapsed time:"));
}
else if (statement.startsWith("truncate "))
{
assertTrue(result.contains(" truncated."));
}
else if (statement.startsWith("assume "))
{
assertTrue(result.contains("successfully."));
}
outStream.reset(); // reset stream so we have only output from next statement all the time
errStream.reset(); // no errors to the end user.
}
}
@Test
public void testEscape()
{
//escaped is the string read from the cli.
String escaped = "backspace \\b tab \\t linefeed \\n form feed \\f carriage return \\r duble quote \\\" " +
"single quote \\' backslash \\\\";
String unescaped = "backspace \b tab \t linefeed \n form feed \f carriage return \r duble quote \" " +
"single quote ' backslash \\";
// when read from the cli may have single quotes around it
assertEquals(unescaped, CliUtils.unescapeSQLString("'" + escaped + "'"));
assertEquals(escaped, CliUtils.escapeSQLString(unescaped));
}
}
| apache-2.0 |
rockmkd/datacollector | stagesupport/src/main/java/com/streamsets/datacollector/record/PathElement.java | 10337 | /*
* Copyright 2017 StreamSets 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.streamsets.datacollector.record;
import com.streamsets.datacollector.util.EscapeUtil;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.lib.util.FieldPathExpressionUtil;
import java.util.ArrayList;
import java.util.List;
public class PathElement {
public enum Type {
ROOT,
MAP,
LIST,
FIELD_EXPRESSION
}
private final Type type;
private final String name;
private final int idx;
public static final String WILDCARD_ANY_LENGTH = "*";
public static final String WILDCARD_SINGLE_CHAR = "?";
public static final int WILDCARD_INDEX_ANY_LENGTH = -1;
public static final int WILDCARD_INDEX_SINGLE_CHAR = -2;
public static final PathElement ROOT = new PathElement(Type.ROOT, null, 0);
private PathElement(Type type, String name, int idx) {
this.type = type;
this.name = name;
this.idx = idx;
}
public static PathElement createMapElement(String name) {
return new PathElement(Type.MAP, name, 0);
}
public static PathElement createArrayElement(int idx) {
return new PathElement(Type.LIST, null, idx);
}
public static PathElement createFieldExpressionElement(String expression) {
return new PathElement(Type.FIELD_EXPRESSION, expression, 0);
}
public Type getType() {
return type;
}
public String getName() {
return name;
}
public int getIndex() {
return idx;
}
@Override
public String toString() {
switch (type) {
case ROOT:
return "PathElement[type=ROOT]";
case MAP:
return Utils.format("PathElement[type=MAP, name='{}']", getName());
case LIST:
return Utils.format("PathElement[type=LIST, idx='{}']", getIndex());
case FIELD_EXPRESSION:
return Utils.format("PathElement[type=FIELD_EXPRESSION, expression='{}']", getName());
default:
throw new IllegalStateException();
}
}
public static final String INVALID_FIELD_PATH = "Invalid fieldPath '{}' at char '{}'";
public static final String INVALID_FIELD_PATH_REASON = "Invalid fieldPath '{}' at char '{}' ({})";
public static final String REASON_EMPTY_FIELD_NAME = "field name can't be empty";
public static final String REASON_INVALID_START = "field path needs to start with '[' or '/'";
public static final String REASON_NOT_VALID_EXPR = "only numbers, the '*' character, or a field path EL expression " +
"is allowed between '[' and ']'";
public static final String REASON_QUOTES = "quotes are not properly closed";
public static final String INVALID_FIELD_PATH_NUMBER = "Invalid fieldPath '{}' at char '{}' ('{}' needs to be a" +
" number, the '*' character, or a field path EL expression)";
public static List<PathElement> parse(
String fieldPath,
boolean isSingleQuoteEscaped
) {
return parse(fieldPath, isSingleQuoteEscaped, false);
}
public static List<PathElement> parse(
String fieldPath,
boolean isSingleQuoteEscaped,
boolean includeFieldPathExpressionElements
) {
if(fieldPath == null) {
throw new NullPointerException("fieldPath cannot be null");
}
fieldPath = EscapeUtil.standardizePathForParse(fieldPath, isSingleQuoteEscaped);
List<PathElement> elements = new ArrayList<>();
elements.add(PathElement.ROOT);
if (!fieldPath.isEmpty()) {
char chars[] = fieldPath.toCharArray();
boolean requiresStart = true;
boolean requiresName = false;
int squareBracketsDepth = 0;
boolean singleQuote = false;
boolean doubleQuote = false;
StringBuilder collector = new StringBuilder();
int pos = 0;
for (; pos < chars.length; pos++) {
final char ch = chars[pos];
if (requiresStart && squareBracketsDepth == 0) {
requiresStart = false;
requiresName = false;
singleQuote = false;
doubleQuote = false;
switch (ch) {
case '/':
requiresName = true;
break;
case '[':
squareBracketsDepth++;
break;
default:
throw new IllegalArgumentException(Utils.format(INVALID_FIELD_PATH_REASON, fieldPath, 0, REASON_INVALID_START));
}
} else {
if (requiresName) {
switch (ch) {
case '\'':
if(pos == 0 || chars[pos - 1] != '\\') {
if(!doubleQuote) {
singleQuote = !singleQuote;
} else {
collector.append(ch);
}
} else {
collector.setLength(collector.length() - 1);
collector.append(ch);
}
break;
case '"':
if(pos == 0 || chars[pos - 1] != '\\') {
if(!singleQuote) {
doubleQuote = !doubleQuote;
} else {
collector.append(ch);
}
} else {
collector.setLength(collector.length() - 1);
collector.append(ch);
}
break;
case '/':
case '[':
case ']':
if(singleQuote || doubleQuote) {
collector.append(ch);
} else {
requiresName = false;
if (ch == '[') {
if (squareBracketsDepth++ > 0) {
collector.append(ch);
}
} else if (ch == ']') {
if (--squareBracketsDepth > 0) {
collector.append(ch);
}
}
if (chars.length <= pos + 1) {
throw new IllegalArgumentException(Utils.format(INVALID_FIELD_PATH_REASON, fieldPath, pos, REASON_EMPTY_FIELD_NAME));
}
if (ch == chars[pos + 1]) {
collector.append(ch);
pos++;
} else {
elements.add(PathElement.createMapElement(collector.toString()));
requiresStart = true;
squareBracketsDepth = 0;
collector.setLength(0);
//not very kosher, we need to replay the current char as start of path element
pos--;
}
}
break;
default:
collector.append(ch);
}
} else if (squareBracketsDepth > 0) {
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '*': //wildcard character
collector.append(ch);
break;
case ']':
if (--squareBracketsDepth == 0) {
String bracketedString = collector.toString();
if (FieldPathExpressionUtil.isFieldPathExpression(bracketedString)) {
if (includeFieldPathExpressionElements) {
elements.add(createFieldExpressionElement(bracketedString));
}
requiresStart = true;
squareBracketsDepth = 0;
collector.setLength(0);
} else {
final boolean singleCharWildcard = WILDCARD_SINGLE_CHAR.equals(bracketedString);
final boolean wildcardAnyLength = WILDCARD_ANY_LENGTH.equals(bracketedString);
final boolean wildcardIndex = singleCharWildcard || wildcardAnyLength;
if (wildcardIndex || bracketedString.matches("[0-9]+")) {
// wildcard or numeric index
try {
int index = singleCharWildcard ? WILDCARD_INDEX_SINGLE_CHAR : WILDCARD_INDEX_ANY_LENGTH;
if(!wildcardIndex) {
index = Integer.parseInt(bracketedString);
}
elements.add(createArrayElement(index));
requiresStart = true;
squareBracketsDepth = 0;
collector.setLength(0);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(Utils.format(INVALID_FIELD_PATH_NUMBER, fieldPath, pos, bracketedString), ex);
}
} else {
throw new IllegalArgumentException(Utils.format(INVALID_FIELD_PATH_REASON, fieldPath, pos, REASON_NOT_VALID_EXPR));
}
}
} else {
collector.append(ch);
}
break;
case '[':
squareBracketsDepth++;
// fall through
default:
collector.append(ch);
break;
}
}
}
}
if(singleQuote || doubleQuote) {
//If there is no matching quote
throw new IllegalArgumentException(Utils.format(INVALID_FIELD_PATH_REASON, fieldPath, 0, REASON_QUOTES));
} else if (pos < chars.length) {
throw new IllegalArgumentException(Utils.format(INVALID_FIELD_PATH, fieldPath, pos));
} else if (collector.length() > 0) {
// the last path element was a map entry, we need to create it.
elements.add(PathElement.createMapElement(collector.toString()));
}
}
return elements;
}
}
| apache-2.0 |
johncarl81/transfuse | transfuse/src/main/java/org/androidtransfuse/gen/variableBuilder/resource/AnimationResourceExpressionBuilder.java | 2717 | /**
* Copyright 2011-2015 John Ericksen
*
* 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.androidtransfuse.gen.variableBuilder.resource;
import com.sun.codemodel.JExpression;
import org.androidtransfuse.gen.ClassGenerationUtil;
import org.androidtransfuse.gen.InjectionBuilderContext;
import org.androidtransfuse.gen.InjectionExpressionBuilder;
import org.androidtransfuse.gen.variableDecorator.TypedExpressionFactory;
import org.androidtransfuse.model.InjectionNode;
import org.androidtransfuse.model.TypedExpression;
import org.androidtransfuse.util.AndroidLiterals;
import javax.inject.Inject;
/**
* @author John Ericksen
*/
public class AnimationResourceExpressionBuilder implements ResourceExpressionBuilder {
private static final String LOAD_ANIMATION = "loadAnimation";
private final ClassGenerationUtil generationUtil;
private final InjectionNode applicationInjectionNode;
private final InjectionExpressionBuilder injectionExpressionBuilder;
private final TypedExpressionFactory typedExpressionFactory;
@Inject
public AnimationResourceExpressionBuilder(/*@Assisted*/ InjectionNode applicationInjectionNode,
ClassGenerationUtil generationUtil,
InjectionExpressionBuilder injectionExpressionBuilder, TypedExpressionFactory typedExpressionFactory) {
this.generationUtil = generationUtil;
this.applicationInjectionNode = applicationInjectionNode;
this.injectionExpressionBuilder = injectionExpressionBuilder;
this.typedExpressionFactory = typedExpressionFactory;
}
@Override
public TypedExpression buildExpression(InjectionBuilderContext context, JExpression resourceIdExpr) {
TypedExpression applicationVar = injectionExpressionBuilder.buildVariable(context, applicationInjectionNode);
//AnimationUtils.loadAnimation(application, id);
JExpression expression = generationUtil.ref(AndroidLiterals.ANIMATION_UTILS).staticInvoke(LOAD_ANIMATION).arg(applicationVar.getExpression()).arg(resourceIdExpr);
return typedExpressionFactory.build(AndroidLiterals.ANIMATION, expression);
}
}
| apache-2.0 |
stoksey69/googleads-java-lib | examples/dfp_axis/src/main/java/dfp/axis/v201408/userteamassociationservice/GetAllUserTeamAssociations.java | 3645 | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dfp.axis.v201408.userteamassociationservice;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.dfp.axis.factory.DfpServices;
import com.google.api.ads.dfp.axis.utils.v201408.StatementBuilder;
import com.google.api.ads.dfp.axis.v201408.UserTeamAssociation;
import com.google.api.ads.dfp.axis.v201408.UserTeamAssociationPage;
import com.google.api.ads.dfp.axis.v201408.UserTeamAssociationServiceInterface;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.api.client.auth.oauth2.Credential;
/**
* This example gets all user team associations. To create user team
* associations, run CreateUserTeamAssociations.java.
*
* Credentials and properties in {@code fromFile()} are pulled from the
* "ads.properties" file. See README for more info.
*
* Tags: UserTeamAssociationService.getUserTeamAssociationsByStatement
*
* @author Adam Rogal
*/
public class GetAllUserTeamAssociations {
public static void runExample(DfpServices dfpServices, DfpSession session)
throws Exception {
// Get the UserTeamAssociationService.
UserTeamAssociationServiceInterface userTeamAssociationService =
dfpServices.get(session, UserTeamAssociationServiceInterface.class);
// Create a statement to select all user team associations.
StatementBuilder statementBuilder = new StatementBuilder()
.orderBy("teamId ASC, userId ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
// Default for total result set size.
int totalResultSetSize = 0;
do {
// Get user team associations by statement.
UserTeamAssociationPage page =
userTeamAssociationService.getUserTeamAssociationsByStatement(
statementBuilder.toStatement());
if (page.getResults() != null) {
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (UserTeamAssociation userTeamAssociation : page.getResults()) {
System.out.printf(
"%d) User team associations with team ID \"%d\" and user ID \"%d\" was found.\n", i++,
userTeamAssociation.getTeamId(), userTeamAssociation.getUserId());
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d\n", totalResultSetSize);
}
public static void main(String[] args) throws Exception {
// Generate a refreshable OAuth2 credential.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.DFP)
.fromFile()
.build()
.generateCredential();
// Construct a DfpSession.
DfpSession session = new DfpSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
DfpServices dfpServices = new DfpServices();
runExample(dfpServices, session);
}
}
| apache-2.0 |
bergerch/library | src/main/java/bftsmart/tom/core/messages/TOMMessageType.java | 1769 | /**
Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bftsmart.tom.core.messages;
/**
* Possible types of TOMMessage
*
* @author alysson
*/
public enum TOMMessageType {
ORDERED_REQUEST, //0
UNORDERED_REQUEST, //1
REPLY, //2
RECONFIG, //3
ASK_STATUS, // 4
STATUS_REPLY,// 5
UNORDERED_HASHED_REQUEST; //6
public int toInt() {
switch(this) {
case ORDERED_REQUEST: return 0;
case UNORDERED_REQUEST: return 1;
case REPLY: return 2;
case RECONFIG: return 3;
case ASK_STATUS: return 4;
case STATUS_REPLY: return 5;
case UNORDERED_HASHED_REQUEST: return 6;
default: return -1;
}
}
public static TOMMessageType fromInt(int i) {
switch(i) {
case 0: return ORDERED_REQUEST;
case 1: return UNORDERED_REQUEST;
case 2: return REPLY;
case 3: return RECONFIG;
case 4: return ASK_STATUS;
case 5: return STATUS_REPLY;
case 6: return UNORDERED_HASHED_REQUEST;
default: return RECONFIG;
}
}
}
| apache-2.0 |
yintaoxue/read-open-source-code | solr-4.10.4/src/org/apache/solr/handler/component/HighlightComponent.java | 8305 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.handler.component;
import com.google.common.base.Objects;
import org.apache.lucene.search.Query;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.HighlightParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.core.PluginInfo;
import org.apache.solr.core.SolrCore;
import org.apache.solr.highlight.DefaultSolrHighlighter;
import org.apache.solr.highlight.PostingsSolrHighlighter;
import org.apache.solr.highlight.SolrHighlighter;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.QParser;
import org.apache.solr.search.QParserPlugin;
import org.apache.solr.search.QueryParsing;
import org.apache.solr.search.SyntaxError;
import org.apache.solr.util.SolrPluginUtils;
import org.apache.solr.util.plugin.PluginInfoInitialized;
import org.apache.solr.util.plugin.SolrCoreAware;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* TODO!
*
*
* @since solr 1.3
*/
public class HighlightComponent extends SearchComponent implements PluginInfoInitialized, SolrCoreAware
{
public static final String COMPONENT_NAME = "highlight";
private PluginInfo info = PluginInfo.EMPTY_INFO;
private SolrHighlighter highlighter;
public static SolrHighlighter getHighlighter(SolrCore core) {
HighlightComponent hl = (HighlightComponent) core.getSearchComponents().get(HighlightComponent.COMPONENT_NAME);
return hl==null ? null: hl.getHighlighter();
}
@Override
public void init(PluginInfo info) {
this.info = info;
}
@Override
public void prepare(ResponseBuilder rb) throws IOException {
SolrParams params = rb.req.getParams();
rb.doHighlights = highlighter.isHighlightingEnabled(params);
if(rb.doHighlights){
String hlq = params.get(HighlightParams.Q);
String hlparser = Objects.firstNonNull(params.get(HighlightParams.QPARSER),
params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE));
if(hlq != null){
try {
QParser parser = QParser.getParser(hlq, hlparser, rb.req);
rb.setHighlightQuery(parser.getHighlightQuery());
} catch (SyntaxError e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
}
}
}
}
@Override
public void inform(SolrCore core) {
List<PluginInfo> children = info.getChildren("highlighting");
if(children.isEmpty()) {
PluginInfo pluginInfo = core.getSolrConfig().getPluginInfo(SolrHighlighter.class.getName()); //TODO deprecated configuration remove later
if (pluginInfo != null) {
highlighter = core.createInitInstance(pluginInfo, SolrHighlighter.class, null, DefaultSolrHighlighter.class.getName());
highlighter.initalize(core.getSolrConfig());
} else {
DefaultSolrHighlighter defHighlighter = new DefaultSolrHighlighter(core);
defHighlighter.init(PluginInfo.EMPTY_INFO);
highlighter = defHighlighter;
}
} else {
highlighter = core.createInitInstance(children.get(0),SolrHighlighter.class,null, DefaultSolrHighlighter.class.getName());
}
}
@Override
public void process(ResponseBuilder rb) throws IOException {
if (rb.doHighlights) {
SolrQueryRequest req = rb.req;
SolrParams params = req.getParams();
String[] defaultHighlightFields; //TODO: get from builder by default?
if (rb.getQparser() != null) {
defaultHighlightFields = rb.getQparser().getDefaultHighlightFields();
} else {
defaultHighlightFields = params.getParams(CommonParams.DF);
}
Query highlightQuery = rb.getHighlightQuery();
if(highlightQuery==null) {
if (rb.getQparser() != null) {
try {
highlightQuery = rb.getQparser().getHighlightQuery();
rb.setHighlightQuery( highlightQuery );
} catch (Exception e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
}
} else {
highlightQuery = rb.getQuery();
rb.setHighlightQuery( highlightQuery );
}
}
if(highlightQuery != null) {
boolean rewrite = (highlighter instanceof PostingsSolrHighlighter == false) && !(Boolean.valueOf(params.get(HighlightParams.USE_PHRASE_HIGHLIGHTER, "true")) &&
Boolean.valueOf(params.get(HighlightParams.HIGHLIGHT_MULTI_TERM, "true")));
highlightQuery = rewrite ? highlightQuery.rewrite(req.getSearcher().getIndexReader()) : highlightQuery;
}
// No highlighting if there is no query -- consider q.alt="*:*
if( highlightQuery != null ) {
NamedList sumData = highlighter.doHighlighting(
rb.getResults().docList,
highlightQuery,
req, defaultHighlightFields );
if(sumData != null) {
// TODO ???? add this directly to the response?
rb.rsp.add("highlighting", sumData);
}
}
}
}
@Override
public void modifyRequest(ResponseBuilder rb, SearchComponent who, ShardRequest sreq) {
if (!rb.doHighlights) return;
// Turn on highlighting only only when retrieving fields
if ((sreq.purpose & ShardRequest.PURPOSE_GET_FIELDS) != 0) {
sreq.purpose |= ShardRequest.PURPOSE_GET_HIGHLIGHTS;
// should already be true...
sreq.params.set(HighlightParams.HIGHLIGHT, "true");
} else {
sreq.params.set(HighlightParams.HIGHLIGHT, "false");
}
}
@Override
public void handleResponses(ResponseBuilder rb, ShardRequest sreq) {
}
@Override
public void finishStage(ResponseBuilder rb) {
if (rb.doHighlights && rb.stage == ResponseBuilder.STAGE_GET_FIELDS) {
Map.Entry<String, Object>[] arr = new NamedList.NamedListEntry[rb.resultIds.size()];
// TODO: make a generic routine to do automatic merging of id keyed data
for (ShardRequest sreq : rb.finished) {
if ((sreq.purpose & ShardRequest.PURPOSE_GET_HIGHLIGHTS) == 0) continue;
for (ShardResponse srsp : sreq.responses) {
if (srsp.getException() != null) {
// can't expect the highlight content if there was an exception for this request
// this should only happen when using shards.tolerant=true
continue;
}
NamedList hl = (NamedList)srsp.getSolrResponse().getResponse().get("highlighting");
for (int i=0; i<hl.size(); i++) {
String id = hl.getName(i);
ShardDoc sdoc = rb.resultIds.get(id);
int idx = sdoc.positionInResponse;
arr[idx] = new NamedList.NamedListEntry<>(id, hl.getVal(i));
}
}
}
// remove nulls in case not all docs were able to be retrieved
rb.rsp.add("highlighting", SolrPluginUtils.removeNulls(arr, new SimpleOrderedMap<Object>()));
}
}
public SolrHighlighter getHighlighter() {
return highlighter;
}
////////////////////////////////////////////
/// SolrInfoMBean
////////////////////////////////////////////
@Override
public String getDescription() {
return "Highlighting";
}
@Override
public String getSource() {
return null;
}
@Override
public URL[] getDocs() {
return null;
}
}
| apache-2.0 |
mattnelson/dropwizard | dropwizard-logging/src/main/java/io/dropwizard/logging/DefaultLoggingFactory.java | 8709 | package io.dropwizard.logging;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.jmx.JMXConfigurator;
import ch.qos.logback.classic.jul.LevelChangePropagator;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.util.StatusPrinter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.logback.InstrumentedAppender;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.logging.async.AsyncAppenderFactory;
import io.dropwizard.logging.async.AsyncLoggingEventAppenderFactory;
import io.dropwizard.logging.filter.LevelFilterFactory;
import io.dropwizard.logging.filter.ThresholdLevelFilterFactory;
import io.dropwizard.logging.layout.DropwizardLayoutFactory;
import io.dropwizard.logging.layout.LayoutFactory;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MalformedObjectNameException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import static java.util.Objects.requireNonNull;
@JsonTypeName("default")
public class DefaultLoggingFactory implements LoggingFactory {
private static final ReentrantLock MBEAN_REGISTRATION_LOCK = new ReentrantLock();
private static final ReentrantLock CHANGE_LOGGER_CONTEXT_LOCK = new ReentrantLock();
@NotNull
private Level level = Level.INFO;
@NotNull
private ImmutableMap<String, JsonNode> loggers = ImmutableMap.of();
@Valid
@NotNull
private ImmutableList<AppenderFactory<ILoggingEvent>> appenders = ImmutableList.<AppenderFactory<ILoggingEvent>>of(
new ConsoleAppenderFactory<>()
);
@JsonIgnore
private final LoggerContext loggerContext;
@JsonIgnore
private final PrintStream configurationErrorsStream;
public DefaultLoggingFactory() {
this(LoggingUtil.getLoggerContext(), System.err);
}
@VisibleForTesting
DefaultLoggingFactory(LoggerContext loggerContext, PrintStream configurationErrorsStream) {
this.loggerContext = requireNonNull(loggerContext);
this.configurationErrorsStream = requireNonNull(configurationErrorsStream);
}
@VisibleForTesting
LoggerContext getLoggerContext() {
return loggerContext;
}
@VisibleForTesting
PrintStream getConfigurationErrorsStream() {
return configurationErrorsStream;
}
@JsonProperty
public Level getLevel() {
return level;
}
@JsonProperty
public void setLevel(Level level) {
this.level = level;
}
@JsonProperty
public ImmutableMap<String, JsonNode> getLoggers() {
return loggers;
}
@JsonProperty
public void setLoggers(Map<String, JsonNode> loggers) {
this.loggers = ImmutableMap.copyOf(loggers);
}
@JsonProperty
public ImmutableList<AppenderFactory<ILoggingEvent>> getAppenders() {
return appenders;
}
@JsonProperty
public void setAppenders(List<AppenderFactory<ILoggingEvent>> appenders) {
this.appenders = ImmutableList.copyOf(appenders);
}
public void configure(MetricRegistry metricRegistry, String name) {
LoggingUtil.hijackJDKLogging();
CHANGE_LOGGER_CONTEXT_LOCK.lock();
final Logger root;
try {
root = configureLoggers(name);
} finally {
CHANGE_LOGGER_CONTEXT_LOCK.unlock();
}
final LevelFilterFactory<ILoggingEvent> levelFilterFactory = new ThresholdLevelFilterFactory();
final AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory = new AsyncLoggingEventAppenderFactory();
final LayoutFactory<ILoggingEvent> layoutFactory = new DropwizardLayoutFactory();
for (AppenderFactory<ILoggingEvent> output : appenders) {
root.addAppender(output.build(loggerContext, name, layoutFactory, levelFilterFactory, asyncAppenderFactory));
}
StatusPrinter.setPrintStream(configurationErrorsStream);
try {
StatusPrinter.printIfErrorsOccured(loggerContext);
} finally {
StatusPrinter.setPrintStream(System.out);
}
final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
MBEAN_REGISTRATION_LOCK.lock();
try {
final ObjectName objectName = new ObjectName("io.dropwizard:type=Logging");
if (!server.isRegistered(objectName)) {
server.registerMBean(new JMXConfigurator(loggerContext,
server,
objectName),
objectName);
}
} catch (MalformedObjectNameException | InstanceAlreadyExistsException |
NotCompliantMBeanException | MBeanRegistrationException e) {
throw new RuntimeException(e);
} finally {
MBEAN_REGISTRATION_LOCK.unlock();
}
configureInstrumentation(root, metricRegistry);
}
public void stop() {
// Should acquire the lock to avoid concurrent listener changes
CHANGE_LOGGER_CONTEXT_LOCK.lock();
try {
loggerContext.stop();
} finally {
CHANGE_LOGGER_CONTEXT_LOCK.unlock();
}
}
private void configureInstrumentation(Logger root, MetricRegistry metricRegistry) {
final InstrumentedAppender appender = new InstrumentedAppender(metricRegistry);
appender.setContext(loggerContext);
appender.start();
root.addAppender(appender);
}
private Logger configureLoggers(String name) {
final Logger root = loggerContext.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
loggerContext.reset();
final LevelChangePropagator propagator = new LevelChangePropagator();
propagator.setContext(loggerContext);
propagator.setResetJUL(true);
loggerContext.addListener(propagator);
root.setLevel(level);
final LevelFilterFactory<ILoggingEvent> levelFilterFactory = new ThresholdLevelFilterFactory();
final AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory = new AsyncLoggingEventAppenderFactory();
final LayoutFactory<ILoggingEvent> layoutFactory = new DropwizardLayoutFactory();
for (Map.Entry<String, JsonNode> entry : loggers.entrySet()) {
final Logger logger = loggerContext.getLogger(entry.getKey());
final JsonNode jsonNode = entry.getValue();
if (jsonNode.isTextual()) {
// Just a level as a string
logger.setLevel(Level.valueOf(jsonNode.asText()));
} else if (jsonNode.isObject()) {
// A level and an appender
final LoggerConfiguration configuration;
try {
configuration = Jackson.newObjectMapper().treeToValue(jsonNode, LoggerConfiguration.class);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException("Wrong format of logger '" + entry.getKey() + "'", e);
}
logger.setLevel(configuration.getLevel());
logger.setAdditive(configuration.isAdditive());
for (AppenderFactory<ILoggingEvent> appender : configuration.getAppenders()) {
logger.addAppender(appender.build(loggerContext, name, layoutFactory, levelFilterFactory, asyncAppenderFactory));
}
} else {
throw new IllegalArgumentException("Unsupported format of logger '" + entry.getKey() + "'");
}
}
return root;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("level", level)
.add("loggers", loggers)
.add("appenders", appenders)
.toString();
}
}
| apache-2.0 |
yahoo/pulsar | pulsar-client-1x-base/pulsar-client-1x/src/main/java/org/apache/pulsar/client/impl/v1/PulsarClientV1Impl.java | 6816 | /**
* 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.pulsar.client.impl.v1;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.apache.pulsar.client.api.ClientConfiguration;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.ConsumerConfiguration;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.ProducerConfiguration;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.Reader;
import org.apache.pulsar.client.api.ReaderConfiguration;
import org.apache.pulsar.client.impl.ProducerImpl;
import org.apache.pulsar.client.impl.PulsarClientImpl;
import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData;
import org.apache.pulsar.client.impl.conf.ProducerConfigurationData;
import org.apache.pulsar.client.impl.conf.ReaderConfigurationData;
import org.apache.pulsar.common.util.FutureUtil;
@SuppressWarnings("deprecation")
public class PulsarClientV1Impl implements PulsarClient {
private final PulsarClientImpl client;
public PulsarClientV1Impl(String serviceUrl, ClientConfiguration conf) throws PulsarClientException {
this.client = new PulsarClientImpl(conf.setServiceUrl(serviceUrl).getConfigurationData().clone());
}
@Override
public void close() throws PulsarClientException {
client.close();
}
@Override
public CompletableFuture<Void> closeAsync() {
return client.closeAsync();
}
@Override
public Producer createProducer(final String topic, final ProducerConfiguration conf) throws PulsarClientException {
if (conf == null) {
throw new PulsarClientException.InvalidConfigurationException("Invalid null configuration object");
}
try {
return createProducerAsync(topic, conf).get();
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof PulsarClientException) {
throw (PulsarClientException) t;
} else {
throw new PulsarClientException(t);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new PulsarClientException(e);
}
}
@Override
public Producer createProducer(String topic)
throws PulsarClientException {
return createProducer(topic, new ProducerConfiguration());
}
@Override
public CompletableFuture<Producer> createProducerAsync(final String topic, final ProducerConfiguration conf) {
ProducerConfigurationData confData = conf.getProducerConfigurationData().clone();
confData.setTopicName(topic);
return client.createProducerAsync(confData).thenApply(p -> new ProducerV1Impl((ProducerImpl<byte[]>) p));
}
@Override
public CompletableFuture<Producer> createProducerAsync(String topic) {
return createProducerAsync(topic, new ProducerConfiguration());
}
@Override
public Reader createReader(String topic, MessageId startMessageId, ReaderConfiguration conf)
throws PulsarClientException {
try {
return createReaderAsync(topic, startMessageId, conf).get();
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof PulsarClientException) {
throw (PulsarClientException) t;
} else {
throw new PulsarClientException(t);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new PulsarClientException(e);
}
}
@Override
public CompletableFuture<Reader> createReaderAsync(String topic, MessageId startMessageId,
ReaderConfiguration conf) {
ReaderConfigurationData<byte[]> confData = conf.getReaderConfigurationData().clone();
confData.setTopicName(topic);
confData.setStartMessageId(startMessageId);
return client.createReaderAsync(confData).thenApply(r -> new ReaderV1Impl(r));
}
@Override
public void shutdown() throws PulsarClientException {
client.shutdown();
}
@Override
public Consumer subscribe(String topic, String subscriptionName) throws PulsarClientException {
return subscribe(topic, subscriptionName, new ConsumerConfiguration());
}
@Override
public CompletableFuture<Consumer> subscribeAsync(final String topic, final String subscription,
final ConsumerConfiguration conf) {
if (conf == null) {
return FutureUtil.failedFuture(
new PulsarClientException.InvalidConfigurationException("Invalid null configuration"));
}
ConsumerConfigurationData<byte[]> confData = conf.getConfigurationData().clone();
confData.getTopicNames().add(topic);
confData.setSubscriptionName(subscription);
return client.subscribeAsync(confData).thenApply(c -> new ConsumerV1Impl(c));
}
@Override
public CompletableFuture<Consumer> subscribeAsync(String topic,
String subscriptionName) {
return subscribeAsync(topic, subscriptionName, new ConsumerConfiguration());
}
@Override
public Consumer subscribe(String topic, String subscription, ConsumerConfiguration conf)
throws PulsarClientException {
try {
return subscribeAsync(topic, subscription, conf).get();
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof PulsarClientException) {
throw (PulsarClientException) t;
} else {
throw new PulsarClientException(t);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new PulsarClientException(e);
}
}
}
| apache-2.0 |
puppetlabs/clj-http-client | src/java/com/puppetlabs/http/client/impl/Promise.java | 639 | package com.puppetlabs.http.client.impl;
import java.util.concurrent.CountDownLatch;
public class Promise<T> implements Deliverable<T> {
private final CountDownLatch latch;
private T value = null;
public Promise() {
latch = new CountDownLatch(1);
}
public synchronized void deliver(T t) {
if (value != null) {
throw new IllegalStateException("Attempting to deliver value to a promise that has already been realized!");
}
value = t;
latch.countDown();
}
public T deref() throws InterruptedException {
latch.await();
return value;
}
}
| apache-2.0 |
rareddy/olingo-odata4 | fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/AccountCollection.java | 1576 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.fit.proxy.staticservice.microsoft.test.odata.services.odatawcfservice.types;
// CHECKSTYLE:OFF (Maven checkstyle)
import java.util.Collection;
// CHECKSTYLE:ON (Maven checkstyle)
import org.apache.olingo.ext.proxy.api.AbstractTerm;
public interface AccountCollection
extends
org.apache.olingo.ext.proxy.api.StructuredCollectionQuery<AccountCollection>,
org.apache.olingo.ext.proxy.api.EntityCollection<Account, AccountCollection, AccountCollection> {
Operations operations();
interface Operations extends org.apache.olingo.ext.proxy.api.Operations {
// No additional methods needed for now.
}
Object getAnnotation(Class<? extends AbstractTerm> term);
Collection<Class<? extends AbstractTerm>> getAnnotationTerms();
}
| apache-2.0 |
charleso/intellij-haskforce | src/com/haskforce/parsing/srcExtsDatatypes/RPatOpTopType.java | 354 | package com.haskforce.parsing.srcExtsDatatypes;
/**
* data RPatOp l
* = RPStar l -- ^ @*@ = 0 or more
* | RPStarG l -- ^ @*!@ = 0 or more, greedy
* | RPPlus l -- ^ @+@ = 1 or more
* | RPPlusG l -- ^ @+!@ = 1 or more, greedy
* | RPOpt l -- ^ @?@ = 0 or 1
* | RPOptG l -- ^ @?!@ = 0 or 1, greedy
*/
public class RPatOpTopType {
}
| apache-2.0 |
testIT-WebTester/webtester2-core | webtester-core/src/main/java/info/novatec/testit/webtester/pagefragments/identification/ByProducers.java | 5465 | package info.novatec.testit.webtester.pagefragments.identification;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.openqa.selenium.By;
import lombok.experimental.UtilityClass;
import info.novatec.testit.webtester.pagefragments.annotations.IdentifyUsing;
import info.novatec.testit.webtester.pagefragments.identification.producers.ClassName;
import info.novatec.testit.webtester.pagefragments.identification.producers.CssSelector;
import info.novatec.testit.webtester.pagefragments.identification.producers.Id;
import info.novatec.testit.webtester.pagefragments.identification.producers.IdEndsWith;
import info.novatec.testit.webtester.pagefragments.identification.producers.IdStartsWith;
import info.novatec.testit.webtester.pagefragments.identification.producers.LinkText;
import info.novatec.testit.webtester.pagefragments.identification.producers.Name;
import info.novatec.testit.webtester.pagefragments.identification.producers.PartialLinkText;
import info.novatec.testit.webtester.pagefragments.identification.producers.TagName;
import info.novatec.testit.webtester.pagefragments.identification.producers.XPath;
/**
* This utility class offers factory methods for Selenium {@link By} instances.
*
* @see By
* @see ByProducer
* @see IdentifyUsing
* @since 2.0
*/
@UtilityClass
public class ByProducers {
private static final Map<Class<? extends ByProducer>, ByProducer> BY_PRODUCER_CACHE = new ConcurrentHashMap<>();
/**
* Creates a new {@link By} using {@link ClassName}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By className(String value) {
return createBy(ClassName.class, value);
}
/**
* Creates a new {@link By} using {@link CssSelector}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By css(String value) {
return createBy(CssSelector.class, value);
}
/**
* Creates a new {@link By} using {@link Id}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By id(String value) {
return createBy(Id.class, value);
}
/**
* Creates a new {@link By} using {@link IdStartsWith}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By idStartsWith(String value) {
return createBy(IdStartsWith.class, value);
}
/**
* Creates a new {@link By} using {@link IdEndsWith}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By idEndsWith(String value) {
return createBy(IdEndsWith.class, value);
}
/**
* Creates a new {@link By} using {@link Name}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By name(String value) {
return createBy(Name.class, value);
}
/**
* Creates a new {@link By} using {@link LinkText}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By linkText(String value) {
return createBy(LinkText.class, value);
}
/**
* Creates a new {@link By} using {@link PartialLinkText}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By partialLinkText(String value) {
return createBy(PartialLinkText.class, value);
}
/**
* Creates a new {@link By} using {@link TagName}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By tagName(String value) {
return createBy(TagName.class, value);
}
/**
* Creates a new {@link By} using {@link XPath}.
*
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By xPath(String value) {
return createBy(XPath.class, value);
}
/**
* Creates a new {@link By} from evaluating the given {@link IdentifyUsing} annotation.
*
* @param identifyUsing the annotation to evaluate
* @return the created {@link By}
* @since 2.0
*/
public static By createBy(IdentifyUsing identifyUsing) {
return createBy(identifyUsing.how(), identifyUsing.value());
}
/**
* Creates a new {@link By} using the given {@link ByProducers} class and {@code value}.
*
* @param producerClass the class to use
* @param value the value to use
* @return the created {@link By}
* @since 2.0
*/
public static By createBy(Class<? extends ByProducer> producerClass, String value) {
ByProducer producer = BY_PRODUCER_CACHE.computeIfAbsent(producerClass, k -> createNewInstanceOf(producerClass));
return producer.createBy(value);
}
private static ByProducer createNewInstanceOf(Class<? extends ByProducer> producerClass) {
try {
return producerClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
String message = "unable to create instance of " + producerClass;
throw new InvalidByProducerException(message, e);
}
}
}
| apache-2.0 |
DariusX/camel | core/camel-core/src/test/java/org/apache/camel/processor/BeanSingletonTest.java | 3791 | /*
* 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.processor;
import javax.naming.Context;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spi.Registry;
import org.apache.camel.support.DefaultRegistry;
import org.apache.camel.support.jndi.JndiBeanRepository;
import org.junit.Test;
public class BeanSingletonTest extends ContextTestSupport {
private Context context;
private Registry registry;
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:noCache").to("bean:something?scope=Prototype");
from("direct:cached").to("bean:something?scope=Singleton");
}
};
}
@Override
protected Registry createRegistry() throws Exception {
context = createJndiContext();
context.bind("something", new MyBean());
registry = new DefaultRegistry(new JndiBeanRepository(context));
return registry;
}
@Test
public void testFreshBeanInContext() throws Exception {
// Just make sure the bean processor doesn't work if the cached is false
MyBean originalInstance = registry.lookupByNameAndType("something", MyBean.class);
template.sendBody("direct:noCache", null);
context.unbind("something");
context.bind("something", new MyBean());
// Make sure we can get the object from the registry
assertNotSame(registry.lookupByName("something"), originalInstance);
template.sendBody("direct:noCache", null);
}
@Test
public void testBeanWithSingleton() throws Exception {
// Just make sure the bean processor doesn't work if the cached is false
MyBean originalInstance = registry.lookupByNameAndType("something", MyBean.class);
template.sendBody("direct:cached", null);
context.unbind("something");
context.bind("something", new MyBean());
// Make sure we can get the object from the registry
assertNotSame(registry.lookupByName("something"), originalInstance);
try {
template.sendBody("direct:cached", null);
fail("The IllegalStateException is expected");
} catch (CamelExecutionException ex) {
assertTrue("IllegalStateException is expected!", ex.getCause() instanceof IllegalStateException);
assertEquals("This bean is not supported to be invoked again!", ex.getCause().getMessage());
}
}
public static class MyBean {
private boolean invoked;
public void doSomething(Exchange exchange) throws Exception {
if (invoked) {
throw new IllegalStateException("This bean is not supported to be invoked again!");
} else {
invoked = true;
}
}
}
}
| apache-2.0 |
apache/groovy | subprojects/groovy-nio/src/main/java/org/apache/groovy/nio/runtime/WritablePath.java | 5283 | /*
* 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.groovy.nio.runtime;
import groovy.lang.Writable;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Iterator;
/**
* A Writable Path.
*/
public class WritablePath implements Path, Writable {
private final String encoding;
private final Path delegate;
public WritablePath(final Path delegate) {
this(delegate, null);
}
public WritablePath(final Path delegate, final String encoding) {
this.encoding = encoding;
this.delegate = delegate;
}
@Override
public Writer writeTo(final Writer out) throws IOException {
try (Reader reader = (this.encoding == null)
? new InputStreamReader(Files.newInputStream(this))
: new InputStreamReader(Files.newInputStream(this), Charset.forName(this.encoding))) {
int c = reader.read();
while (c != -1) {
out.write(c);
c = reader.read();
}
}
return out;
}
@Override
public FileSystem getFileSystem() {
return delegate.getFileSystem();
}
@Override
public boolean isAbsolute() {
return delegate.isAbsolute();
}
@Override
public Path getRoot() {
return delegate.getRoot();
}
@Override
public Path getFileName() {
return delegate.getFileName();
}
@Override
public Path getParent() {
return delegate.getParent();
}
@Override
public int getNameCount() {
return delegate.getNameCount();
}
@Override
public Path getName(int index) {
return delegate.getName(index);
}
@Override
public Path subpath(int beginIndex, int endIndex) {
return delegate.subpath(beginIndex, endIndex);
}
@Override
public boolean startsWith(Path other) {
return delegate.startsWith(other);
}
@Override
public boolean startsWith(String other) {
return delegate.startsWith(other);
}
@Override
public boolean endsWith(Path other) {
return delegate.endsWith(other);
}
@Override
public boolean endsWith(String other) {
return delegate.endsWith(other);
}
@Override
public Path normalize() {
return delegate.normalize();
}
@Override
public Path resolve(Path other) {
return delegate.resolve(other);
}
@Override
public Path resolve(String other) {
return delegate.resolve(other);
}
@Override
public Path resolveSibling(Path other) {
return delegate.resolveSibling(other);
}
@Override
public Path resolveSibling(String other) {
return delegate.resolveSibling(other);
}
@Override
public Path relativize(Path other) {
return delegate.relativize(other);
}
@Override
public URI toUri() {
return delegate.toUri();
}
@Override
public Path toAbsolutePath() {
return delegate.toAbsolutePath();
}
@Override
public Path toRealPath(LinkOption... options) throws IOException {
return delegate.toRealPath(options);
}
@Override
public File toFile() {
return delegate.toFile();
}
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException {
return delegate.register(watcher, events, modifiers);
}
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) throws IOException {
return delegate.register(watcher, events);
}
@Override
public Iterator<Path> iterator() {
return delegate.iterator();
}
@Override
public int compareTo(Path other) {
return delegate.compareTo(other);
}
@Override
public boolean equals(Object other) {
return delegate.equals(other);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public String toString() {
return delegate.toString();
}
}
| apache-2.0 |
apache/maven | maven-model-transform/src/main/java/org/apache/maven/model/transform/CiFriendlyXMLFilter.java | 2610 | package org.apache.maven.model.transform;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.List;
import java.util.function.Function;
import org.apache.maven.model.transform.pull.NodeBufferingParser;
import org.codehaus.plexus.util.xml.pull.XmlPullParser;
/**
* Resolves all ci-friendly properties occurrences between version-tags
*
* @author Robert Scholte
* @author Guillaume Nodet
* @since 4.0.0
*/
class CiFriendlyXMLFilter
extends NodeBufferingParser
{
private final boolean replace;
private Function<String, String> replaceChain = Function.identity();
CiFriendlyXMLFilter( XmlPullParser xmlPullParser, boolean replace )
{
super( xmlPullParser, "version" );
this.replace = replace;
}
public CiFriendlyXMLFilter setChangelist( String changelist )
{
replaceChain = replaceChain.andThen( t -> t.replace( "${changelist}", changelist ) );
return this;
}
public CiFriendlyXMLFilter setRevision( String revision )
{
replaceChain = replaceChain.andThen( t -> t.replace( "${revision}", revision ) );
return this;
}
public CiFriendlyXMLFilter setSha1( String sha1 )
{
replaceChain = replaceChain.andThen( t -> t.replace( "${sha1}", sha1 ) );
return this;
}
/**
* @return {@code true} is any of the ci properties is set, otherwise {@code false}
*/
public boolean isSet()
{
return !replaceChain.equals( Function.identity() );
}
@Override
protected void process( List<Event> buffer )
{
for ( Event event : buffer )
{
if ( event.event == TEXT && replace && event.text.contains( "${" ) )
{
event.text = replaceChain.apply( event.text );
}
pushEvent( event );
}
}
}
| apache-2.0 |
Darsstar/framework | compatibility-server/src/main/java/com/vaadin/v7/data/util/converter/StringToIntegerConverter.java | 2831 | /*
* 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.v7.data.util.converter;
import java.text.NumberFormat;
import java.util.Locale;
/**
* A converter that converts from {@link String} to {@link Integer} and back.
* Uses the given locale and a {@link NumberFormat} instance for formatting and
* parsing.
* <p>
* Override and overwrite {@link #getFormat(Locale)} to use a different format.
* </p>
*
* @author Vaadin Ltd
* @since 7.0
*/
@Deprecated
public class StringToIntegerConverter
extends AbstractStringToNumberConverter<Integer> {
/**
* Returns the format used by
* {@link #convertToPresentation(Integer, Class, Locale)} and
* {@link #convertToModel(String, Class, Locale)}.
*
* @param locale
* The locale to use
* @return A NumberFormat instance
*/
@Override
protected NumberFormat getFormat(Locale locale) {
if (locale == null) {
locale = Locale.getDefault();
}
return NumberFormat.getIntegerInstance(locale);
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.data.util.converter.Converter#convertToModel(java.lang.Object,
* java.lang.Class, java.util.Locale)
*/
@Override
public Integer convertToModel(String value,
Class<? extends Integer> targetType, Locale locale)
throws ConversionException {
Number n = convertToNumber(value, targetType, locale);
if (n == null) {
return null;
}
int intValue = n.intValue();
if (intValue == n.longValue()) {
// If the value of n is outside the range of long, the return value
// of longValue() is either Long.MIN_VALUE or Long.MAX_VALUE. The
// above comparison promotes int to long and thus does not need to
// consider wrap-around.
return intValue;
}
throw new ConversionException("Could not convert '" + value + "' to "
+ Integer.class.getName() + ": value out of range");
}
/*
* (non-Javadoc)
*
* @see com.vaadin.data.util.converter.Converter#getModelType()
*/
@Override
public Class<Integer> getModelType() {
return Integer.class;
}
}
| apache-2.0 |
NASA-Tournament-Lab/CoECI-CMS-Healthcare-Fraud-Prevention | hub/src/java/main/com/hfpp/network/hub/services/LookupService.java | 741 | /*
* Copyright (C) 2013 TopCoder Inc., All Rights Reserved.
*/
package com.hfpp.network.hub.services;
import java.util.List;
import com.hfpp.network.models.Role;
/**
* <p>
* The LookupService is used to retrieve lookup entities.
* </p>
*
* <p>
* <strong>Thread Safety: </strong> Implementations need to be effectively thread safe.
* </p>
*
* @author flying2hk, sparemax
* @version 1.0
*/
public interface LookupService {
/**
* This method is used to get all roles.
*
* @return all roles, empty list will be returned if no roles.
*
* @throws NetworkHubServiceException
* if any other error occurred
*/
public List<Role> getAllRoles() throws NetworkHubServiceException;
}
| apache-2.0 |
freeVM/freeVM | enhanced/java/classlib/modules/luni/src/test/api/common/org/apache/harmony/luni/tests/java/util/LocaleTest.java | 14037 | /*
* 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.harmony.luni.tests.java.util;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public class LocaleTest extends junit.framework.TestCase {
Locale testLocale;
Locale l;
Locale defaultLocale;
/**
* @tests java.util.Locale#Locale(java.lang.String, java.lang.String)
*/
public void test_ConstructorLjava_lang_StringLjava_lang_String() {
// Test for method java.util.Locale(java.lang.String, java.lang.String)
Locale x = new Locale("xx", "CV");
assertTrue("Failed to create Locale", x.getCountry().equals("CV")
&& x.getVariant().equals(""));
}
/**
* @tests java.util.Locale#Locale(java.lang.String, java.lang.String,
* java.lang.String)
*/
public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() {
// Test for method java.util.Locale(java.lang.String, java.lang.String,
// java.lang.String)
Locale x = new Locale("xx", "CV", "ZZ");
assertTrue("Failed to create Locale", x.getLanguage().equals("xx")
&& (x.getCountry().equals("CV") && x.getVariant().equals("ZZ")));
try {
new Locale(null, "CV", "ZZ");
fail("expected NullPointerException with 1st parameter == null");
} catch(NullPointerException e) {
}
try {
new Locale("xx", null, "ZZ");
fail("expected NullPointerException with 2nd parameter == null");
} catch(NullPointerException e) {
}
try {
new Locale("xx", "CV", null);
fail("expected NullPointerException with 3rd parameter == null");
} catch(NullPointerException e) {
}
}
/**
* @tests java.util.Locale#clone()
*/
public void test_clone() {
// Test for method java.lang.Object java.util.Locale.clone()
assertTrue("Clone failed", l.clone().equals(l));
}
/**
* @tests java.util.Locale#equals(java.lang.Object)
*/
public void test_equalsLjava_lang_Object() {
// Test for method boolean java.util.Locale.equals(java.lang.Object)
Locale l2 = new Locale("en", "CA", "WIN32");
assertTrue("Same object returned false", testLocale.equals(testLocale));
assertTrue("Same values returned false", testLocale.equals(l2));
assertTrue("Different locales returned true", !testLocale.equals(l));
}
/**
* @tests java.util.Locale#getAvailableLocales()
*/
public void test_getAvailableLocales() {
// Test for method java.util.Locale []
// java.util.Locale.getAvailableLocales()
// Assumes there will generally be about 100+ available locales...
Locale[] locales = Locale.getAvailableLocales();
assertTrue("Wrong number of locales: ", locales.length > 100);
// regression test for HARMONY-1514
// HashSet can filter duplicate locales
Set<Locale> localesSet = new HashSet<Locale>(Arrays.asList(locales));
// Non-bug difference for HARMONY-5442
assertTrue(localesSet.size() <= locales.length);
}
/**
* @tests java.util.Locale#getCountry()
*/
public void test_getCountry() {
// Test for method java.lang.String java.util.Locale.getCountry()
assertTrue("Returned incorrect country: " + testLocale.getCountry(),
testLocale.getCountry().equals("CA"));
}
/**
* @tests java.util.Locale#getDefault()
*/
public void test_getDefault() {
// Test for method java.util.Locale java.util.Locale.getDefault()
assertTrue("returns copy", Locale.getDefault() == Locale.getDefault());
Locale org = Locale.getDefault();
Locale.setDefault(l);
Locale x = Locale.getDefault();
Locale.setDefault(org);
assertEquals("Failed to get locale", "fr_CA_WIN32", x.toString());
}
/**
* @tests java.util.Locale#getDisplayCountry()
*/
public void test_getDisplayCountry() {
// Test for method java.lang.String java.util.Locale.getDisplayCountry()
assertTrue("Returned incorrect country: "
+ testLocale.getDisplayCountry(), testLocale
.getDisplayCountry().equals("Canada"));
// Regression for Harmony-1146
// Non-bug difference for HARMONY-5442
Locale l_countryCD = new Locale("", "CD"); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Congo - Kinshasa", //$NON-NLS-1$
l_countryCD.getDisplayCountry());
}
/**
* @tests java.util.Locale#getDisplayCountry(java.util.Locale)
*/
public void test_getDisplayCountryLjava_util_Locale() {
// Test for method java.lang.String
// java.util.Locale.getDisplayCountry(java.util.Locale)
assertEquals("Returned incorrect country", "Italie", Locale.ITALY
.getDisplayCountry(l));
}
/**
* @tests java.util.Locale#getDisplayLanguage()
*/
public void test_getDisplayLanguage() {
// Test for method java.lang.String
// java.util.Locale.getDisplayLanguage()
assertTrue("Returned incorrect language: "
+ testLocale.getDisplayLanguage(), testLocale
.getDisplayLanguage().equals("English"));
// Regression for Harmony-1146
Locale l_languageAE = new Locale("ae", ""); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Avestan", l_languageAE.getDisplayLanguage()); //$NON-NLS-1$
// Regression for HARMONY-4402
Locale defaultLocale = Locale.getDefault();
try {
Locale locale = new Locale("no", "NO");
Locale.setDefault(locale);
assertEquals("norsk", locale.getDisplayLanguage()); //$NON-NLS-1$
} finally {
Locale.setDefault(defaultLocale);
}
}
/**
* @tests java.util.Locale#getDisplayLanguage(java.util.Locale)
*/
public void test_getDisplayLanguageLjava_util_Locale() {
// Test for method java.lang.String
// java.util.Locale.getDisplayLanguage(java.util.Locale)
assertTrue("Returned incorrect language: "
+ testLocale.getDisplayLanguage(l), testLocale
.getDisplayLanguage(l).equals("anglais"));
}
/**
* @tests java.util.Locale#getDisplayName()
*/
public void test_getDisplayName() {
// Test for method java.lang.String java.util.Locale.getDisplayName()
assertTrue("Returned incorrect name: " + testLocale.getDisplayName(),
testLocale.getDisplayName().equals("English (Canada,WIN32)"));
}
/**
* @tests java.util.Locale#getDisplayName(java.util.Locale)
*/
public void test_getDisplayNameLjava_util_Locale() {
// Test for method java.lang.String
// java.util.Locale.getDisplayName(java.util.Locale)
assertTrue("Returned incorrect name: " + testLocale.getDisplayName(l),
testLocale.getDisplayName(l).equals("anglais (Canada,WIN32)"));
}
/**
* @tests java.util.Locale#getDisplayVariant()
*/
public void test_getDisplayVariant() {
// Test for method java.lang.String java.util.Locale.getDisplayVariant()
assertTrue("Returned incorrect variant: "
+ testLocale.getDisplayVariant(), testLocale
.getDisplayVariant().equals("WIN32"));
}
/**
* @tests java.util.Locale#getDisplayVariant(java.util.Locale)
*/
public void test_getDisplayVariantLjava_util_Locale() {
// Test for method java.lang.String
// java.util.Locale.getDisplayVariant(java.util.Locale)
assertTrue("Returned incorrect variant: "
+ testLocale.getDisplayVariant(l), testLocale
.getDisplayVariant(l).equals("WIN32"));
}
/**
* @tests java.util.Locale#getISO3Country()
*/
public void test_getISO3Country() {
// Test for method java.lang.String java.util.Locale.getISO3Country()
assertTrue("Returned incorrect ISO3 country: "
+ testLocale.getISO3Country(), testLocale.getISO3Country()
.equals("CAN"));
Locale l = new Locale("", "CD");
assertEquals("COD", l.getISO3Country());
}
/**
* @tests java.util.Locale#getISO3Language()
*/
public void test_getISO3Language() {
// Test for method java.lang.String java.util.Locale.getISO3Language()
assertTrue("Returned incorrect ISO3 language: "
+ testLocale.getISO3Language(), testLocale.getISO3Language()
.equals("eng"));
Locale l = new Locale("ae");
assertEquals("ave", l.getISO3Language());
// Regression for Harmony-1146
// Non-bug difference for HARMONY-5442
Locale l_CountryCS = new Locale("", "CS"); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("SCG", l_CountryCS.getISO3Country()); //$NON-NLS-1$
// Regression for Harmony-1129
l = new Locale("ak", ""); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("aka", l.getISO3Language()); //$NON-NLS-1$
}
/**
* @tests java.util.Locale#getISOCountries()
*/
public void test_getISOCountries() {
// Test for method java.lang.String []
// java.util.Locale.getISOCountries()
// Assumes all countries are 2 digits, and that there will always be
// 230 countries on the list...
String[] isoCountries = Locale.getISOCountries();
int length = isoCountries.length;
int familiarCount = 0;
for (int i = 0; i < length; i++) {
if (isoCountries[i].length() != 2) {
fail("Wrong format for ISOCountries.");
}
if (isoCountries[i].equals("CA") || isoCountries[i].equals("BB")
|| isoCountries[i].equals("US")
|| isoCountries[i].equals("KR"))
familiarCount++;
}
assertTrue("ISOCountries missing.", familiarCount == 4 && length > 230);
}
/**
* @tests java.util.Locale#getISOLanguages()
*/
public void test_getISOLanguages() {
// Test for method java.lang.String []
// java.util.Locale.getISOLanguages()
// Assumes always at least 131 ISOlanguages...
String[] isoLang = Locale.getISOLanguages();
int length = isoLang.length;
// Non-bug difference for HARMONY-5442
assertTrue(isoLang[length / 2].length() == 3);
assertTrue(isoLang[length / 2].toLowerCase().equals(isoLang[length / 2]));
assertTrue("Wrong number of ISOLanguages.", length > 130);
}
/**
* @tests java.util.Locale#getLanguage()
*/
public void test_getLanguage() {
// Test for method java.lang.String java.util.Locale.getLanguage()
assertTrue("Returned incorrect language: " + testLocale.getLanguage(),
testLocale.getLanguage().equals("en"));
}
/**
* @tests java.util.Locale#getVariant()
*/
public void test_getVariant() {
// Test for method java.lang.String java.util.Locale.getVariant()
assertTrue("Returned incorrect variant: " + testLocale.getVariant(),
testLocale.getVariant().equals("WIN32"));
}
/**
* @tests java.util.Locale#setDefault(java.util.Locale)
*/
public void test_setDefaultLjava_util_Locale() {
// Test for method void java.util.Locale.setDefault(java.util.Locale)
Locale org = Locale.getDefault();
Locale.setDefault(l);
Locale x = Locale.getDefault();
Locale.setDefault(org);
assertEquals("Failed to set locale", "fr_CA_WIN32", x.toString());
Locale.setDefault(new Locale("tr", ""));
String res1 = "\u0069".toUpperCase();
String res2 = "\u0049".toLowerCase();
Locale.setDefault(org);
assertEquals("Wrong toUppercase conversion", "\u0130", res1);
assertEquals("Wrong toLowercase conversion", "\u0131", res2);
}
/**
* @tests java.util.Locale#toString()
*/
public void test_toString() {
// Test for method java.lang.String java.util.Locale.toString()
assertEquals("Returned incorrect string representation", "en_CA_WIN32", testLocale
.toString());
Locale l = new Locale("en", "");
assertEquals("Wrong representation 1", "en", l.toString());
l = new Locale("", "CA");
assertEquals("Wrong representation 2", "_CA", l.toString());
// Non-bug difference for HARMONY-5442
l = new Locale("", "CA", "var");
assertEquals("Wrong representation 2.5", "_CA_var", l.toString());
l = new Locale("en", "", "WIN");
assertEquals("Wrong representation 4", "en__WIN", l.toString());
l = new Locale("en", "CA");
assertEquals("Wrong representation 6", "en_CA", l.toString());
l = new Locale("en", "CA", "VAR");
assertEquals("Wrong representation 7", "en_CA_VAR", l.toString());
l = new Locale("", "", "var");
assertEquals("Wrong representation 8", "", l.toString());
}
// Regression Test for HARMONY-2953
public void test_getISO() {
Locale locale = new Locale("an");
assertEquals("arg", locale.getISO3Language());
locale = new Locale("PS");
assertEquals("pus", locale.getISO3Language());
List<String> languages = Arrays.asList(Locale.getISOLanguages());
assertTrue(languages.contains("ak"));
// Non-bug difference for HARMONY-5442
List<String> countries = Arrays.asList(Locale.getISOCountries());
assertFalse(countries.contains("CS"));
}
/**
* Sets up the fixture, for example, open a network connection. This method
* is called before a test is executed.
*/
protected void setUp() {
defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.US);
testLocale = new Locale("en", "CA", "WIN32");
l = new Locale("fr", "CA", "WIN32");
}
/**
* Tears down the fixture, for example, close a network connection. This
* method is called after a test is executed.
*/
protected void tearDown() {
Locale.setDefault(defaultLocale);
}
}
| apache-2.0 |
mehtabsinghmann/resilience4j | resilience4j-spring-boot2/src/main/java/io/github/resilience4j/circuitbreaker/monitoring/endpoint/CircuitBreakerEndpointResponse.java | 570 | package io.github.resilience4j.circuitbreaker.monitoring.endpoint;
import java.util.List;
public class CircuitBreakerEndpointResponse {
private List<String> circuitBreakers;
public CircuitBreakerEndpointResponse(){
}
public CircuitBreakerEndpointResponse(List<String> circuitBreakers){
this.circuitBreakers = circuitBreakers;
}
public List<String> getCircuitBreakers() {
return circuitBreakers;
}
public void setCircuitBreakers(List<String> circuitBreakers) {
this.circuitBreakers = circuitBreakers;
}
}
| apache-2.0 |
cbeams-archive/spring-framework-2.5.x | src/org/springframework/orm/jdo/JdoUsageException.java | 1307 | /*
* Copyright 2002-2005 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.orm.jdo;
import javax.jdo.JDOFatalUserException;
import javax.jdo.JDOUserException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
/**
* JDO-specific subclass of InvalidDataAccessApiUsageException.
* Converts JDO's JDOUserException and JDOFatalUserException.
*
* @author Juergen Hoeller
* @since 03.06.2003
* @see PersistenceManagerFactoryUtils#convertJdoAccessException
*/
public class JdoUsageException extends InvalidDataAccessApiUsageException {
public JdoUsageException(JDOUserException ex) {
super(ex.getMessage(), ex);
}
public JdoUsageException(JDOFatalUserException ex) {
super(ex.getMessage(), ex);
}
}
| apache-2.0 |
Darsstar/framework | compatibility-client/src/main/java/com/vaadin/v7/client/ui/calendar/schedule/DateCellDayEvent.java | 22024 | /*
* 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.v7.client.ui.calendar.schedule;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.vaadin.client.WidgetUtil;
import com.vaadin.v7.shared.ui.calendar.DateConstants;
/**
* Internally used by the calendar.
*
* @since 7.1
*/
public class DateCellDayEvent extends FocusableHTML
implements MouseDownHandler, MouseUpHandler, MouseMoveHandler,
KeyDownHandler, ContextMenuHandler, HasTooltipKey {
private final DateCell dateCell;
private Element caption = null;
private final Element eventContent;
private CalendarEvent calendarEvent = null;
private HandlerRegistration moveRegistration;
private int startY = -1;
private int startX = -1;
private String moveWidth;
public static final int HALF_HOUR_IN_MILLI_SECONDS = 1800 * 1000;
private Date startDatetimeFrom;
private Date startDatetimeTo;
private boolean mouseMoveStarted;
private int top;
private int startYrelative;
private int startXrelative;
private boolean disabled;
private final WeekGrid weekGrid;
private Element topResizeBar;
private Element bottomResizeBar;
private Element clickTarget;
private final Integer eventIndex;
private int slotHeight;
private final List<HandlerRegistration> handlers;
private boolean mouseMoveCanceled;
public DateCellDayEvent(DateCell dateCell, WeekGrid parent,
CalendarEvent event) {
super();
this.dateCell = dateCell;
handlers = new LinkedList<HandlerRegistration>();
setStylePrimaryName("v-calendar-event");
setCalendarEvent(event);
weekGrid = parent;
Style s = getElement().getStyle();
if (!event.getStyleName().isEmpty()) {
addStyleDependentName(event.getStyleName());
}
s.setPosition(Position.ABSOLUTE);
caption = DOM.createDiv();
caption.addClassName("v-calendar-event-caption");
getElement().appendChild(caption);
eventContent = DOM.createDiv();
eventContent.addClassName("v-calendar-event-content");
getElement().appendChild(eventContent);
if (weekGrid.getCalendar().isEventResizeAllowed()) {
topResizeBar = DOM.createDiv();
bottomResizeBar = DOM.createDiv();
topResizeBar.addClassName("v-calendar-event-resizetop");
bottomResizeBar.addClassName("v-calendar-event-resizebottom");
getElement().appendChild(topResizeBar);
getElement().appendChild(bottomResizeBar);
}
eventIndex = event.getIndex();
}
@Override
protected void onAttach() {
super.onAttach();
handlers.add(addMouseDownHandler(this));
handlers.add(addMouseUpHandler(this));
handlers.add(addKeyDownHandler(this));
handlers.add(addDomHandler(this, ContextMenuEvent.getType()));
}
@Override
protected void onDetach() {
for (HandlerRegistration handler : handlers) {
handler.removeHandler();
}
handlers.clear();
super.onDetach();
}
public void setSlotHeightInPX(int slotHeight) {
this.slotHeight = slotHeight;
}
public void updatePosition(long startFromMinutes, long durationInMinutes) {
if (startFromMinutes < 0) {
startFromMinutes = 0;
}
top = weekGrid.getPixelTopFor((int) startFromMinutes);
getElement().getStyle().setTop(top, Unit.PX);
if (durationInMinutes > 0) {
int heightMinutes = weekGrid.getPixelLengthFor(
(int) startFromMinutes, (int) durationInMinutes);
setHeight(heightMinutes);
} else {
setHeight(-1);
}
boolean multiRowCaption = (durationInMinutes > 30);
updateCaptions(multiRowCaption);
}
public int getTop() {
return top;
}
public void setMoveWidth(int width) {
moveWidth = width + "px";
}
public void setHeight(int h) {
if (h == -1) {
getElement().getStyle().setProperty("height", "");
eventContent.getStyle().setProperty("height", "");
} else {
getElement().getStyle().setHeight(h, Unit.PX);
// FIXME measure the border height (2px) from the DOM
eventContent.getStyle().setHeight(h - 2, Unit.PX);
}
}
/**
* @param bigMode
* If false, event is so small that caption must be in time-row
*/
private void updateCaptions(boolean bigMode) {
String innerHtml;
String timeAsText = calendarEvent.getTimeAsText();
String htmlOrText;
if (dateCell.weekgrid.getCalendar().isEventCaptionAsHtml()) {
htmlOrText = calendarEvent.getCaption();
} else {
htmlOrText = WidgetUtil.escapeHTML(calendarEvent.getCaption());
}
if (bigMode) {
innerHtml = "<span>" + timeAsText + "</span><br />" + htmlOrText;
} else {
innerHtml = "<span>" + timeAsText + "<span>:</span></span> "
+ htmlOrText;
}
caption.setInnerHTML(innerHtml);
eventContent.setInnerHTML("");
}
@Override
public void onKeyDown(KeyDownEvent event) {
int keycode = event.getNativeEvent().getKeyCode();
if (keycode == KeyCodes.KEY_ESCAPE && mouseMoveStarted) {
cancelMouseMove();
}
}
@Override
public void onMouseDown(MouseDownEvent event) {
startX = event.getClientX();
startY = event.getClientY();
if (isDisabled()
|| event.getNativeButton() != NativeEvent.BUTTON_LEFT) {
return;
}
clickTarget = Element.as(event.getNativeEvent().getEventTarget());
mouseMoveCanceled = false;
if (weekGrid.getCalendar().isEventMoveAllowed()
|| clickTargetsResize()) {
moveRegistration = addMouseMoveHandler(this);
setFocus(true);
try {
startYrelative = (int) ((double) event.getRelativeY(caption)
% slotHeight);
startXrelative = (event.getRelativeX(weekGrid.getElement())
- weekGrid.timebar.getOffsetWidth())
% getDateCellWidth();
} catch (Exception e) {
GWT.log("Exception calculating relative start position", e);
}
mouseMoveStarted = false;
Style s = getElement().getStyle();
s.setZIndex(1000);
startDatetimeFrom = (Date) calendarEvent.getStartTime().clone();
startDatetimeTo = (Date) calendarEvent.getEndTime().clone();
Event.setCapture(getElement());
}
// make sure the right cursor is always displayed
if (clickTargetsResize()) {
addGlobalResizeStyle();
}
/*
* We need to stop the event propagation or else the WeekGrid range
* select will kick in
*/
event.stopPropagation();
event.preventDefault();
}
@Override
public void onMouseUp(MouseUpEvent event) {
if (mouseMoveCanceled
|| event.getNativeButton() != NativeEvent.BUTTON_LEFT) {
return;
}
Event.releaseCapture(getElement());
setFocus(false);
if (moveRegistration != null) {
moveRegistration.removeHandler();
moveRegistration = null;
}
int endX = event.getClientX();
int endY = event.getClientY();
int xDiff = 0, yDiff = 0;
if (startX != -1 && startY != -1) {
// Drag started
xDiff = startX - endX;
yDiff = startY - endY;
}
startX = -1;
startY = -1;
mouseMoveStarted = false;
Style s = getElement().getStyle();
s.setZIndex(1);
if (!clickTargetsResize()) {
// check if mouse has moved over threshold of 3 pixels
boolean mouseMoved = (xDiff < -3 || xDiff > 3 || yDiff < -3
|| yDiff > 3);
if (!weekGrid.getCalendar().isDisabledOrReadOnly() && mouseMoved) {
// Event Move:
// - calendar must be enabled
// - calendar must not be in read-only mode
weekGrid.eventMoved(this);
} else if (!weekGrid.getCalendar().isDisabled()) {
// Event Click:
// - calendar must be enabled (read-only is allowed)
EventTarget et = event.getNativeEvent().getEventTarget();
Element e = Element.as(et);
if (e == caption || e == eventContent
|| e.getParentElement() == caption) {
if (weekGrid.getCalendar()
.getEventClickListener() != null) {
weekGrid.getCalendar().getEventClickListener()
.eventClick(calendarEvent);
}
}
}
} else { // click targeted resize bar
removeGlobalResizeStyle();
if (weekGrid.getCalendar().getEventResizeListener() != null) {
weekGrid.getCalendar().getEventResizeListener()
.eventResized(calendarEvent);
}
dateCell.recalculateEventWidths();
}
}
@Override
@SuppressWarnings("deprecation")
public void onMouseMove(MouseMoveEvent event) {
if (startY < 0 && startX < 0) {
return;
}
if (isDisabled()) {
Event.releaseCapture(getElement());
mouseMoveStarted = false;
startY = -1;
startX = -1;
removeGlobalResizeStyle();
return;
}
int currentY = event.getClientY();
int currentX = event.getClientX();
int moveY = (currentY - startY);
int moveX = (currentX - startX);
if ((moveY < 5 && moveY > -6) && (moveX < 5 && moveX > -6)) {
return;
}
if (!mouseMoveStarted) {
setWidth(moveWidth);
getElement().getStyle().setMarginLeft(0, Unit.PX);
mouseMoveStarted = true;
}
HorizontalPanel parent = (HorizontalPanel) getParent().getParent();
int relativeX = event.getRelativeX(parent.getElement())
- weekGrid.timebar.getOffsetWidth();
int halfHourDiff = 0;
if (moveY > 0) {
halfHourDiff = (startYrelative + moveY) / slotHeight;
} else {
halfHourDiff = (moveY - startYrelative) / slotHeight;
}
int dateCellWidth = getDateCellWidth();
long dayDiff = 0;
if (moveX >= 0) {
dayDiff = (startXrelative + moveX) / dateCellWidth;
} else {
dayDiff = (moveX - (dateCellWidth - startXrelative))
/ dateCellWidth;
}
int dayOffset = relativeX / dateCellWidth;
// sanity check for right side overflow
int dateCellCount = weekGrid.getDateCellCount();
if (dayOffset >= dateCellCount) {
dayOffset--;
dayDiff--;
}
int dayOffsetPx = calculateDateCellOffsetPx(dayOffset)
+ weekGrid.timebar.getOffsetWidth();
GWT.log("DateCellWidth: " + dateCellWidth + " dayDiff: " + dayDiff
+ " dayOffset: " + dayOffset + " dayOffsetPx: " + dayOffsetPx
+ " startXrelative: " + startXrelative + " moveX: " + moveX);
if (relativeX < 0 || relativeX >= getDatesWidth()) {
return;
}
Style s = getElement().getStyle();
Date from = calendarEvent.getStartTime();
Date to = calendarEvent.getEndTime();
long duration = to.getTime() - from.getTime();
if (!clickTargetsResize()
&& weekGrid.getCalendar().isEventMoveAllowed()) {
long daysMs = dayDiff * DateConstants.DAYINMILLIS;
from.setTime(startDatetimeFrom.getTime() + daysMs);
from.setTime(from.getTime()
+ ((long) HALF_HOUR_IN_MILLI_SECONDS * halfHourDiff));
to.setTime((from.getTime() + duration));
calendarEvent.setStartTime(from);
calendarEvent.setEndTime(to);
calendarEvent.setStart(new Date(from.getTime()));
calendarEvent.setEnd(new Date(to.getTime()));
// Set new position for the event
long startFromMinutes = (from.getHours() * 60) + from.getMinutes();
long range = calendarEvent.getRangeInMinutes();
startFromMinutes = calculateStartFromMinute(startFromMinutes, from,
to, dayOffsetPx);
if (startFromMinutes < 0) {
range += startFromMinutes;
}
updatePosition(startFromMinutes, range);
s.setLeft(dayOffsetPx, Unit.PX);
if (weekGrid.getDateCellWidths() != null) {
s.setWidth(weekGrid.getDateCellWidths()[dayOffset], Unit.PX);
} else {
setWidth(moveWidth);
}
} else if (clickTarget == topResizeBar) {
long oldStartTime = startDatetimeFrom.getTime();
long newStartTime = oldStartTime
+ ((long) HALF_HOUR_IN_MILLI_SECONDS * halfHourDiff);
if (!isTimeRangeTooSmall(newStartTime, startDatetimeTo.getTime())) {
newStartTime = startDatetimeTo.getTime() - getMinTimeRange();
}
from.setTime(newStartTime);
calendarEvent.setStartTime(from);
calendarEvent.setStart(new Date(from.getTime()));
// Set new position for the event
long startFromMinutes = (from.getHours() * 60) + from.getMinutes();
long range = calendarEvent.getRangeInMinutes();
updatePosition(startFromMinutes, range);
} else if (clickTarget == bottomResizeBar) {
long oldEndTime = startDatetimeTo.getTime();
long newEndTime = oldEndTime
+ ((long) HALF_HOUR_IN_MILLI_SECONDS * halfHourDiff);
if (!isTimeRangeTooSmall(startDatetimeFrom.getTime(), newEndTime)) {
newEndTime = startDatetimeFrom.getTime() + getMinTimeRange();
}
to.setTime(newEndTime);
calendarEvent.setEndTime(to);
calendarEvent.setEnd(new Date(to.getTime()));
// Set new position for the event
long startFromMinutes = (startDatetimeFrom.getHours() * 60)
+ startDatetimeFrom.getMinutes();
long range = calendarEvent.getRangeInMinutes();
startFromMinutes = calculateStartFromMinute(startFromMinutes, from,
to, dayOffsetPx);
if (startFromMinutes < 0) {
range += startFromMinutes;
}
updatePosition(startFromMinutes, range);
}
}
private void cancelMouseMove() {
mouseMoveCanceled = true;
// reset and remove everything related to the event handling
Event.releaseCapture(getElement());
setFocus(false);
if (moveRegistration != null) {
moveRegistration.removeHandler();
moveRegistration = null;
}
mouseMoveStarted = false;
removeGlobalResizeStyle();
Style s = getElement().getStyle();
s.setZIndex(1);
// reset the position of the event
int dateCellWidth = getDateCellWidth();
int dayOffset = startXrelative / dateCellWidth;
s.clearLeft();
calendarEvent.setStartTime(startDatetimeFrom);
calendarEvent.setEndTime(startDatetimeTo);
long startFromMinutes = (startDatetimeFrom.getHours() * 60)
+ startDatetimeFrom.getMinutes();
long range = calendarEvent.getRangeInMinutes();
startFromMinutes = calculateStartFromMinute(startFromMinutes,
startDatetimeFrom, startDatetimeTo, dayOffset);
if (startFromMinutes < 0) {
range += startFromMinutes;
}
updatePosition(startFromMinutes, range);
startY = -1;
startX = -1;
// to reset the event width
((DateCell) getParent()).recalculateEventWidths();
}
// date methods are not deprecated in GWT
@SuppressWarnings("deprecation")
private long calculateStartFromMinute(long startFromMinutes, Date from,
Date to, int dayOffset) {
boolean eventStartAtDifferentDay = from.getDate() != to.getDate();
if (eventStartAtDifferentDay) {
long minutesOnPrevDay = (getTargetDateByCurrentPosition(dayOffset)
.getTime() - from.getTime()) / DateConstants.MINUTEINMILLIS;
startFromMinutes = -1 * minutesOnPrevDay;
}
return startFromMinutes;
}
/**
* @param dateOffset
* @return the amount of pixels the given date is from the left side
*/
private int calculateDateCellOffsetPx(int dateOffset) {
int dateCellOffset = 0;
int[] dateWidths = weekGrid.getDateCellWidths();
if (dateWidths != null) {
for (int i = 0; i < dateOffset; i++) {
dateCellOffset += dateWidths[i] + 1;
}
} else {
dateCellOffset = dateOffset * weekGrid.getDateCellWidth();
}
return dateCellOffset;
}
/**
* Check if the given time range is too small for events
*
* @param start
* @param end
* @return
*/
private boolean isTimeRangeTooSmall(long start, long end) {
return (end - start) >= getMinTimeRange();
}
/**
* @return the minimum amount of ms that an event must last when resized
*/
private long getMinTimeRange() {
return DateConstants.MINUTEINMILLIS * 30;
}
private Date getTargetDateByCurrentPosition(int left) {
DateCell newParent = (DateCell) weekGrid.content
.getWidget((left / getDateCellWidth()) + 1);
Date targetDate = newParent.getDate();
return targetDate;
}
private int getDateCellWidth() {
return weekGrid.getDateCellWidth();
}
/* Returns total width of all date cells. */
private int getDatesWidth() {
if (weekGrid.width == -1) {
// Undefined width. Needs to be calculated by the known cell
// widths.
int count = weekGrid.content.getWidgetCount() - 1;
return count * getDateCellWidth();
}
return weekGrid.getInternalWidth();
}
/**
* @return true if the current mouse movement is resizing
*/
private boolean clickTargetsResize() {
return weekGrid.getCalendar().isEventResizeAllowed()
&& (clickTarget == topResizeBar
|| clickTarget == bottomResizeBar);
}
private void addGlobalResizeStyle() {
if (clickTarget == topResizeBar) {
weekGrid.getCalendar().addStyleDependentName("nresize");
} else if (clickTarget == bottomResizeBar) {
weekGrid.getCalendar().addStyleDependentName("sresize");
}
}
private void removeGlobalResizeStyle() {
weekGrid.getCalendar().removeStyleDependentName("nresize");
weekGrid.getCalendar().removeStyleDependentName("sresize");
}
public void setCalendarEvent(CalendarEvent calendarEvent) {
this.calendarEvent = calendarEvent;
}
public CalendarEvent getCalendarEvent() {
return calendarEvent;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public boolean isDisabled() {
return disabled;
}
@Override
public void onContextMenu(ContextMenuEvent event) {
if (dateCell.weekgrid.getCalendar().getMouseEventListener() != null) {
event.preventDefault();
event.stopPropagation();
dateCell.weekgrid.getCalendar().getMouseEventListener()
.contextMenu(event, this);
}
}
@Override
public Object getTooltipKey() {
return eventIndex;
}
}
| apache-2.0 |
cushon/error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ImmutableSetForContainsTest.java | 16525 | /*
* Copyright 2016 The Error Prone 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.errorprone.bugpatterns;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link ImmutableSetForContains}. */
@RunWith(JUnit4.class)
public final class ImmutableSetForContainsTest {
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(ImmutableSetForContains.class, getClass());
@Test
public void immutableListOf_onlyContainsReplaces() {
refactoringHelper
.addInputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST_1 =",
" ImmutableList.<String>builder().add(\"hello\").build();",
" private static final ImmutableList<String> MY_LIST_2 = ImmutableList.of(\"hello\");",
" private static final ImmutableList<String> MY_LIST_3 =",
" new ArrayList<String>().stream().collect(toImmutableList());",
" private static final ImmutableList<String> MY_LIST_4 =",
" new ImmutableList.Builder<String>().add(\"hello\").build();",
" private void myFunc() {",
" boolean myBool1 = MY_LIST_1.contains(\"he\");",
" boolean myBool2 = MY_LIST_2.containsAll(new ArrayList<String>());",
" boolean myBool3 = MY_LIST_3.isEmpty();",
" boolean myBool4 = MY_LIST_4.isEmpty();",
" }",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import static com.google.common.collect.ImmutableSet.toImmutableSet;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableSet<String> MY_LIST_1 =",
" ImmutableSet.<String>builder().add(\"hello\").build();",
" private static final ImmutableSet<String> MY_LIST_2 = ImmutableSet.of(\"hello\");",
" private static final ImmutableSet<String> MY_LIST_3 =",
" new ArrayList<String>().stream().collect(toImmutableSet());",
" private static final ImmutableSet<String> MY_LIST_4 =",
" new ImmutableSet.Builder<String>().add(\"hello\").build();",
" private void myFunc() {",
" boolean myBool1 = MY_LIST_1.contains(\"he\");",
" boolean myBool2 = MY_LIST_2.containsAll(new ArrayList<String>());",
" boolean myBool3 = MY_LIST_3.isEmpty();",
" boolean myBool4 = MY_LIST_4.isEmpty();",
" }",
"}")
.doTest();
}
@Test
public void immutableList_initUsingStaticFunc_replacesWithCopyOf() {
refactoringHelper
.addInputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = initMyList();",
" private static ImmutableList<String> initMyList() {",
" return ImmutableList.of();",
" }",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import static com.google.common.collect.ImmutableList.toImmutableList;",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableSet<String> MY_LIST = ",
" ImmutableSet.copyOf(initMyList());",
" private static ImmutableList<String> initMyList() {",
" return ImmutableList.of();",
" }",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.doTest();
}
@Test
public void immutableList_rawType_replacesWithImmutableSet() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.addOutputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableSet MY_LIST = ImmutableSet.of(\"hello\");",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.doTest();
}
@Test
public void fieldAnnotatedWithBind_noMatch() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.inject.testing.fieldbinder.Bind;",
"import java.util.ArrayList;",
"class Test {",
" @Bind",
" private static final ImmutableList MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" boolean myBool = MY_LIST.contains(\"he\");",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableVarPassedToAFunc_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" consumer(MY_LIST);",
" }",
" private void consumer(ImmutableList<String> arg) {",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_uniqueElements_iterating_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION;",
"import com.google.common.collect.ImmutableList;",
"import com.sun.source.tree.Tree.Kind;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> STR_LIST = ImmutableList.of(\"hello\");",
" private static final ImmutableList<Kind> ENUM_LIST =",
" ImmutableList.of(Kind.AND, METHOD_INVOCATION);",
" private void myFunc() {",
" STR_LIST.stream().forEach(System.out::println);",
" STR_LIST.forEach(System.out::println);",
" ENUM_LIST.stream().forEach(System.out::println);",
" ENUM_LIST.forEach(System.out::println);",
" for (String myStr : STR_LIST) { System.out.println(myStr); }",
" for (Kind myKind : ENUM_LIST) { System.out.println(myKind); }",
" for (Long lvar : ImmutableList.<Long>of(2L)) { System.out.println(lvar); }",
" ImmutableList<Long> longList = ImmutableList.of(1L);",
" for (Long lvar : longList) { System.out.println(lvar); }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_duplicateElements_iterating_doesNotReplace() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> STR_LIST_1 = ",
" ImmutableList.of(\"hello\", \"hello\");",
" private static final ImmutableList<String> STR_LIST_2 = ",
" ImmutableList.of(\"hello\", strGenFunc());",
" private void myFunc() {",
" STR_LIST_1.stream().forEach(System.out::println);",
" STR_LIST_2.stream().forEach(System.out::println);",
" }",
" private static String strGenFunc() { return \"\"; }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_distinctElementsInBuilder_iterating_doesNotReplace() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> STR_LIST = ",
" ImmutableList.<String>builder().add(\"hello\").build();",
" private void myFunc() {",
" STR_LIST.stream().forEach(System.out::println);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_passedToFunctionsAcceptingSet_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.Iterables;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" ImmutableSet<String> mySet = ImmutableSet.copyOf(MY_LIST);",
" String onlyElement = Iterables.getOnlyElement(MY_LIST);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_passedToGenericFunctionAcceptingList_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import com.google.common.collect.ImmutableMap;",
"import com.google.common.collect.ImmutableSet;",
"import com.google.common.collect.Iterables;",
"import java.util.ArrayList;",
"import java.util.List;",
"class Test {",
" private static final ImmutableList<String> MY_LIST_1 = ImmutableList.of(\"hello\");",
" private static final ImmutableList<String> MY_LIST_2 = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" ImmutableMap<String, List<String>> myMap = ",
" ImmutableMap.<String, List<String>>builder().put(\"a\", MY_LIST_1).build();",
" boolean myBool = ImmutableList.of().equals(MY_LIST_2);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_uniqueElements_inLoopExprAndStatement_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = ImmutableList.of(\"hello\");",
" private void myFunc() {",
" for (String myStr : MY_LIST) {",
" System.out.println(MY_LIST.indexOf(myStr));",
" }",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableListInNestedClass_usedInParentClass_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" private static final class Nested {",
" private static final ImmutableList<String> MY_LIST_1 = ImmutableList.of(\"a\");",
" private static final ImmutableList<String> MY_LIST_2 = ImmutableList.of(\"b\");",
" }",
" private void myFunc() {",
" String one = Nested.MY_LIST_1.get(0);",
" String two = Nested.MY_LIST_2.iterator().next();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void twoImmutableListsUsedInSameMethodInvocation_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST_1 = ImmutableList.of(\"hello\");",
" private static final ImmutableList<String> MY_LIST_2 = ImmutableList.of(\"world\");",
" private void myFunc() {",
" MY_LIST_1.forEach(elem -> System.out.println(MY_LIST_2.get(0)));",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void listOfClassOrDistinctInstances_uniqueElements_iterating_negative() {
refactoringHelper
.addInputLines(
"Test.java",
"import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION;",
"import com.google.common.collect.ImmutableList;",
"import com.sun.source.tree.Tree.Kind;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<Class<?>> CLS_LIST = ",
" ImmutableList.of(Long.class, Double.class);",
" private static final ImmutableList<Object> OBJ_LIST =",
" ImmutableList.of(new String(\"\"), new Object());",
" private void myFunc() {",
" CLS_LIST.stream().forEach(System.out::println);",
" OBJ_LIST.forEach(System.out::println);",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void immutableListGetInVarArg_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"import java.util.ArrayList;",
"class Test {",
" private static final ImmutableList<String> MY_LIST = ImmutableList.of(\"hello\");",
" private String myFunc() {",
" return String.format(\"%s\", MY_LIST.get(0));",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void suppressionOnVariableTree_noFinding() {
refactoringHelper
.addInputLines(
"Test.java",
"import com.google.common.collect.ImmutableList;",
"class Test {",
" @SuppressWarnings(\"ImmutableSetForContains\")",
" private static final ImmutableList<String> MY_LIST_1 =",
" ImmutableList.<String>builder().add(\"hello\").build();",
" private void myFunc() {",
" boolean myBool1 = MY_LIST_1.contains(\"he\");",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| apache-2.0 |
smgoller/geode | geode-lucene/src/distributedTest/java/org/apache/geode/cache/lucene/LuceneQueriesWithReindexFlagEnabledClientDUnitTest.java | 1766 | /*
* 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.geode.cache.lucene;
import org.junit.After;
import org.junit.Before;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.apache.geode.cache.lucene.internal.LuceneServiceImpl;
import org.apache.geode.test.junit.categories.LuceneTest;
import org.apache.geode.test.junit.runners.GeodeParamsRunner;
@Category({LuceneTest.class})
@RunWith(GeodeParamsRunner.class)
public class LuceneQueriesWithReindexFlagEnabledClientDUnitTest
extends LuceneQueriesClientDUnitTest {
private static final long serialVersionUID = 1L;
@Before
public void setLuceneReindexFlag() {
dataStore1.invoke(() -> LuceneServiceImpl.LUCENE_REINDEX = true);
dataStore2.invoke(() -> LuceneServiceImpl.LUCENE_REINDEX = true);
}
@After
public void clearLuceneReindexFlag() {
dataStore1.invoke(() -> LuceneServiceImpl.LUCENE_REINDEX = false);
dataStore2.invoke(() -> LuceneServiceImpl.LUCENE_REINDEX = false);
}
}
| apache-2.0 |
papicella/snappy-store | gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/sql/execute/TriggerEvents.java | 1679 | /*
Derby - Class com.pivotal.gemfirexd.internal.impl.sql.execute.TriggerEvents
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.pivotal.gemfirexd.internal.impl.sql.execute;
/**
* Static final trigger events. One for
* each known trigger event. Use these rather
* than constructing a new TriggerEvent.
*
*/
public class TriggerEvents
{
public static final TriggerEvent BEFORE_INSERT = new TriggerEvent(TriggerEvent.BEFORE_INSERT);
public static final TriggerEvent BEFORE_DELETE = new TriggerEvent(TriggerEvent.BEFORE_DELETE);
public static final TriggerEvent BEFORE_UPDATE = new TriggerEvent(TriggerEvent.BEFORE_UPDATE);
public static final TriggerEvent AFTER_INSERT = new TriggerEvent(TriggerEvent.AFTER_INSERT);
public static final TriggerEvent AFTER_DELETE = new TriggerEvent(TriggerEvent.AFTER_DELETE);
public static final TriggerEvent AFTER_UPDATE = new TriggerEvent(TriggerEvent.AFTER_UPDATE);
}
| apache-2.0 |