code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.plugin.ml;
import io.trino.spi.function.AccumulatorState;
import io.trino.spi.function.AccumulatorStateMetadata;
import java.util.Map;
@AccumulatorStateMetadata(stateSerializerClass = EvaluateClassifierPredictionsStateSerializer.class, stateFactoryClass = EvaluateClassifierPredictionsStateFactory.class)
public interface EvaluateClassifierPredictionsState
extends AccumulatorState
{
void addMemoryUsage(int memory);
Map<String, Integer> getTruePositives();
Map<String, Integer> getFalsePositives();
Map<String, Integer> getFalseNegatives();
}
| ebyhr/presto | plugin/trino-ml/src/main/java/io/trino/plugin/ml/EvaluateClassifierPredictionsState.java | Java | apache-2.0 | 1,153 |
/**
* 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.waveprotocol.wave.client.editor.extract;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import org.waveprotocol.wave.client.editor.content.ContentNode;
import org.waveprotocol.wave.model.document.util.Point;
import org.waveprotocol.wave.model.util.Preconditions;
/**
* Thrown whenever we detect an inconsistency has come up, and we
* need to repair it in some manner.
*
* @author [email protected] (Daniel Danilatos)
*/
@SuppressWarnings("serial")
public abstract class InconsistencyException extends Exception {
private final Element where;
/**
* @param where The HTML element where or within something went awry
*/
protected InconsistencyException(Element where) {
this.where = where;
}
/**
* @return The HTML element where or within something went awry
*/
public Element getNode() {
return where;
}
/**
* HTML node(s) removed with respect to the content
*/
public static class HtmlMissing extends InconsistencyException {
ContentNode brokenNode;
/**
* @param brokenNode The content node that is missing its impl nodelet
* @param where The HTML element where or within something went awry
*/
public HtmlMissing(ContentNode brokenNode, Element where) {
super(where);
Preconditions.checkNotNull(brokenNode, "Broken node is unspecified");
this.brokenNode = brokenNode;
}
/**
* @return The content node that is missing its impl nodelet
*/
public ContentNode getBrokenNode() {
return brokenNode;
}
@Override
public String toString() {
return "HtmlMissing: " + brokenNode + " in " + getNode();
}
}
/**
* HTML node(s) inserted with respect to the content
*/
public static class HtmlInserted extends InconsistencyException {
final Point.El<ContentNode> contentPoint;
final Point.El<Node> htmlPoint;
/**
* @param htmlPoint The place in the HTML right before where html was inserted
* @param contentPoint The corresponding place in the content
*/
public HtmlInserted(Point.El<ContentNode> contentPoint, Point.El<Node> htmlPoint) {
super(htmlPoint.getContainer().<Element>cast());
this.contentPoint = contentPoint;
this.htmlPoint = htmlPoint;
}
/**
* @return The place in the content where something was inserted
*/
public Point.El<ContentNode> getContentPoint() {
return contentPoint;
}
/**
* @return The place in the html where something was inserted
*/
public Point.El<Node> getHtmlPoint() {
return htmlPoint;
}
@Override
public String toString() {
return "HtmlInserted: " + contentPoint;
}
}
}
| wisebaldone/incubator-wave | wave/src/main/java/org/waveprotocol/wave/client/editor/extract/InconsistencyException.java | Java | apache-2.0 | 3,547 |
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rules;
import static org.junit.Assert.assertEquals;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import org.junit.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathSourcePathTest {
@Test
public void shouldResolveFilesUsingTheBuildContextsFileSystem() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
PathSourcePath path = new PathSourcePath(projectFilesystem, Paths.get("cheese"));
SourcePathResolver resolver = new SourcePathResolver(
new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer())
);
Path resolved = resolver.deprecatedGetPath(path);
assertEquals(Paths.get("cheese"), resolved);
}
@Test
public void shouldReturnTheOriginalPathAsTheReference() {
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
Path expected = Paths.get("cheese");
PathSourcePath path = new PathSourcePath(projectFilesystem, expected);
assertEquals(expected, path.getRelativePath());
}
}
| raviagarwal7/buck | test/com/facebook/buck/rules/PathSourcePathTest.java | Java | apache-2.0 | 1,725 |
package com.alibaba.jstorm.queue.disruptor;
import org.apache.log4j.Logger;
import com.lmax.disruptor.EventHandler;
public class JstormEventHandler implements EventHandler {
Logger logger = Logger.getLogger(JstormEventHandler.class);
private int count;
public JstormEventHandler(int count) {
this.count = count;
}
@Override
public void onEvent(Object event, long sequence, boolean endOfBatch)
throws Exception {
long msgId = Long.parseLong(((JstormEvent) event).getMsgId());
// if (msgId % size ==0) {
// logger.warn("consumer msgId=" + msgId + ", seq=" + sequence);
// }
if (msgId == count - 1) {
logger.warn("end..." + System.currentTimeMillis());
}
}
}
| fengshao0907/jstorm | jstorm-server/src/main/java/com/alibaba/jstorm/queue/disruptor/JstormEventHandler.java | Java | apache-2.0 | 720 |
/*******************************************************************************
* Copyright (c) Intel Corporation
* Copyright (c) 2017
*
* 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.osc.core.broker.model.sdn;
import java.util.List;
import org.osc.sdk.controller.element.NetworkElement;
/**
* PortPairGroupNetworkElementImpl contains only element id which is used to compare the manager sfc port group element id.
*/
public class PortPairGroupNetworkElementImpl implements NetworkElement {
private String elementId;
public PortPairGroupNetworkElementImpl(String elementId) {
this.elementId = elementId;
}
@Override
public String getElementId() {
return this.elementId;
}
@Override
public String getParentId() {
return null;
}
@Override
public List<String> getMacAddresses() {
return null;
}
@Override
public List<String> getPortIPs() {
return null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.elementId == null) ? 0 : this.elementId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof NetworkElement)) {
return false;
}
NetworkElement other = (NetworkElement) obj;
if (this.elementId == null) {
if (other.getElementId() != null) {
return false;
}
} else if (!this.elementId.equals(other.getElementId())) {
return false;
}
return true;
}
@Override
public String toString() {
return "PortPairGroupNetworkElementImpl [elementId=" + this.elementId + "]";
}
}
| arvindn05/osc-core | osc-server/src/main/java/org/osc/core/broker/model/sdn/PortPairGroupNetworkElementImpl.java | Java | apache-2.0 | 2,254 |
package org.apache.lucene.search;
/*
* 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.IOException;
import org.apache.lucene.index.LeafReaderContext;
/**
* A {@link Collector} implementation which wraps another
* {@link Collector} and makes sure only documents with
* scores > 0 are collected.
*/
public class PositiveScoresOnlyCollector extends FilterCollector {
public PositiveScoresOnlyCollector(Collector in) {
super(in);
}
@Override
public LeafCollector getLeafCollector(LeafReaderContext context)
throws IOException {
return new FilterLeafCollector(super.getLeafCollector(context)) {
private Scorer scorer;
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = new ScoreCachingWrappingScorer(scorer);
in.setScorer(this.scorer);
}
@Override
public void collect(int doc) throws IOException {
if (scorer.score() > 0) {
in.collect(doc);
}
}
};
}
}
| yida-lxw/solr-5.3.1 | lucene/core/src/java/org/apache/lucene/search/PositiveScoresOnlyCollector.java | Java | apache-2.0 | 1,778 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.extractor.mp3;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.extractor.ConstantBitrateSeekMap;
import com.google.android.exoplayer2.extractor.MpegAudioHeader;
/**
* MP3 seeker that doesn't rely on metadata and seeks assuming the source has a constant bitrate.
*/
/* package */ final class ConstantBitrateSeeker extends ConstantBitrateSeekMap implements Seeker {
/**
* @param inputLength The length of the stream in bytes, or {@link C#LENGTH_UNSET} if unknown.
* @param firstFramePosition The position of the first frame in the stream.
* @param mpegAudioHeader The MPEG audio header associated with the first frame.
*/
public ConstantBitrateSeeker(
long inputLength, long firstFramePosition, MpegAudioHeader mpegAudioHeader) {
super(inputLength, firstFramePosition, mpegAudioHeader.bitrate, mpegAudioHeader.frameSize);
}
@Override
public long getTimeUs(long position) {
return getTimeUsAtPosition(position);
}
@Override
public long getDataEndPosition() {
return C.POSITION_UNSET;
}
}
| superbderrick/ExoPlayer | library/core/src/main/java/com/google/android/exoplayer2/extractor/mp3/ConstantBitrateSeeker.java | Java | apache-2.0 | 1,727 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.ml.math.primitives.vector;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.ignite.ml.math.StorageConstants;
import org.apache.ignite.ml.math.primitives.matrix.Matrix;
import org.apache.ignite.ml.math.primitives.matrix.impl.DenseMatrix;
import org.apache.ignite.ml.math.primitives.vector.impl.DelegatingVector;
import org.apache.ignite.ml.math.primitives.vector.impl.DenseVector;
import org.apache.ignite.ml.math.primitives.vector.impl.SparseVector;
import org.apache.ignite.ml.math.primitives.vector.impl.VectorizedViewMatrix;
import org.jetbrains.annotations.NotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/** */
class VectorImplementationsFixtures {
/** */
private static final List<Supplier<Iterable<Vector>>> suppliers = Arrays.asList(
(Supplier<Iterable<Vector>>)DenseLocalOnHeapVectorFixture::new,
(Supplier<Iterable<Vector>>)SparseLocalVectorFixture::new,
(Supplier<Iterable<Vector>>)DelegatingVectorFixture::new,
(Supplier<Iterable<Vector>>)MatrixVectorViewFixture::new
);
/** */
void consumeSampleVectors(Consumer<Integer> paramsConsumer, BiConsumer<Vector, String> consumer) {
for (Supplier<Iterable<Vector>> fixtureSupplier : suppliers) {
final Iterable<Vector> fixture = fixtureSupplier.get();
for (Vector v : fixture) {
if (paramsConsumer != null)
paramsConsumer.accept(v.size());
consumer.accept(v, fixture.toString());
}
}
}
/** */
private static class DenseLocalOnHeapVectorFixture extends VectorSizesExtraFixture<Boolean> {
/** */
DenseLocalOnHeapVectorFixture() {
super("DenseLocalOnHeapVector",
(size, shallowCp) -> new DenseVector(new double[size], shallowCp),
"shallow copy", new Boolean[] {false, true, null});
}
}
/** */
private static class SparseLocalVectorFixture extends VectorSizesExtraFixture<Integer> {
/** */
SparseLocalVectorFixture() {
super("SparseLocalVector", (x, y) -> new SparseVector(x), "access mode",
new Integer[] {StorageConstants.SEQUENTIAL_ACCESS_MODE, StorageConstants.RANDOM_ACCESS_MODE, null});
}
}
/** */
private static class MatrixVectorViewFixture extends VectorSizesExtraFixture<Integer> {
/** */
MatrixVectorViewFixture() {
super("MatrixVectorView",
MatrixVectorViewFixture::newView,
"stride kind", new Integer[] {0, 1, 2, null});
}
/** */
private static Vector newView(int size, int strideKind) {
final Matrix parent = new DenseMatrix(size, size);
return new VectorizedViewMatrix(parent, 0, 0, strideKind != 1 ? 1 : 0, strideKind != 0 ? 1 : 0);
}
}
/** */
private static class VectorSizesExtraFixture<T> implements Iterable<Vector> {
/** */
private final Supplier<VectorSizesExtraIterator<T>> iter;
/** */
private final AtomicReference<String> ctxDescrHolder = new AtomicReference<>("Iterator not started.");
/** */
VectorSizesExtraFixture(String vectorKind, BiFunction<Integer, T, Vector> ctor, String extraParamName,
T[] extras) {
iter = () -> new VectorSizesExtraIterator<>(vectorKind, ctor, ctxDescrHolder::set, extraParamName, extras);
}
/** {@inheritDoc} */
@NotNull
@Override public Iterator<Vector> iterator() {
return iter.get();
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return ctxDescrHolder.get();
}
}
/** */
private abstract static class VectorSizesFixture implements Iterable<Vector> {
/** */
private final Supplier<VectorSizesIterator> iter;
/** */
private final AtomicReference<String> ctxDescrHolder = new AtomicReference<>("Iterator not started.");
/** */
VectorSizesFixture(String vectorKind, Function<Integer, Vector> ctor) {
iter = () -> new VectorSizesIterator(vectorKind, ctor, ctxDescrHolder::set);
}
/** {@inheritDoc} */
@NotNull
@Override public Iterator<Vector> iterator() {
return iter.get();
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return ctxDescrHolder.get();
}
}
/** */
private static class VectorSizesExtraIterator<T> extends VectorSizesIterator {
/** */
private final T[] extras;
/** */
private int extraIdx;
/** */
private final BiFunction<Integer, T, Vector> ctor;
/** */
private final String extraParamName;
/**
* @param vectorKind Descriptive name to use for context logging.
* @param ctor Constructor for objects to iterate over.
* @param ctxDescrConsumer Context logging consumer.
* @param extraParamName Name of extra parameter to iterate over.
* @param extras Array of extra parameter values to iterate over.
*/
VectorSizesExtraIterator(String vectorKind, BiFunction<Integer, T, Vector> ctor,
Consumer<String> ctxDescrConsumer, String extraParamName, T[] extras) {
super(vectorKind, null, ctxDescrConsumer);
this.ctor = ctor;
this.extraParamName = extraParamName;
this.extras = extras;
}
/** {@inheritDoc} */
@Override public boolean hasNext() {
return super.hasNext() && hasNextExtra(extraIdx);
}
/** {@inheritDoc} */
@Override void nextIdx() {
assert extras[extraIdx] != null
: "Index(es) out of bound at " + this;
if (hasNextExtra(extraIdx + 1)) {
extraIdx++;
return;
}
extraIdx = 0;
super.nextIdx();
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return "{" + super.toString() +
", " + extraParamName + "=" + extras[extraIdx] +
'}';
}
/** {@inheritDoc} */
@Override BiFunction<Integer, Integer, Vector> ctor() {
return (size, delta) -> ctor.apply(size + delta, extras[extraIdx]);
}
/** {@inheritDoc} */
@Override void selfTest() {
final Set<Integer> extraIdxs = new HashSet<>();
int cnt = 0;
while (hasNext()) {
assertNotNull("Expect not null vector at " + this, next());
if (extras[extraIdx] != null)
extraIdxs.add(extraIdx);
cnt++;
}
assertEquals("Extra param tested", extraIdxs.size(), extras.length - 1);
assertEquals("Combinations tested mismatch.",
7 * 3 * (extras.length - 1), cnt);
}
/** */
private boolean hasNextExtra(int idx) {
return extras[idx] != null;
}
}
/** */
private static class VectorSizesIterator extends TwoParamsIterator<Integer, Integer> {
/** */
private final Function<Integer, Vector> ctor;
/** */
VectorSizesIterator(String vectorKind, Function<Integer, Vector> ctor, Consumer<String> ctxDescrConsumer) {
super(vectorKind, null, ctxDescrConsumer,
"size", new Integer[] {2, 4, 8, 16, 32, 64, 128, null},
"size delta", new Integer[] {-1, 0, 1, null});
this.ctor = ctor;
}
/** {@inheritDoc} */
@Override BiFunction<Integer, Integer, Vector> ctor() {
return (size, delta) -> ctor.apply(size + delta);
}
}
/** */
private static class TwoParamsIterator<T, U> implements Iterator<Vector> {
/** */
private final T params1[];
/** */
private final U params2[];
/** */
private final String vectorKind;
/** */
private final String param1Name;
/** */
private final String param2Name;
/** */
private final BiFunction<T, U, Vector> ctor;
/** */
private final Consumer<String> ctxDescrConsumer;
/** */
private int param1Idx;
/** */
private int param2Idx;
/** */
TwoParamsIterator(String vectorKind, BiFunction<T, U, Vector> ctor,
Consumer<String> ctxDescrConsumer, String param1Name, T[] params1, String param2Name, U[] params2) {
this.param1Name = param1Name;
this.params1 = params1;
this.param2Name = param2Name;
this.params2 = params2;
this.vectorKind = vectorKind;
this.ctor = ctor;
this.ctxDescrConsumer = ctxDescrConsumer;
}
/** {@inheritDoc} */
@Override public boolean hasNext() {
return hasNextParam1(param1Idx) && hasNextParam2(param2Idx);
}
/** {@inheritDoc} */
@Override public Vector next() {
if (!hasNext())
throw new NoSuchElementException(toString());
if (ctxDescrConsumer != null)
ctxDescrConsumer.accept(toString());
Vector res = ctor().apply(params1[param1Idx], params2[param2Idx]);
nextIdx();
return res;
}
/** */
void selfTest() {
final Set<Integer> sizeIdxs = new HashSet<>(), deltaIdxs = new HashSet<>();
int cnt = 0;
while (hasNext()) {
assertNotNull("Expect not null vector at " + this, next());
if (params1[param1Idx] != null)
sizeIdxs.add(param1Idx);
if (params2[param2Idx] != null)
deltaIdxs.add(param2Idx);
cnt++;
}
assertEquals("Sizes tested mismatch.", sizeIdxs.size(), params1.length - 1);
assertEquals("Deltas tested", deltaIdxs.size(), params2.length - 1);
assertEquals("Combinations tested mismatch.",
(params1.length - 1) * (params2.length - 1), cnt);
}
/** IMPL NOTE override in subclasses if needed */
void nextIdx() {
assert params1[param1Idx] != null && params2[param2Idx] != null
: "Index(es) out of bound at " + this;
if (hasNextParam2(param2Idx + 1)) {
param2Idx++;
return;
}
param2Idx = 0;
param1Idx++;
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return vectorKind + "{" + param1Name + "=" + params1[param1Idx] +
", " + param2Name + "=" + params2[param2Idx] +
'}';
}
/** IMPL NOTE override in subclasses if needed */
BiFunction<T, U, Vector> ctor() {
return ctor;
}
/** */
private boolean hasNextParam1(int idx) {
return params1[idx] != null;
}
/** */
private boolean hasNextParam2(int idx) {
return params2[idx] != null;
}
}
/** Delegating vector with dense local onheap vector */
private static class DelegatingVectorFixture implements Iterable<Vector> {
/** */
private final Supplier<VectorSizesExtraIterator<Boolean>> iter;
/** */
private final AtomicReference<String> ctxDescrHolder = new AtomicReference<>("Iterator not started.");
/** */
DelegatingVectorFixture() {
iter = () -> new VectorSizesExtraIterator<>("DelegatingVector with DenseLocalOnHeapVector",
(size, shallowCp) -> new DelegatingVector(new DenseVector(new double[size], shallowCp)),
ctxDescrHolder::set, "shallow copy", new Boolean[] {false, true, null});
}
/** {@inheritDoc} */
@NotNull
@Override public Iterator<Vector> iterator() {
return iter.get();
}
/** {@inheritDoc} */
@Override public String toString() {
// IMPL NOTE index within bounds is expected to be guaranteed by proper code in this class
return ctxDescrHolder.get();
}
}
}
| NSAmelchev/ignite | modules/ml/src/test/java/org/apache/ignite/ml/math/primitives/vector/VectorImplementationsFixtures.java | Java | apache-2.0 | 14,067 |
/*
* 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.sql.test;
import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.advise.SqlAdvisor;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorWithHints;
/**
* Creates the objects needed to run a SQL parsing or validation test.
*
* @see org.apache.calcite.sql.test.SqlTester
*/
public interface SqlTestFactory {
SqlOperatorTable createOperatorTable(SqlTestFactory factory);
SqlParser createParser(SqlTestFactory factory, String sql);
SqlValidator getValidator(SqlTestFactory factory);
SqlAdvisor createAdvisor(SqlValidatorWithHints validator);
Object get(String name);
}
// End SqlTestFactory.java
| wanglan/calcite | core/src/test/java/org/apache/calcite/sql/test/SqlTestFactory.java | Java | apache-2.0 | 1,554 |
/**
* Copyright 2005-2016 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.kubernetes.api;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import java.util.List;
/**
*/
public class PodIdToReplicationControllerIDExample {
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Arguments: kuberneteMasterUrl namespace podID");
return;
}
String kuberneteMasterUrl = args[0];
String namespace = args[1];
String podID = args[2];
System.out.println("Looking up ReplicationController for pod ID: " + podID);
KubernetesClient client = new DefaultKubernetesClient(new ConfigBuilder().withMasterUrl(kuberneteMasterUrl).build());
Pod pod = (Pod) client.pods().inNamespace(namespace).withName(podID);
pod.getMetadata().getLabels();
List<ReplicationController> replicationControllers = client.replicationControllers().inNamespace(namespace).withLabels(pod.getMetadata().getLabels()).list().getItems();
if (replicationControllers.size() == 1) {
ReplicationController replicationController = replicationControllers.get(0);
String id = KubernetesHelper.getName(replicationController);
System.out.println("Found replication controller: " + id);
} else {
System.out.println("Could not find replication controller!");
}
}
}
| KurtStam/fabric8 | components/kubernetes-api/src/test/java/io/fabric8/kubernetes/api/PodIdToReplicationControllerIDExample.java | Java | apache-2.0 | 2,230 |
package com.baidu.rigel.biplatform.parser.result;
public abstract class AbstractResult<T> implements ComputeResult {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 4414418789997355453L;
/**
* data
*/
private T data;
public AbstractResult() {
super();
}
/**
* 获取 data
* @return the data
*/
public T getData() {
return data;
}
/**
* 设置 data
* @param data the data to set
*/
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return data + "";
}
}
| qqming113/bi-platform | parser/src/main/java/com/baidu/rigel/biplatform/parser/result/AbstractResult.java | Java | apache-2.0 | 737 |
/*
Copyright 2007-2009 Selenium committers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import static org.openqa.selenium.WaitingConditions.elementTextToContain;
import static org.openqa.selenium.WaitingConditions.elementTextToEqual;
import static org.openqa.selenium.WaitingConditions.elementValueToEqual;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
import static org.openqa.selenium.testing.Ignore.Driver.CHROME;
import static org.openqa.selenium.testing.Ignore.Driver.HTMLUNIT;
import static org.openqa.selenium.testing.Ignore.Driver.IE;
import static org.openqa.selenium.testing.Ignore.Driver.MARIONETTE;
import static org.openqa.selenium.testing.Ignore.Driver.OPERA;
import static org.openqa.selenium.testing.Ignore.Driver.OPERA_MOBILE;
import static org.openqa.selenium.testing.Ignore.Driver.SAFARI;
import org.junit.Test;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;
import org.openqa.selenium.testing.JavascriptEnabled;
import org.openqa.selenium.testing.TestUtilities;
import org.openqa.selenium.testing.drivers.SauceDriver;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class CorrectEventFiringTest extends JUnit4TestBase {
@Ignore(value = {CHROME}, reason = "Webkit bug 22261")
@JavascriptEnabled
@Test
public void testShouldFireFocusEventWhenClicking() {
driver.get(pages.javascriptPage);
clickOnElementWhichRecordsEvents();
assertEventFired("focus");
}
@JavascriptEnabled
@Test
public void testShouldFireClickEventWhenClicking() {
driver.get(pages.javascriptPage);
clickOnElementWhichRecordsEvents();
assertEventFired("click");
}
@JavascriptEnabled
@Test
public void testShouldFireMouseDownEventWhenClicking() {
driver.get(pages.javascriptPage);
clickOnElementWhichRecordsEvents();
assertEventFired("mousedown");
}
@JavascriptEnabled
@Test
public void testShouldFireMouseUpEventWhenClicking() {
driver.get(pages.javascriptPage);
clickOnElementWhichRecordsEvents();
assertEventFired("mouseup");
}
@JavascriptEnabled
@Test
public void testShouldFireMouseOverEventWhenClicking() {
driver.get(pages.javascriptPage);
clickOnElementWhichRecordsEvents();
assertEventFired("mouseover");
}
// TODO: this is a bad test: mousemove should not fire in a perfect click (e.g. mouse did not move
// while doing down, up, click
@JavascriptEnabled
@Test
@Ignore(MARIONETTE)
public void testShouldFireMouseMoveEventWhenClicking() {
driver.get(pages.javascriptPage);
clickOnElementWhichRecordsEvents();
assertEventFired("mousemove");
}
@JavascriptEnabled
@Test
public void testShouldNotThrowIfEventHandlerThrows() {
driver.get(pages.javascriptPage);
try {
driver.findElement(By.id("throwing-mouseover")).click();
} catch (WebDriverException e) {
fail("Error in event handler should not have propagated: " + e);
}
}
@Ignore(value = {CHROME}, reason = "Webkit bug 22261")
@JavascriptEnabled
@Test
public void testShouldFireEventsInTheRightOrder() {
driver.get(pages.javascriptPage);
clickOnElementWhichRecordsEvents();
String text = driver.findElement(By.id("result")).getText();
int lastIndex = -1;
for (String event : new String[] {"mousedown", "focus", "mouseup", "click"}) {
int index = text.indexOf(event);
assertTrue(event + " did not fire at all", index != -1);
assertTrue(event + " did not fire in the correct order", index > lastIndex);
}
}
@JavascriptEnabled
@Test
public void testsShouldIssueMouseDownEvents() {
driver.get(pages.javascriptPage);
driver.findElement(By.id("mousedown")).click();
assertEventFired("mouse down");
String result = driver.findElement(By.id("result")).getText();
assertThat(result, equalTo("mouse down"));
}
@JavascriptEnabled
@Test
public void testShouldIssueClickEvents() {
driver.get(pages.javascriptPage);
driver.findElement(By.id("mouseclick")).click();
WebElement result = driver.findElement(By.id("result"));
wait.until(elementTextToEqual(result, "mouse click"));
assertThat(result.getText(), equalTo("mouse click"));
}
@JavascriptEnabled
@Test
public void testShouldIssueMouseUpEvents() {
driver.get(pages.javascriptPage);
driver.findElement(By.id("mouseup")).click();
WebElement result = driver.findElement(By.id("result"));
wait.until(elementTextToEqual(result, "mouse up"));
assertThat(result.getText(), equalTo("mouse up"));
}
@JavascriptEnabled
@Test
public void testMouseEventsShouldBubbleUpToContainingElements() {
driver.get(pages.javascriptPage);
driver.findElement(By.id("child")).click();
WebElement result = driver.findElement(By.id("result"));
wait.until(elementTextToEqual(result, "mouse down"));
assertThat(result.getText(), equalTo("mouse down"));
}
@JavascriptEnabled
@Ignore(value = {MARIONETTE})
@Test
public void testShouldEmitOnChangeEventsWhenSelectingElements() {
driver.get(pages.javascriptPage);
// Intentionally not looking up the select tag. See selenium r7937 for details.
List<WebElement> allOptions = driver.findElements(By.xpath("//select[@id='selector']//option"));
String initialTextValue = driver.findElement(By.id("result")).getText();
WebElement foo = allOptions.get(0);
WebElement bar = allOptions.get(1);
foo.click();
assertThat(driver.findElement(By.id("result")).getText(),
equalTo(initialTextValue));
bar.click();
assertThat(driver.findElement(By.id("result")).getText(),
equalTo("bar"));
}
@JavascriptEnabled
@Ignore(value = {HTMLUNIT, MARIONETTE})
@Test
public void testShouldEmitOnClickEventsWhenSelectingElements() {
driver.get(pages.javascriptPage);
// Intentionally not looking up the select tag. See selenium r7937 for details.
List<WebElement> allOptions = driver.findElements(By.xpath("//select[@id='selector2']//option"));
WebElement foo = allOptions.get(0);
WebElement bar = allOptions.get(1);
foo.click();
assertThat(driver.findElement(By.id("result")).getText(),
equalTo("foo"));
bar.click();
assertThat(driver.findElement(By.id("result")).getText(),
equalTo("bar"));
}
@JavascriptEnabled
@Ignore(value = {IE, HTMLUNIT},
reason = "IE: Only fires the onchange event when the checkbox loses the focus, "
+ "HtmlUnit: default mode is IE8 now")
@Test
public void testShouldEmitOnChangeEventsWhenChangingTheStateOfACheckbox() {
driver.get(pages.javascriptPage);
WebElement checkbox = driver.findElement(By.id("checkbox"));
checkbox.click();
WebElement result = driver.findElement(By.id("result"));
wait.until(elementTextToEqual(result, "checkbox thing"));
}
@JavascriptEnabled
@Test
public void testShouldEmitClickEventWhenClickingOnATextInputElement() {
driver.get(pages.javascriptPage);
WebElement clicker = driver.findElement(By.id("clickField"));
clicker.click();
wait.until(elementValueToEqual(clicker, "Clicked"));
assertThat(clicker.getAttribute("value"), equalTo("Clicked"));
}
@JavascriptEnabled
@Test
public void testShouldFireTwoClickEventsWhenClickingOnALabel() {
driver.get(pages.javascriptPage);
driver.findElement(By.id("labelForCheckbox")).click();
WebElement result = driver.findElement(By.id("result"));
assertNotNull(wait.until(elementTextToContain(result, "labelclick chboxclick")));
}
@JavascriptEnabled
@Test
public void testClearingAnElementShouldCauseTheOnChangeHandlerToFire() {
driver.get(pages.javascriptPage);
WebElement element = driver.findElement(By.id("clearMe"));
element.clear();
WebElement result = driver.findElement(By.id("result"));
assertThat(result.getText(), equalTo("Cleared"));
}
@JavascriptEnabled
@Test
public void testSendingKeysToAnotherElementShouldCauseTheBlurEventToFire() {
assumeFalse(browserNeedsFocusOnThisOs(driver));
driver.get(pages.javascriptPage);
WebElement element = driver.findElement(By.id("theworks"));
element.sendKeys("foo");
WebElement element2 = driver.findElement(By.id("changeable"));
element2.sendKeys("bar");
assertEventFired("blur");
}
@JavascriptEnabled
@Test
public void testSendingKeysToAnElementShouldCauseTheFocusEventToFire() {
assumeFalse(browserNeedsFocusOnThisOs(driver));
driver.get(pages.javascriptPage);
WebElement element = driver.findElement(By.id("theworks"));
element.sendKeys("foo");
assertEventFired("focus");
}
@JavascriptEnabled
@Test
public void testSendingKeysToAFocusedElementShouldNotBlurThatElement() {
assumeFalse(browserNeedsFocusOnThisOs(driver));
driver.get(pages.javascriptPage);
WebElement element = driver.findElement(By.id("theworks"));
element.click();
// Wait until focused
boolean focused = false;
WebElement result = driver.findElement(By.id("result"));
for (int i = 0; i < 5; ++i) {
String fired = result.getText();
if (fired.contains("focus")) {
focused = true;
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
if (!focused) {
fail("Clicking on element didn't focus it in time - can't proceed so failing");
}
element.sendKeys("a");
assertEventNotFired("blur");
}
@JavascriptEnabled
@Test
@Ignore(MARIONETTE)
public void testSubmittingFormFromFormElementShouldFireOnSubmitForThatForm() {
driver.get(pages.javascriptPage);
WebElement formElement = driver.findElement(By.id("submitListeningForm"));
formElement.submit();
assertEventFired("form-onsubmit");
}
@JavascriptEnabled
@Ignore({MARIONETTE})
@Test
public void testSubmittingFormFromFormInputSubmitElementShouldFireOnSubmitForThatForm() {
driver.get(pages.javascriptPage);
WebElement submit = driver.findElement(By.id("submitListeningForm-submit"));
submit.submit();
assertEventFired("form-onsubmit");
}
@JavascriptEnabled
@Ignore({MARIONETTE})
@Test
public void testSubmittingFormFromFormInputTextElementShouldFireOnSubmitForThatFormAndNotClickOnThatInput() {
driver.get(pages.javascriptPage);
WebElement submit = driver.findElement(By.id("submitListeningForm-submit"));
submit.submit();
assertEventFired("form-onsubmit");
assertEventNotFired("text-onclick");
}
@JavascriptEnabled
@Ignore(value = {OPERA, SAFARI, OPERA_MOBILE, MARIONETTE},
reason = "Does not yet support file uploads", issues = { 4220 })
@Test
public void testUploadingFileShouldFireOnChangeEvent() throws IOException {
driver.get(pages.formPage);
WebElement uploadElement = driver.findElement(By.id("upload"));
WebElement result = driver.findElement(By.id("fileResults"));
assertThat(result.getText(), equalTo(""));
File file = File.createTempFile("test", "txt");
file.deleteOnExit();
uploadElement.sendKeys(file.getAbsolutePath());
// Shift focus to something else because send key doesn't make the focus leave
driver.findElement(By.id("id-name1")).click();
assertThat(result.getText(), equalTo("changed"));
}
private String getTextFromElementOnceAvailable(String elementId) {
return wait.until(visibilityOfElementLocated(By.id(elementId))).getText();
}
@JavascriptEnabled
@Test
public void testShouldReportTheXAndYCoordinatesWhenClicking() {
assumeFalse("Skipping test which fails in IE on Sauce",
SauceDriver.shouldUseSauce() && TestUtilities.isInternetExplorer(driver));
driver.get(pages.clickEventPage);
WebElement element = driver.findElement(By.id("eventish"));
element.click();
String clientX = getTextFromElementOnceAvailable("clientX");
String clientY = getTextFromElementOnceAvailable("clientY");
assertThat(clientX, not(equalTo("0")));
assertThat(clientY, not(equalTo("0")));
}
@JavascriptEnabled
@Ignore(value = {MARIONETTE}, reason = "Not tested")
@Test
public void testClickEventsShouldBubble() {
driver.get(pages.clicksPage);
driver.findElement(By.id("bubblesFrom")).click();
boolean eventBubbled = (Boolean)((JavascriptExecutor)driver).executeScript("return !!window.bubbledClick;");
assertTrue("Event didn't bubble up", eventBubbled);
}
private void clickOnElementWhichRecordsEvents() {
driver.findElement(By.id("plainButton")).click();
}
private void assertEventFired(String eventName) {
WebElement result = driver.findElement(By.id("result"));
String text = wait.until(elementTextToContain(result, eventName));
boolean conditionMet = text.contains(eventName);
assertTrue("No " + eventName + " fired: " + text, conditionMet);
}
private void assertEventNotFired(String eventName) {
WebElement result = driver.findElement(By.id("result"));
String text = result.getText();
assertFalse(eventName + " fired: " + text, text.contains(eventName));
}
private boolean browserNeedsFocusOnThisOs(WebDriver driver) {
// No browser yet demands focus on windows
if (TestUtilities.getEffectivePlatform().is(Platform.WINDOWS))
return false;
if (Boolean.getBoolean("webdriver.focus.override")) {
return false;
}
String browserName = getBrowserName(driver);
return browserName.toLowerCase().contains("firefox");
}
private String getBrowserName(WebDriver driver) {
if (driver instanceof HasCapabilities) {
return ((HasCapabilities) driver).getCapabilities().getBrowserName();
}
return driver.getClass().getName();
}
}
| orange-tv-blagnac/selenium | java/client/test/org/openqa/selenium/CorrectEventFiringTest.java | Java | apache-2.0 | 14,684 |
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.social.config;
public class FakeTemplate implements Fake {
private String accessToken;
public FakeTemplate() {}
public FakeTemplate(String accessToken) {
this.accessToken = accessToken;
}
public String getAccessToken() {
return accessToken;
}
public boolean isAuthorized() {
return accessToken != null;
}
}
| shanika/spring-social | spring-social-config/src/test/java/org/springframework/social/config/FakeTemplate.java | Java | apache-2.0 | 974 |
package com.github.pockethub.android.dagger;
import com.github.pockethub.android.ui.gist.GistFragment;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
@Module
interface GistsViewFragmentProvider {
@ContributesAndroidInjector
GistFragment gistFragment();
}
| PKRoma/github-android | app/src/main/java/com/github/pockethub/android/dagger/GistsViewFragmentProvider.java | Java | apache-2.0 | 292 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), available at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* TIANI Medgraph AG.
* Portions created by the Initial Developer are Copyright (C) 2003-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gunter Zeilinger <[email protected]>
* Franz Willer <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chex.archive.hsm;
/**
* @author [email protected]
* @version $Revision: 2232 $ $Date: 2006-01-19 00:02:08 +0800 (周四, 19 1月 2006) $
* @since Jan 16, 2006
*/
public class FTPArchiverService extends AbstractFileCopyService {
/* (non-Javadoc)
* @see org.dcm4chex.archive.hsm.AbstractFileCopyService#process(org.dcm4chex.archive.hsm.FileCopyOrder)
*/
protected void process(FileCopyOrder order) throws Exception {
// TODO Auto-generated method stub
}
}
| medicayun/medicayundicom | dcm4jboss-all/tags/DCM4JBOSS_2_7_6/dcm4jboss-sar/src/java/org/dcm4chex/archive/hsm/FTPArchiverService.java | Java | apache-2.0 | 2,377 |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.uif.view;
import org.kuali.rice.krad.datadictionary.parse.BeanTag;
import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute;
import org.kuali.rice.krad.inquiry.InquirableImpl;
import org.kuali.rice.krad.uif.UifConstants.ViewType;
/**
* Type of <code>View</code> that provides a read-only display of a record of
* data (object instance)
*
* <p>
* The <code>InquiryView</code> provides the interface for the Inquiry
* framework. It works with the <code>Inquirable</code> service and inquiry
* controller. The view does render a form to support the configuration of
* actions to perform operations on the data.
* </p>
*
* <p>
* Inquiry views are primarily configured by the object class they are
* associated with. This provides the default dictionary information for the
* fields. If more than one inquiry view is needed for the same object class,
* the view name can be used to further identify an unique view
* </p>
*
* @author Kuali Rice Team ([email protected])
*/
@BeanTag(name = "inquiryView", parent = "Uif-InquiryView")
public class InquiryView extends FormView {
private static final long serialVersionUID = 716926008488403616L;
private Class<?> dataObjectClassName;
public InquiryView() {
super();
setViewTypeName(ViewType.INQUIRY);
setApplyDirtyCheck(false);
setTranslateCodesOnReadOnlyDisplay(true);
}
/**
* The following initialization is performed:
*
* <ul>
* <li>Set the abstractTypeClasses map for the inquiry object path</li>
* </ul>
*
* {@inheritDoc}
*/
@Override
public void performInitialization(Object model) {
super.performInitialization(model);
getObjectPathToConcreteClassMapping().put(getDefaultBindingObjectPath(), getDataObjectClassName());
}
/**
* Class name for the object the inquiry applies to
*
* <p>
* The object class name is used to pick up a dictionary entry which will
* feed the attribute field definitions and other configuration. In addition
* it is used to configure the <code>Inquirable</code> which will carry out
* the inquiry action
* </p>
*
* @return inquiry object class
*/
@BeanTagAttribute
public Class<?> getDataObjectClassName() {
return this.dataObjectClassName;
}
/**
* Setter for the object class name
*
* @param dataObjectClassName
*/
public void setDataObjectClassName(Class<?> dataObjectClassName) {
this.dataObjectClassName = dataObjectClassName;
}
}
| ricepanda/rice-git3 | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/view/InquiryView.java | Java | apache-2.0 | 3,336 |
/*
* 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.io;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.testtools.FileBasedTestCase;
import org.junit.Test;
/**
* This class ensure the correctness of {@link FileUtils#directoryContains(File,File)}.
*
* @see FileUtils#directoryContains(File, File)
* @since 2.2
* @version $Id$
*/
public class FileUtilsDirectoryContainsTestCase extends FileBasedTestCase {
private File directory1;
private File directory2;
private File directory3;
private File file1;
private File file1ByRelativeDirectory2;
private File file2;
private File file2ByRelativeDirectory1;
private File file3;
final File top = getTestDirectory();
public FileUtilsDirectoryContainsTestCase(final String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
top.mkdirs();
directory1 = new File(top, "directory1");
directory2 = new File(top, "directory2");
directory3 = new File(directory2, "directory3");
directory1.mkdir();
directory2.mkdir();
directory3.mkdir();
file1 = new File(directory1, "file1");
file2 = new File(directory2, "file2");
file3 = new File(top, "file3");
// Tests case with relative path
file1ByRelativeDirectory2 = new File(getTestDirectory(), "directory2/../directory1/file1");
file2ByRelativeDirectory1 = new File(getTestDirectory(), "directory1/../directory2/file2");
FileUtils.touch(file1);
FileUtils.touch(file2);
FileUtils.touch(file3);
}
@Override
protected void tearDown() throws Exception {
FileUtils.deleteDirectory(top);
}
@Test
public void testCanonicalPath() throws IOException {
assertTrue(FileUtils.directoryContains(directory1, file1ByRelativeDirectory2));
assertTrue(FileUtils.directoryContains(directory2, file2ByRelativeDirectory1));
assertFalse(FileUtils.directoryContains(directory1, file2ByRelativeDirectory1));
assertFalse(FileUtils.directoryContains(directory2, file1ByRelativeDirectory2));
}
@Test
public void testDirectoryContainsDirectory() throws IOException {
assertTrue(FileUtils.directoryContains(top, directory1));
assertTrue(FileUtils.directoryContains(top, directory2));
assertTrue(FileUtils.directoryContains(top, directory3));
assertTrue(FileUtils.directoryContains(directory2, directory3));
}
@Test
public void testDirectoryContainsFile() throws IOException {
assertTrue(FileUtils.directoryContains(directory1, file1));
assertTrue(FileUtils.directoryContains(directory2, file2));
}
@Test
public void testDirectoryDoesNotContainFile() throws IOException {
assertFalse(FileUtils.directoryContains(directory1, file2));
assertFalse(FileUtils.directoryContains(directory2, file1));
assertFalse(FileUtils.directoryContains(directory1, file3));
assertFalse(FileUtils.directoryContains(directory2, file3));
}
@Test
public void testDirectoryDoesNotContainsDirectory() throws IOException {
assertFalse(FileUtils.directoryContains(directory1, top));
assertFalse(FileUtils.directoryContains(directory2, top));
assertFalse(FileUtils.directoryContains(directory3, top));
assertFalse(FileUtils.directoryContains(directory3, directory2));
}
@Test
public void testDirectoryDoesNotExist() throws IOException {
final File dir = new File("DOESNOTEXIST");
assertFalse(dir.exists());
try {
assertFalse(FileUtils.directoryContains(dir, file1));
fail("Expected " + IllegalArgumentException.class.getName());
} catch (final IllegalArgumentException e) {
// expected
}
}
@Test
public void testSameFile() throws IOException {
try {
assertTrue(FileUtils.directoryContains(file1, file1));
fail("Expected " + IllegalArgumentException.class.getName());
} catch (final IllegalArgumentException e) {
// expected
}
}
@Test
public void testIO466() throws IOException {
File fooFile = new File(directory1.getParent(), "directory1.txt");
assertFalse(FileUtils.directoryContains(directory1, fooFile));
}
@Test
public void testFileDoesNotExist() throws IOException {
assertFalse(FileUtils.directoryContains(top, null));
final File file = new File("DOESNOTEXIST");
assertFalse(file.exists());
assertFalse(FileUtils.directoryContains(top, file));
}
/**
* Test to demonstrate a file which does not exist returns false
* @throws IOException If an I/O error occurs
*/
@Test
public void testFileDoesNotExistBug() throws IOException {
final File file = new File(top, "DOESNOTEXIST");
assertTrue("Check directory exists", top.exists());
assertFalse("Check file does not exist", file.exists());
assertFalse("Direcory does not contain unrealized file", FileUtils.directoryContains(top, file));
}
@Test
public void testUnrealizedContainment() throws IOException {
final File dir = new File("DOESNOTEXIST");
final File file = new File(dir, "DOESNOTEXIST2");
assertFalse(dir.exists());
assertFalse(file.exists());
try {
assertTrue(FileUtils.directoryContains(dir, file));
} catch (final IllegalArgumentException e) {
// expected
}
}
}
| jankill/commons-io | src/test/java/org/apache/commons/io/FileUtilsDirectoryContainsTestCase.java | Java | apache-2.0 | 6,426 |
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xnio.conduits;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import org.xnio.channels.StreamSinkChannel;
/**
* A stream source conduit which limits the length of input.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class FixedLengthStreamSourceConduit extends AbstractStreamSourceConduit<StreamSourceConduit> implements StreamSourceConduit {
private long remaining;
/**
* Construct a new instance.
*
* @param next the conduit to limit
* @param remaining the number of bytes to limit to
*/
public FixedLengthStreamSourceConduit(final StreamSourceConduit next, final long remaining) {
super(next);
this.remaining = remaining;
}
public long transferTo(final long position, final long count, final FileChannel target) throws IOException {
long length = this.remaining;
if (length > 0) {
final long res = next.transferTo(position, Math.min(count, length), target);
if (res > 0L) {
this.remaining = length - res;
}
return res;
} else {
return 0;
}
}
public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException {
long length = this.remaining;
if (length > 0) {
final long res = next.transferTo(Math.min(count, length), throughBuffer, target);
if (res > 0L) {
this.remaining = length - res;
}
return res;
} else {
return -1L;
}
}
public int read(final ByteBuffer dst) throws IOException {
final int limit = dst.limit();
final int pos = dst.position();
final int res;
final long length = this.remaining;
if (length == 0L) {
return -1;
}
if (limit - pos > length) {
dst.limit(pos + (int) length);
try {
res = next.read(dst);
} finally {
dst.limit(limit);
}
} else {
res = next.read(dst);
}
if (res > 0L) {
this.remaining = length - res;
}
return res;
}
public long read(final ByteBuffer[] dsts, final int offs, final int len) throws IOException {
if (len == 0) {
return 0L;
} else if (len == 1) {
return read(dsts[offs]);
}
final long length = this.remaining;
if (length == 0L) {
return -1L;
}
long res;
int lim;
// The total amount of buffer space discovered so far.
long t = 0L;
for (int i = 0; i < length; i ++) {
final ByteBuffer buffer = dsts[i + offs];
// Grow the discovered buffer space by the remaining size of the current buffer.
// We want to capture the limit so we calculate "remaining" ourselves.
t += (lim = buffer.limit()) - buffer.position();
if (t > length) {
// only read up to this point, and trim the last buffer by the number of extra bytes
buffer.limit(lim - (int) (t - length));
try {
res = next.read(dsts, offs, i + 1);
if (res > 0L) {
this.remaining = length - res;
}
return res;
} finally {
// restore the original limit
buffer.limit(lim);
}
}
}
// the total buffer space is less than the remaining count.
res = t == 0L ? 0L : next.read(dsts, offs, len);
if (res > 0L) {
this.remaining = length - res;
}
return res;
}
/**
* Get the number of bytes which remain available to read.
*
* @return the number of bytes which remain available to read
*/
public long getRemaining() {
return remaining;
}
}
| stuartwdouglas/xnio | api/src/main/java/org/xnio/conduits/FixedLengthStreamSourceConduit.java | Java | apache-2.0 | 4,795 |
/*
* $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/impl/auth/DigestSchemeFactory.java $
* $Revision: 534839 $
* $Date: 2007-05-03 06:03:41 -0700 (Thu, 03 May 2007) $
*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.auth;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.params.HttpParams;
/**
*
* @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
*
* @since 4.0
*/
public class DigestSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new DigestScheme();
}
}
| haikuowuya/android_system_code | src/org/apache/http/impl/auth/DigestSchemeFactory.java | Java | apache-2.0 | 1,861 |
/**
*
* Copyright 2017 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.wildfly.swarm.microprofile.jwtauth.detect;
import org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor;
import org.jboss.shrinkwrap.descriptor.api.webcommon31.LoginConfigType;
import org.wildfly.swarm.spi.meta.WebXmlFractionDetector;
/**
* A detector that looks at the WebXml descriptor for a login-config/auth-method of type MP-JWT.
*/
public class MPJWTAuthWebXmlDetector extends WebXmlFractionDetector {
@Override
public String artifactId() {
return "microprofile-jwt";
}
/**
* @return true of the WebXml indicates an MP-JWT auth-method
*/
@Override
protected boolean doDetect() {
super.doDetect();
boolean isMPJWTAuth = false;
if (webXMl.getAllLoginConfig().size() > 0) {
LoginConfigType<WebAppDescriptor> lc = webXMl.getOrCreateLoginConfig();
isMPJWTAuth = lc.getAuthMethod() != null && lc.getAuthMethod().equalsIgnoreCase("MP-JWT");
}
return isMPJWTAuth;
}
}
| nelsongraca/wildfly-swarm | fractions/microprofile/microprofile-jwt/src/main/java/org/wildfly/swarm/microprofile/jwtauth/detect/MPJWTAuthWebXmlDetector.java | Java | apache-2.0 | 1,651 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.plugin.mongodb;
import com.google.common.collect.ImmutableList;
import com.mongodb.client.ListIndexesIterable;
import io.trino.spi.connector.SortOrder;
import org.bson.Document;
import java.util.List;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class MongoIndex
{
private final String name;
private final List<MongodbIndexKey> keys;
private final boolean unique;
public static List<MongoIndex> parse(ListIndexesIterable<Document> indexes)
{
ImmutableList.Builder<MongoIndex> builder = ImmutableList.builder();
for (Document index : indexes) {
// TODO: v, ns, sparse fields
Document key = (Document) index.get("key");
String name = index.getString("name");
boolean unique = index.getBoolean("unique", false);
if (key.containsKey("_fts")) { // Full Text Search
continue;
}
builder.add(new MongoIndex(name, parseKey(key), unique));
}
return builder.build();
}
private static List<MongodbIndexKey> parseKey(Document key)
{
ImmutableList.Builder<MongodbIndexKey> builder = ImmutableList.builder();
for (String name : key.keySet()) {
Object value = key.get(name);
if (value instanceof Number) {
int order = ((Number) value).intValue();
checkState(order == 1 || order == -1, "Unknown index sort order");
builder.add(new MongodbIndexKey(name, order == 1 ? SortOrder.ASC_NULLS_LAST : SortOrder.DESC_NULLS_LAST));
}
else if (value instanceof String) {
builder.add(new MongodbIndexKey(name, (String) value));
}
else {
throw new UnsupportedOperationException("Unknown index type: " + value.toString());
}
}
return builder.build();
}
public MongoIndex(String name, List<MongodbIndexKey> keys, boolean unique)
{
this.name = name;
this.keys = keys;
this.unique = unique;
}
public String getName()
{
return name;
}
public List<MongodbIndexKey> getKeys()
{
return keys;
}
public boolean isUnique()
{
return unique;
}
public static class MongodbIndexKey
{
private final String name;
private final Optional<SortOrder> sortOrder;
private final Optional<String> type;
public MongodbIndexKey(String name, SortOrder sortOrder)
{
this(name, Optional.of(sortOrder), Optional.empty());
}
public MongodbIndexKey(String name, String type)
{
this(name, Optional.empty(), Optional.of(type));
}
public MongodbIndexKey(String name, Optional<SortOrder> sortOrder, Optional<String> type)
{
this.name = requireNonNull(name, "name is null");
this.sortOrder = sortOrder;
this.type = type;
}
public String getName()
{
return name;
}
public Optional<SortOrder> getSortOrder()
{
return sortOrder;
}
public Optional<String> getType()
{
return type;
}
}
}
| electrum/presto | plugin/trino-mongodb/src/main/java/io/trino/plugin/mongodb/MongoIndex.java | Java | apache-2.0 | 3,951 |
/**
* Copyright 2014 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 org.fusesource.camel.component.sap.model.idoc.util;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.ecore.EObject;
import org.fusesource.camel.component.sap.model.idoc.*;
/**
* <!-- begin-user-doc -->
* The <b>Adapter Factory</b> for the model.
* It provides an adapter <code>createXXX</code> method for each class of the model.
* <!-- end-user-doc -->
* @see org.fusesource.camel.component.sap.model.idoc.IdocPackage
* @generated
*/
public class IdocAdapterFactory extends AdapterFactoryImpl {
/**
* The cached model package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static IdocPackage modelPackage;
/**
* Creates an instance of the adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IdocAdapterFactory() {
if (modelPackage == null) {
modelPackage = IdocPackage.eINSTANCE;
}
}
/**
* Returns whether this factory is applicable for the type of the object.
* <!-- begin-user-doc -->
* This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model.
* <!-- end-user-doc -->
* @return whether this factory is applicable for the type of the object.
* @generated
*/
@Override
public boolean isFactoryForType(Object object) {
if (object == modelPackage) {
return true;
}
if (object instanceof EObject) {
return ((EObject)object).eClass().getEPackage() == modelPackage;
}
return false;
}
/**
* The switch that delegates to the <code>createXXX</code> methods.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IdocSwitch<Adapter> modelSwitch =
new IdocSwitch<Adapter>() {
@Override
public Adapter caseDocumentList(DocumentList object) {
return createDocumentListAdapter();
}
@Override
public Adapter caseDocument(Document object) {
return createDocumentAdapter();
}
@Override
public Adapter caseSegment(Segment object) {
return createSegmentAdapter();
}
@Override
public Adapter caseSegmentChildren(SegmentChildren object) {
return createSegmentChildrenAdapter();
}
@Override
public <S extends Segment> Adapter caseSegmentList(SegmentList<S> object) {
return createSegmentListAdapter();
}
@Override
public Adapter defaultCase(EObject object) {
return createEObjectAdapter();
}
};
/**
* Creates an adapter for the <code>target</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param target the object to adapt.
* @return the adapter for the <code>target</code>.
* @generated
*/
@Override
public Adapter createAdapter(Notifier target) {
return modelSwitch.doSwitch((EObject)target);
}
/**
* Creates a new adapter for an object of class '{@link org.fusesource.camel.component.sap.model.idoc.DocumentList <em>Document List</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.fusesource.camel.component.sap.model.idoc.DocumentList
* @generated
*/
public Adapter createDocumentListAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.fusesource.camel.component.sap.model.idoc.Document <em>Document</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.fusesource.camel.component.sap.model.idoc.Document
* @generated
*/
public Adapter createDocumentAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.fusesource.camel.component.sap.model.idoc.Segment <em>Segment</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.fusesource.camel.component.sap.model.idoc.Segment
* @generated
*/
public Adapter createSegmentAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.fusesource.camel.component.sap.model.idoc.SegmentChildren <em>Segment Children</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.fusesource.camel.component.sap.model.idoc.SegmentChildren
* @generated
*/
public Adapter createSegmentChildrenAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link org.fusesource.camel.component.sap.model.idoc.SegmentList <em>Segment List</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see org.fusesource.camel.component.sap.model.idoc.SegmentList
* @generated
*/
public Adapter createSegmentListAdapter() {
return null;
}
/**
* Creates a new adapter for the default case.
* <!-- begin-user-doc -->
* This default implementation returns null.
* <!-- end-user-doc -->
* @return the new adapter.
* @generated
*/
public Adapter createEObjectAdapter() {
return null;
}
} //IdocAdapterFactory
| janstey/fuse-1 | components/camel-sap/org.fusesource.camel.component.sap.model/src/org/fusesource/camel/component/sap/model/idoc/util/IdocAdapterFactory.java | Java | apache-2.0 | 6,508 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.base.metrics;
import org.chromium.base.annotations.JNINamespace;
/**
* Java API which exposes the registered histograms on the native side as
* JSON test.
*/
@JNINamespace("base::android")
public final class StatisticsRecorderAndroid {
private StatisticsRecorderAndroid() {}
/**
* @return All the registered histograms as JSON text.
*/
public static String toJson() {
return nativeToJson();
}
private static native String nativeToJson();
} | mogoweb/365browser | app/src/main/java/org/chromium/base/metrics/StatisticsRecorderAndroid.java | Java | apache-2.0 | 673 |
/*
* Copyright 2018 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.media2.test.service.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import androidx.media2.session.SessionCommand;
import androidx.media2.session.SessionCommandGroup;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Tests {@link SessionCommand} and {@link SessionCommandGroup}.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class SessionCommandTest {
// Prefix for all command codes
private static final String PREFIX_COMMAND_CODE = "COMMAND_CODE_";
private static final List<String> PREFIX_COMMAND_CODES = new ArrayList<>();
static {
PREFIX_COMMAND_CODES.add("COMMAND_CODE_PLAYER_");
PREFIX_COMMAND_CODES.add("COMMAND_CODE_VOLUME_");
PREFIX_COMMAND_CODES.add("COMMAND_CODE_SESSION_");
PREFIX_COMMAND_CODES.add("COMMAND_CODE_LIBRARY_");
}
/**
* Test possible typos in naming
*/
@Test
public void codes_name() {
List<Field> fields = getSessionCommandsFields("");
for (int i = 0; i < fields.size(); i++) {
String name = fields.get(i).getName();
boolean matches = false;
if (name.startsWith("COMMAND_VERSION_") || name.equals("COMMAND_CODE_CUSTOM")) {
matches = true;
}
if (!matches) {
for (int j = 0; j < PREFIX_COMMAND_CODES.size(); j++) {
if (name.startsWith(PREFIX_COMMAND_CODES.get(j))) {
matches = true;
break;
}
}
}
assertTrue("Unexpected constant " + name, matches);
}
}
/**
* Tests possible code duplications in values
*/
@Test
public void codes_valueDuplication() throws IllegalAccessException {
List<Field> fields = getSessionCommandsFields(PREFIX_COMMAND_CODE);
Set<Integer> values = new HashSet<>();
for (int i = 0; i < fields.size(); i++) {
Integer value = fields.get(i).getInt(null);
assertTrue(values.add(value));
}
}
/**
* Tests whether codes are continuous
*/
@Test
@Ignore
public void codes_valueContinuous() throws IllegalAccessException {
for (int i = 0; i < PREFIX_COMMAND_CODES.size(); i++) {
List<Field> fields = getSessionCommandsFields(PREFIX_COMMAND_CODES.get(i));
List<Integer> values = new ArrayList<>();
for (int j = 0; j < fields.size(); j++) {
values.add(fields.get(j).getInt(null));
}
Collections.sort(values);
for (int j = 1; j < values.size(); j++) {
assertEquals(
"Command code isn't continuous. Missing " + (values.get(j - 1) + 1)
+ " in " + PREFIX_COMMAND_CODES.get(i),
((int) values.get(j - 1)) + 1, (int) values.get(j));
}
}
}
@Test
public void addAllPredefinedCommands_withVersion1_notHaveVersion2Commands() {
SessionCommandGroup.Builder builder = new SessionCommandGroup.Builder();
builder.addAllPredefinedCommands(SessionCommand.COMMAND_VERSION_1);
SessionCommandGroup commands = builder.build();
assertFalse(commands.hasCommand(SessionCommand.COMMAND_CODE_SESSION_SET_MEDIA_URI));
assertFalse(commands.hasCommand(SessionCommand.COMMAND_CODE_PLAYER_MOVE_PLAYLIST_ITEM));
}
@Test
public void addAllPredefinedCommands_withVersion2_hasVersion2Commands() {
SessionCommandGroup.Builder builder = new SessionCommandGroup.Builder();
builder.addAllPredefinedCommands(SessionCommand.COMMAND_VERSION_2);
SessionCommandGroup commands = builder.build();
assertTrue(commands.hasCommand(SessionCommand.COMMAND_CODE_SESSION_SET_MEDIA_URI));
assertTrue(commands.hasCommand(SessionCommand.COMMAND_CODE_PLAYER_MOVE_PLAYLIST_ITEM));
}
private static List<Field> getSessionCommandsFields(String prefix) {
final List<Field> list = new ArrayList<>();
final Field[] fields = SessionCommand.class.getFields();
if (fields != null) {
for (int i = 0; i < fields.length; i++) {
if (isPublicStaticFinalInt(fields[i])
&& fields[i].getName().startsWith(prefix)) {
list.add(fields[i]);
}
}
}
return list;
}
private static boolean isPublicStaticFinalInt(Field field) {
if (field.getType() != int.class) {
return false;
}
int modifier = field.getModifiers();
return Modifier.isPublic(modifier) && Modifier.isStatic(modifier)
&& Modifier.isFinal(modifier);
}
}
| AndroidX/androidx | media2/media2-session/version-compat-tests/previous/service/src/androidTest/java/androidx/media2/test/service/tests/SessionCommandTest.java | Java | apache-2.0 | 5,807 |
/*
* Copyright 2011 The Closure Compiler 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.debugging.sourcemap;
/**
* A list of currently support SourceMap format revisions.
*/
public enum SourceMapFormat {
/** The latest "stable" format */
DEFAULT,
/** V3: A nice compact format */
V3;
}
| GoogleChromeLabs/chromeos_smart_card_connector | third_party/closure-compiler/src/src/com/google/debugging/sourcemap/SourceMapFormat.java | Java | apache-2.0 | 846 |
/*
* Copyright 2013 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 com.google.errorprone.bugpatterns;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author [email protected] (Steven Goldfeder)
*/
@RunWith(JUnit4.class)
public class InjectScopeAnnotationOnInterfaceOrAbstractClassTest {
private CompilationTestHelper compilationHelper;
@Before
public void setUp() {
compilationHelper =
CompilationTestHelper.newInstance(
InjectScopeAnnotationOnInterfaceOrAbstractClass.class, getClass());
}
@Test
public void testPositiveCase() throws Exception {
compilationHelper
.addSourceFile("InjectScopeAnnotationOnInterfaceOrAbstractClassPositiveCases.java")
.doTest();
}
@Test
public void testNegativeCase() throws Exception {
compilationHelper
.addSourceFile("InjectScopeAnnotationOnInterfaceOrAbstractClassNegativeCases.java")
.doTest();
}
}
| Turbo87/error-prone | core/src/test/java/com/google/errorprone/bugpatterns/InjectScopeAnnotationOnInterfaceOrAbstractClassTest.java | Java | apache-2.0 | 1,615 |
package org.gradle;
import org.junit.Before;
public abstract class AbstractTest {
protected int value = 0;
@Before
public void before() {
value = 1;
}
}
| gstevey/gradle | subprojects/testing-jvm/src/integTest/resources/org/gradle/testing/junit/JUnitJdkNavigationIntegrationTest/shouldNotNavigateToJdkClasses/src/test/java/org/gradle/AbstractTest.java | Java | apache-2.0 | 181 |
/*
* Copyright 2004-2006 Stefan Reuter
*
* 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.asteriskjava.live;
import java.io.Serializable;
import org.asteriskjava.util.AstUtil;
/**
* Represents a Caller*ID containing name and number.
* <br>
* Objects of this type are immutable.
*
* @author srt
* @version $Id$
* @since 0.3
*/
public class CallerId implements Serializable
{
/**
* Serial version identifier.
*/
private static final long serialVersionUID = 6498024163374551005L;
private final String name;
private final String number;
/**
* Creates a new CallerId.
*
* @param name the Caller*ID name.
* @param number the Caller*ID number.
*/
public CallerId(String name, String number)
{
this.name = (AstUtil.isNull(name)) ? null : name;
this.number = (AstUtil.isNull(number)) ? null : number;
}
/**
* Returns the Caller*ID name.
*
* @return the Caller*ID name.
*/
public String getName()
{
return name;
}
/**
* Returns the the Caller*ID number.
*
* @return the Caller*ID number.
*/
public String getNumber()
{
return number;
}
/**
* Parses a caller id string in the form
* <code>"Some Name" <1234></code> to a CallerId object.
*
* @param s the caller id string to parse.
* @return the corresponding CallerId object which is never <code>null</code>.
* @see AstUtil#parseCallerId(String)
*/
public static CallerId valueOf(String s)
{
final String[] parsedCallerId;
parsedCallerId = AstUtil.parseCallerId(s);
return new CallerId(parsedCallerId[0], parsedCallerId[1]);
}
/**
* Returns a string representation of this CallerId in the form
* <code>"Some Name" <1234></code>.
*/
@Override
public String toString()
{
final StringBuilder sb;
sb = new StringBuilder();
if (name != null)
{
sb.append("\"");
sb.append(name);
sb.append("\"");
if (number != null)
{
sb.append(" ");
}
}
if (number != null)
{
sb.append("<");
sb.append(number);
sb.append(">");
}
return sb.toString();
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
CallerId callerId = (CallerId) o;
if (name != null ? !name.equals(callerId.name) : callerId.name != null)
{
return false;
}
if (number != null ? !number.equals(callerId.number) : callerId.number != null)
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (number != null ? number.hashCode() : 0);
return result;
}
}
| pk1057/asterisk-java | src/main/java/org/asteriskjava/live/CallerId.java | Java | apache-2.0 | 3,681 |
package org.ifsoft.rtp;
import org.ifsoft.*;
public abstract class RTCPPSPacket extends RTCPFeedbackPacket
{
public static RTCPPSPacket createPacket(Byte firstByte)
{
Byte _var0 = firstByte;
if(_var0.byteValue() == 1)
return new RTCPPLIPacket();
if(_var0.byteValue() == 15)
return new RTCPAFBPacket();
else
return null;
}
public RTCPPSPacket(Byte feedbackMessageType)
{
super(feedbackMessageType);
}
}
| Gugli/Openfire | src/plugins/rayo/src/java/org/ifsoft/rtp/RTCPPSPacket.java | Java | apache-2.0 | 506 |
/*
* 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.androidenterprise.model;
/**
* Model definition for AdministratorWebTokenSpecPrivateApps.
*
* <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 Google Play EMM 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 AdministratorWebTokenSpecPrivateApps extends com.google.api.client.json.GenericJson {
/**
* Whether the Private Apps page is displayed. Default is true.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enabled;
/**
* Whether the Private Apps page is displayed. Default is true.
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnabled() {
return enabled;
}
/**
* Whether the Private Apps page is displayed. Default is true.
* @param enabled enabled or {@code null} for none
*/
public AdministratorWebTokenSpecPrivateApps setEnabled(java.lang.Boolean enabled) {
this.enabled = enabled;
return this;
}
@Override
public AdministratorWebTokenSpecPrivateApps set(String fieldName, Object value) {
return (AdministratorWebTokenSpecPrivateApps) super.set(fieldName, value);
}
@Override
public AdministratorWebTokenSpecPrivateApps clone() {
return (AdministratorWebTokenSpecPrivateApps) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-androidenterprise/v1/1.31.0/com/google/api/services/androidenterprise/model/AdministratorWebTokenSpecPrivateApps.java | Java | apache-2.0 | 2,328 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.sql.planner.assertions;
import io.trino.Session;
import io.trino.metadata.Metadata;
import io.trino.sql.planner.Symbol;
import io.trino.sql.planner.plan.AssignUniqueId;
import io.trino.sql.planner.plan.PlanNode;
import java.util.Optional;
import static com.google.common.base.MoreObjects.toStringHelper;
public class AssignUniqueIdMatcher
implements RvalueMatcher
{
@Override
public Optional<Symbol> getAssignedSymbol(PlanNode node, Session session, Metadata metadata, SymbolAliases symbolAliases)
{
if (!(node instanceof AssignUniqueId)) {
return Optional.empty();
}
AssignUniqueId assignUniqueIdNode = (AssignUniqueId) node;
return Optional.of(assignUniqueIdNode.getIdColumn());
}
@Override
public String toString()
{
return toStringHelper(this)
.toString();
}
}
| ebyhr/presto | core/trino-main/src/test/java/io/trino/sql/planner/assertions/AssignUniqueIdMatcher.java | Java | apache-2.0 | 1,459 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.sql.tree;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;
public class JoinOn
extends JoinCriteria
{
private final Expression expression;
public JoinOn(Expression expression)
{
this.expression = requireNonNull(expression, "expression is null");
}
public Expression getExpression()
{
return expression;
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false;
}
JoinOn o = (JoinOn) obj;
return Objects.equals(expression, o.expression);
}
@Override
public int hashCode()
{
return Objects.hash(expression);
}
@Override
public String toString()
{
return toStringHelper(this)
.addValue(expression)
.toString();
}
@Override
public List<Node> getNodes()
{
return ImmutableList.of(expression);
}
}
| electrum/presto | core/trino-parser/src/main/java/io/trino/sql/tree/JoinOn.java | Java | apache-2.0 | 1,779 |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.mobile.windows.api.services.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.mobile.windows.api.common.PluginConstants;
import org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.SyncmlMessageFormatException;
import org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.SyncmlOperationException;
import org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.WindowsConfigurationException;
import org.wso2.carbon.device.mgt.mobile.windows.api.common.exceptions.WindowsDeviceEnrolmentException;
import org.wso2.carbon.device.mgt.mobile.windows.api.common.util.AuthenticationInfo;
import org.wso2.carbon.device.mgt.mobile.windows.api.common.util.DeviceUtil;
import org.wso2.carbon.device.mgt.mobile.windows.api.common.util.WindowsAPIUtils;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.ItemTag;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.ReplaceTag;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.SyncmlDocument;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.SyncmlHeader;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.WindowsOperationException;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.util.Constants;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.util.OperationCode;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.util.OperationHandler;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.util.OperationReply;
import org.wso2.carbon.device.mgt.mobile.windows.api.operations.util.SyncmlParser;
import org.wso2.carbon.device.mgt.mobile.windows.api.services.DeviceManagementService;
import org.wso2.carbon.device.mgt.mobile.windows.impl.dto.MobileCacheEntry;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import static org.wso2.carbon.device.mgt.mobile.windows.api.common.util.WindowsAPIUtils.convertToDeviceIdentifierObject;
public class DeviceManagementServiceImpl implements DeviceManagementService {
private static Log log = LogFactory.getLog(
org.wso2.carbon.device.mgt.mobile.windows.api.services.syncml.impl.SyncmlServiceImpl.class);
@Override
public Response getResponse(Document request) throws WindowsDeviceEnrolmentException, WindowsOperationException,
NotificationManagementException, WindowsConfigurationException {
int msgId;
int sessionId;
String user;
String token;
String response;
SyncmlDocument syncmlDocument;
List<? extends Operation> pendingOperations;
OperationHandler operationHandler = new OperationHandler();
OperationReply operationReply = new OperationReply();
try {
if (SyncmlParser.parseSyncmlPayload(request) != null) {
syncmlDocument = SyncmlParser.parseSyncmlPayload(request);
SyncmlHeader syncmlHeader = syncmlDocument.getHeader();
sessionId = syncmlHeader.getSessionId();
user = syncmlHeader.getSource().getLocName();
DeviceIdentifier deviceIdentifier = convertToDeviceIdentifierObject(syncmlHeader.getSource().
getLocURI());
msgId = syncmlHeader.getMsgID();
if ((PluginConstants.SyncML.SYNCML_FIRST_MESSAGE_ID == msgId) &&
(PluginConstants.SyncML.SYNCML_FIRST_SESSION_ID == sessionId)) {
token = syncmlHeader.getCredential().getData();
MobileCacheEntry cacheToken = DeviceUtil.getTokenEntry(token);
DeviceUtil.persistChallengeToken(token, deviceIdentifier.getId(), user);
PrivilegedCarbonContext carbonCtx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonCtx.setTenantId(cacheToken.getTenanatID(), true);
if ((cacheToken.getUsername() != null) && (cacheToken.getUsername().equals(user))) {
if (modifyEnrollWithMoreDetail(request, cacheToken.getTenantDomain(), cacheToken.getTenanatID())) {
pendingOperations = operationHandler.getPendingOperations(syncmlDocument);
response = operationReply.generateReply(syncmlDocument, pendingOperations);
return Response.status(Response.Status.OK).entity(response).build();
} else {
String msg = "Error occurred in while modify the enrollment.";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
} else {
String msg = "Authentication failure due to incorrect credentials.";
log.error(msg);
return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build();
}
} else {
MobileCacheEntry cacheToken = DeviceUtil.getTokenEntryFromDeviceId(deviceIdentifier.getId());
PrivilegedCarbonContext carbonCtx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonCtx.setTenantId(cacheToken.getTenanatID());
if ((syncmlDocument.getBody().getAlert() != null)) {
if (!syncmlDocument.getBody().getAlert().getData().equals(Constants.DISENROLL_ALERT_DATA)) {
pendingOperations = operationHandler.getPendingOperations(syncmlDocument);
return Response.ok().entity(operationReply.generateReply(
syncmlDocument, pendingOperations)).build();
} else {
if (WindowsAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false) != null) {
WindowsAPIUtils.getDeviceManagementService().disenrollDevice(deviceIdentifier);
return Response.ok().entity(operationReply.generateReply(syncmlDocument, null)).build();
} else {
String msg = "Enrolled device can not be found in the server.";
log.error(msg);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
}
} else {
pendingOperations = operationHandler.getPendingOperations(syncmlDocument);
return Response.ok().entity(operationReply.generateReply(
syncmlDocument, pendingOperations)).build();
}
}
}
} catch (SyncmlMessageFormatException e) {
String msg = "Error occurred while parsing syncml request.";
log.error(msg, e);
throw new WindowsOperationException(msg, e);
} catch (OperationManagementException e) {
String msg = "Cannot access operation management service.";
log.error(msg, e);
throw new WindowsOperationException(msg, e);
} catch (SyncmlOperationException e) {
String msg = "Error occurred while getting effective feature.";
log.error(msg, e);
throw new WindowsConfigurationException(msg, e);
} catch (DeviceManagementException e) {
String msg = "Failure occurred in dis-enrollment flow.";
log.error(msg, e);
throw new WindowsOperationException(msg, e);
}
return null;
}
/**
* Enroll phone device
*
* @param request Device syncml request for the server side.
* @return enroll state
* @throws WindowsDeviceEnrolmentException
* @throws WindowsOperationException
*/
private boolean modifyEnrollWithMoreDetail(Document request, String tenantDomain, int tenantId) throws WindowsDeviceEnrolmentException,
WindowsOperationException {
String devMan = null;
String devMod = null;
boolean status = false;
String user;
SyncmlDocument syncmlDocument;
try {
syncmlDocument = SyncmlParser.parseSyncmlPayload(request);
ReplaceTag replace = syncmlDocument.getBody().getReplace();
List<ItemTag> itemList = replace.getItems();
for (ItemTag itemTag : itemList) {
String locURI = itemTag.getSource().getLocURI();
if (OperationCode.Info.MANUFACTURER.getCode().equals(locURI)) {
devMan = itemTag.getData();
}
if (OperationCode.Info.DEVICE_MODEL.getCode().equals(locURI)) {
devMod = itemTag.getData();
}
}
user = syncmlDocument.getHeader().getSource().getLocName();
AuthenticationInfo authenticationInfo = new AuthenticationInfo();
authenticationInfo.setUsername(user);
authenticationInfo.setTenantId(tenantId);
authenticationInfo.setTenantDomain(tenantDomain);
WindowsAPIUtils.startTenantFlow(authenticationInfo);
DeviceIdentifier deviceIdentifier = convertToDeviceIdentifierObject(syncmlDocument.
getHeader().getSource().getLocURI());
Device existingDevice = WindowsAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier);
if (!existingDevice.getProperties().isEmpty()) {
List<Device.Property> existingProperties = new ArrayList<>();
Device.Property vendorProperty = new Device.Property();
vendorProperty.setName(PluginConstants.SyncML.VENDOR);
vendorProperty.setValue(devMan);
existingProperties.add(vendorProperty);
Device.Property deviceModelProperty = new Device.Property();
deviceModelProperty.setName(PluginConstants.SyncML.MODEL);
deviceModelProperty.setValue(devMod);
existingProperties.add(deviceModelProperty);
existingDevice.setProperties(existingProperties);
existingDevice.setDeviceIdentifier(syncmlDocument.getHeader().getSource().getLocURI());
existingDevice.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
status = WindowsAPIUtils.getDeviceManagementService().modifyEnrollment(existingDevice);
return status;
}
} catch (DeviceManagementException e) {
throw new WindowsDeviceEnrolmentException("Failure occurred while enrolling device.", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return status;
}
}
| harshanL/carbon-device-mgt-plugins | components/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows.api/src/main/java/org/wso2/carbon/device/mgt/mobile/windows/api/services/impl/DeviceManagementServiceImpl.java | Java | apache-2.0 | 12,283 |
/*
* Copyright 2014 Goldman Sachs.
*
* 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.gs.collections.impl.lazy.primitive;
import com.gs.collections.api.iterator.BooleanIterator;
import com.gs.collections.impl.block.factory.primitive.BooleanPredicates;
import com.gs.collections.impl.list.mutable.primitive.BooleanArrayList;
import com.gs.collections.impl.math.MutableInteger;
import org.junit.Assert;
import org.junit.Test;
public class SelectBooleanIterableTest
{
private final SelectBooleanIterable iterable = new SelectBooleanIterable(BooleanArrayList.newListWith(true, false, false, true), BooleanPredicates.isTrue());
@Test
public void booleanIterator()
{
StringBuilder concat = new StringBuilder();
for (BooleanIterator iterator = this.iterable.booleanIterator(); iterator.hasNext(); )
{
concat.append(iterator.next());
}
Assert.assertEquals("truetrue", concat.toString());
}
@Test
public void forEach()
{
String[] concat = new String[1];
concat[0] = "";
this.iterable.forEach(each -> concat[0] += each);
Assert.assertEquals("truetrue", concat[0]);
}
@Test
public void injectInto()
{
MutableInteger result = this.iterable.injectInto(new MutableInteger(0), (object, value) -> object.add(value ? 1 : 0));
Assert.assertEquals(new MutableInteger(2), result);
}
@Test
public void size()
{
Assert.assertEquals(2L, this.iterable.size());
}
@Test
public void empty()
{
Assert.assertTrue(this.iterable.notEmpty());
Assert.assertFalse(this.iterable.isEmpty());
}
@Test
public void count()
{
Assert.assertEquals(2L, this.iterable.count(BooleanPredicates.isTrue()));
Assert.assertEquals(0L, this.iterable.count(BooleanPredicates.isFalse()));
}
@Test
public void anySatisfy()
{
Assert.assertTrue(this.iterable.anySatisfy(BooleanPredicates.isTrue()));
Assert.assertFalse(this.iterable.anySatisfy(BooleanPredicates.isFalse()));
}
@Test
public void allSatisfy()
{
Assert.assertTrue(this.iterable.allSatisfy(BooleanPredicates.isTrue()));
Assert.assertFalse(this.iterable.allSatisfy(BooleanPredicates.isFalse()));
}
@Test
public void select()
{
Assert.assertEquals(0L, this.iterable.select(BooleanPredicates.isFalse()).size());
Assert.assertEquals(2L, this.iterable.select(BooleanPredicates.equal(true)).size());
}
@Test
public void reject()
{
Assert.assertEquals(2L, this.iterable.reject(BooleanPredicates.isFalse()).size());
Assert.assertEquals(0L, this.iterable.reject(BooleanPredicates.equal(true)).size());
}
@Test
public void detectIfNone()
{
Assert.assertTrue(this.iterable.detectIfNone(BooleanPredicates.isTrue(), false));
Assert.assertFalse(this.iterable.detectIfNone(BooleanPredicates.isFalse(), false));
}
@Test
public void collect()
{
Assert.assertEquals(2L, this.iterable.collect(String::valueOf).size());
}
@Test
public void toArray()
{
Assert.assertEquals(2L, this.iterable.toArray().length);
Assert.assertTrue(this.iterable.toArray()[0]);
Assert.assertTrue(this.iterable.toArray()[1]);
}
@Test
public void contains()
{
Assert.assertTrue(this.iterable.contains(true));
Assert.assertFalse(this.iterable.contains(false));
}
@Test
public void containsAll()
{
Assert.assertTrue(this.iterable.containsAll(true, true));
Assert.assertFalse(this.iterable.containsAll(false, true));
Assert.assertFalse(this.iterable.containsAll(false, false));
}
}
| gabby2212/gs-collections | unit-tests/src/test/java/com/gs/collections/impl/lazy/primitive/SelectBooleanIterableTest.java | Java | apache-2.0 | 4,320 |
/*
* Copyright 2013 Goldman Sachs.
*
* 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.gs.collections.impl.map.immutable.primitive;
import com.gs.collections.impl.test.Verify;
import org.junit.Test;
public class ImmutableCharIntSingletonMapSerializationTest
{
@Test
public void serializedForm()
{
Verify.assertSerializedForm(
1L,
"rO0ABXNyAExjb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5tYXAuaW1tdXRhYmxlLnByaW1pdGl2ZS5J\n"
+ "bW11dGFibGVDaGFySW50U2luZ2xldG9uTWFwAAAAAAAAAAECAAJDAARrZXkxSQAGdmFsdWUxeHAA\n"
+ "AQAAAAE=",
new ImmutableCharIntSingletonMap((char) 1, 1));
}
}
| gabby2212/gs-collections | serialization-tests/src/test/java/com/gs/collections/impl/map/immutable/primitive/ImmutableCharIntSingletonMapSerializationTest.java | Java | apache-2.0 | 1,206 |
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.bpmn.client.forms.fields.assigneeEditor.widget;
import java.util.List;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwtmockito.GwtMockitoTestRunner;
import org.assertj.core.api.Assertions;
import org.jboss.errai.ioc.client.api.ManagedInstance;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.bpmn.client.forms.fields.assigneeEditor.AssigneeLiveSearchService;
import org.kie.workbench.common.stunner.bpmn.client.forms.fields.i18n.StunnerBPMNConstants;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.stubbing.Answer;
import org.uberfire.ext.widgets.common.client.dropdown.LiveSearchDropDown;
import org.uberfire.mocks.EventSourceMock;
import org.uberfire.mvp.ParameterizedCommand;
import org.uberfire.workbench.events.NotificationEvent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.kie.workbench.common.stunner.bpmn.forms.model.AssigneeType.USER;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(GwtMockitoTestRunner.class)
public class AssigneeEditorWidgetTest {
private static final int MAX = 5;
@Mock
private AssigneeEditorWidgetView view;
@Mock
private ManagedInstance<AssigneeListItem> listItems;
@Mock
private TranslationService translationService;
@Mock
private EventSourceMock<NotificationEvent> notification;
private AssigneeEditorWidget widget;
@Captor
private ArgumentCaptor<ParameterizedCommand<Throwable>> commandCaptor;
@Captor
private ArgumentCaptor<NotificationEvent> eventCaptor;
@Before
public void init() {
when(view.asWidget()).thenReturn(mock(Widget.class));
when(listItems.get()).then((Answer<AssigneeListItem>) invocationOnMock -> new AssigneeListItem(mock(LiveSearchDropDown.class), mock(AssigneeLiveSearchService.class)));
widget = new AssigneeEditorWidget(view, listItems, translationService, notification);
}
@Test
public void testSetEmptyValue() {
widget.setValue("");
verify(view).clearList();
verify(listItems).destroyAll();
verify(listItems, never()).get();
verify(view, never()).add(any());
}
@Test
public void testSetValue() {
String value = "a,b,c";
widget.setValue(value);
verify(view).clearList();
verify(listItems).destroyAll();
verify(listItems, times(3)).get();
verify(view, times(3)).add(any());
widget.doSave();
String newValue = widget.getValue();
assertEquals(value, newValue);
}
@Test
public void testAddAssigneesWithoutMax() {
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
verify(listItems, times(7)).get();
verify(view, times(7)).add(any());
}
@Test
public void testAddAssigneesWithMaxAndRemove() {
widget.init(USER, MAX);
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
widget.addAssignee();
verify(listItems, times(5)).get();
ArgumentCaptor<AssigneeListItem> itemsArgumentCaptor = ArgumentCaptor.forClass(AssigneeListItem.class);
verify(view, times(5)).add(itemsArgumentCaptor.capture());
verify(view).disableAddButton();
List<AssigneeListItem> items = itemsArgumentCaptor.getAllValues();
Assertions.assertThat(items)
.isNotNull()
.isNotEmpty()
.hasSize(5);
items.forEach(widget::removeAssignee);
verify(listItems, times(5)).destroy(any());
verify(view, times(5)).enableAddButton();
}
@Test
public void testCheckDuplicateName() {
widget.addAssignee();
verify(listItems, times(1)).get();
ArgumentCaptor<AssigneeListItem> itemsArgumentCaptor = ArgumentCaptor.forClass(AssigneeListItem.class);
verify(view, times(1)).add(itemsArgumentCaptor.capture());
List<AssigneeListItem> items = itemsArgumentCaptor.getAllValues();
Assertions.assertThat(items)
.isNotNull()
.isNotEmpty()
.hasSize(1);
String name = "John Stark";
items.get(0).getAssignee().setName(name);
assertTrue(widget.isDuplicateName(name));
}
@Test
public void testGeneral() {
verify(view).init(widget);
widget.asWidget();
verify(view).asWidget();
widget.getNameHeader();
verify(translationService).getTranslation(StunnerBPMNConstants.ASSIGNEE_LABEL);
widget.getAddLabel();
verify(translationService).getTranslation(StunnerBPMNConstants.ASSIGNEE_NEW);
widget.destroy();
verify(listItems).destroyAll();
}
@Test
public void setReadOnlyTrue() {
widget.setReadOnly(true);
verify(view,
times(1)).setReadOnly(true);
}
@Test
public void setReadOnlyFalse() {
widget.setReadOnly(false);
verify(view,
times(1)).setReadOnly(false);
}
public void testItemWithError() {
AssigneeListItem listItem = mock(AssigneeListItem.class);
when(listItems.get()).thenReturn(listItem);
String itemError = "ItemError";
String translatedMessage = "TranslatedMessage";
when(translationService.format(StunnerBPMNConstants.ASSIGNEE_SEARCH_ERROR, itemError)).thenReturn(translatedMessage);
widget.addAssignee();
verify(listItem).init(any(), any(), any(), any(), commandCaptor.getValue());
Exception itemException = new Exception(itemError);
commandCaptor.getValue().execute(itemException);
verify(notification).fire(eventCaptor.capture());
assertEquals(NotificationEvent.NotificationType.ERROR, eventCaptor.getValue().getType());
assertEquals(translatedMessage, eventCaptor.getValue().getNotification());
}
}
| mbiarnes/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-client/src/test/java/org/kie/workbench/common/stunner/bpmn/client/forms/fields/assigneeEditor/widget/AssigneeEditorWidgetTest.java | Java | apache-2.0 | 7,186 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cn.itcast.util;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
/**
* 工具类
* @author fqy
*/
public class UiUtil {
private UiUtil(){}
/**
* 修改窗体图标
* @param jf
*/
public static void setFrameIcon(JFrame jf,String imagePath){
//获取工具类
Toolkit took = Toolkit.getDefaultToolkit();
//根据路径获取图片
Image image = took.getImage(imagePath);
//设置图标
jf.setIconImage(image);
}
/**
* 设置窗体居中
* @param jf
*/
public static void setFrameCenter(JFrame jf){
/*
思路:
获取屏幕的宽和高
获取窗体的宽和高
*/
//获取工具类
Toolkit took = Toolkit.getDefaultToolkit();
//获取屏幕的宽和高
Dimension screen = took.getScreenSize();
double screenWidth = screen.getWidth();
double screenHeight = screen.getHeight();
//获取窗体的宽和高
int jfWidth = jf.getWidth();
int jfHeight = jf.getHeight();
//设置坐标
int width = (int)(screenWidth-jfWidth)/2;
int height = (int)(screenHeight-jfHeight)/2;
jf.setLocation(width,height);
}
}
| planecyc/Java | day25/code/登录注册/src/cn/itcast/util/UiUtil.java | Java | artistic-2.0 | 1,557 |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.xensource.xenapi.samples;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import com.xensource.xenapi.*;
/**
* Tests using an https (SSL) connection to a XenServer.
*
* Before running, perform these steps:
*
* 1. Copy to your client machine /etc/xensource/xapi-ssl.pem from the XenServer you want to connect to.
* 2. Run 'openssl x509 -inform PEM -outform DER -in xapi-ssl.pem -out xapi-ssl.jks'
* This converts the certificate into a form that Java's keytool can understand.
* 3. Run keytool (found in Java's bin directory) as follows:
* 'keytool -importcert -file xapi-ssl.jks -alias <hostname>'
* You can optionally pass the -keystore argument if you want to specify the location of your keystore.
* 4. To tell the JVM the location and password of your keystore, run it with the additional parameters
* (Sun's keytool seems to insist on using private key and keystore passwords):
* -Djavax.net.ssl.trustStore="<path to keystore>" -Djavax.net.ssl.trustStorePassword=<password>
* For extra debug info, try:
* -Djavax.net.debug=ssl
*/
public class Https extends TestBase
{
public String getTestName() {
return "Https";
}
protected void TestCore() throws Exception {
}
@Override
public void RunTest(FileLogger logger, TargetServer server) throws Exception
{
this.logger = logger;
Connection conn = null;
try
{
// Create our own HostnameVerifier
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return session.getPeerHost().equals(hostname);
}
};
// Sets the default HostnameVerifier used on all Https connections created after this point
HttpsURLConnection.setDefaultHostnameVerifier(hv);
URL url = new URL("https://" + server.Hostname);
conn = new Connection(url);
// Log in
Session.loginWithPassword(conn, server.Username, server.Password, "1.3");
// Print a record
for (Host host : Host.getAllRecords(conn).keySet())
{
log(host.toString());
break;
}
}
finally
{
if (conn != null)
Session.logout(conn);
}
}
}
| xapi-project/xen-api-sdk | java/autogen/xen-api-samples/src/main/java/com/xensource/xenapi/samples/Https.java | Java | bsd-2-clause | 3,944 |
package org.hisp.dhis.i18n.ui.resourcebundle;
/*
* Copyright (c) 2004-2017, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.hisp.dhis.common.comparator.LocaleNameComparator;
import org.hisp.dhis.i18n.locale.LocaleManager;
import org.hisp.dhis.commons.util.PathUtils;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Torgeir Lorange Ostby
* @author Pham Thi Thuy
* @author Nguyen Dang Quang
*/
public class DefaultResourceBundleManager
implements ResourceBundleManager
{
private static final String EXT_RESOURCE_BUNDLE = ".properties";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
private String globalResourceBundleName;
public void setGlobalResourceBundleName( String globalResourceBundleName )
{
this.globalResourceBundleName = globalResourceBundleName;
}
private String specificResourceBundleName;
public void setSpecificResourceBundleName( String specificResourceBundleName )
{
this.specificResourceBundleName = specificResourceBundleName;
}
// -------------------------------------------------------------------------
// ResourceBundleManager implementation
// -------------------------------------------------------------------------
@Override
public ResourceBundle getSpecificResourceBundle( Class<?> clazz, Locale locale )
{
return getSpecificResourceBundle( clazz.getName(), locale );
}
@Override
public ResourceBundle getSpecificResourceBundle( String clazzName, Locale locale )
{
String path = PathUtils.getClassPath( clazzName );
for ( String dir = path; dir != null; dir = PathUtils.getParent( dir ) )
{
String baseName = PathUtils.addChild( dir, specificResourceBundleName );
try
{
return ResourceBundle.getBundle( baseName, locale );
}
catch ( MissingResourceException ignored )
{
}
}
return null;
}
@Override
public ResourceBundle getGlobalResourceBundle( Locale locale )
throws ResourceBundleManagerException
{
try
{
return ResourceBundle.getBundle( globalResourceBundleName, locale );
}
catch ( MissingResourceException e )
{
throw new ResourceBundleManagerException( "Failed to get global resource bundle" );
}
}
@Override
public List<Locale> getAvailableLocales()
throws ResourceBundleManagerException
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource( globalResourceBundleName + EXT_RESOURCE_BUNDLE );
if ( url == null )
{
throw new ResourceBundleManagerException( "Failed to find global resource bundle" );
}
List<Locale> locales = null;
if ( url.toExternalForm().startsWith( "jar:" ) )
{
locales = new ArrayList<>( getAvailableLocalesFromJar( url ) );
}
else
{
String dirPath = new File( url.getFile() ).getParent();
locales = new ArrayList<>( getAvailableLocalesFromDir( dirPath ) );
}
Collections.sort( locales, LocaleNameComparator.INSTANCE );
return locales;
}
private Collection<Locale> getAvailableLocalesFromJar( URL url )
throws ResourceBundleManagerException
{
JarFile jar = null;
Set<Locale> availableLocales = new HashSet<>();
try
{
JarURLConnection connection = (JarURLConnection) url.openConnection();
jar = connection.getJarFile();
Enumeration<JarEntry> e = jar.entries();
while ( e.hasMoreElements() )
{
JarEntry entry = e.nextElement();
String name = entry.getName();
if ( name.startsWith( globalResourceBundleName ) && name.endsWith( EXT_RESOURCE_BUNDLE ) )
{
availableLocales.add( getLocaleFromName( name ) );
}
}
}
catch ( IOException e )
{
throw new ResourceBundleManagerException( "Failed to get jar file: " + url, e );
}
return availableLocales;
}
private Collection<Locale> getAvailableLocalesFromDir( String dirPath )
{
dirPath = convertURLToFilePath( dirPath );
File dir = new File( dirPath );
Set<Locale> availableLocales = new HashSet<>();
File[] files = dir.listFiles( new FilenameFilter()
{
@Override
public boolean accept( File dir, String name )
{
return name.startsWith( globalResourceBundleName ) && name.endsWith( EXT_RESOURCE_BUNDLE );
}
} );
if ( files != null )
{
for ( File file : files )
{
availableLocales.add( getLocaleFromName( file.getName() ) );
}
}
return availableLocales;
}
private Locale getLocaleFromName( String name )
{
Pattern pattern = Pattern.compile( "^" + globalResourceBundleName
+ "(?:_([a-z]{2,3})(?:_([A-Z]{2})(?:_(.+))?)?)?" + EXT_RESOURCE_BUNDLE + "$" );
Matcher matcher = pattern.matcher( name );
if ( matcher.matches() )
{
if ( matcher.group( 1 ) != null )
{
if ( matcher.group( 2 ) != null )
{
if ( matcher.group( 3 ) != null )
{
return new Locale( matcher.group( 1 ), matcher.group( 2 ), matcher.group( 3 ) );
}
return new Locale( matcher.group( 1 ), matcher.group( 2 ) );
}
return new Locale( matcher.group( 1 ) );
}
}
return LocaleManager.DEFAULT_LOCALE;
}
// -------------------------------------------------------------------------
// Support method
// -------------------------------------------------------------------------
private String convertURLToFilePath( String url )
{
try
{
url = URLDecoder.decode( url, "iso-8859-1" );
}
catch ( Exception ex )
{
ex.printStackTrace();
}
return url;
}
}
| vmluan/dhis2-core | dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/i18n/ui/resourcebundle/DefaultResourceBundleManager.java | Java | bsd-3-clause | 8,881 |
package org.knowm.xchange.cryptofacilities.dto.marketdata;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import org.knowm.xchange.cryptofacilities.Util;
import org.knowm.xchange.cryptofacilities.dto.CryptoFacilitiesResult;
/** @author Panchen */
public class CryptoFacilitiesFill extends CryptoFacilitiesResult {
private final Date fillTime;
private final String order_id;
private final String fill_id;
private final String cliOrdId;
private final String symbol;
private final String side;
private final BigDecimal size;
private final BigDecimal price;
private final String fillType;
public CryptoFacilitiesFill(
@JsonProperty("result") String result,
@JsonProperty("error") String error,
@JsonProperty("fillTime") String strfillTime,
@JsonProperty("order_id") String order_id,
@JsonProperty("fill_id") String fill_id,
@JsonProperty("cliOrdId") String cliOrdId,
@JsonProperty("symbol") String symbol,
@JsonProperty("side") String side,
@JsonProperty("size") BigDecimal size,
@JsonProperty("price") BigDecimal price,
@JsonProperty("fillType") String fillType)
throws ParseException {
super(result, error);
this.fillTime = Util.parseDate(strfillTime);
this.order_id = order_id;
this.fill_id = fill_id;
this.cliOrdId = cliOrdId;
this.symbol = symbol;
this.side = side;
this.size = size;
this.price = price;
this.fillType = fillType;
}
public String getSymbol() {
return symbol;
}
public Date getFillTime() {
return fillTime;
}
public String getOrderId() {
return order_id;
}
public String getFillId() {
return fill_id;
}
public String getClientOrderId() {
return cliOrdId;
}
public String getSide() {
return side;
}
public BigDecimal getSize() {
return size;
}
public BigDecimal getPrice() {
return price;
}
public String getFillType() {
return fillType;
}
@Override
public String toString() {
return "CryptoFacilitiesFill [order_id="
+ order_id
+ ", fill_id="
+ fill_id
+ ", cliOrdId="
+ cliOrdId
+ ", fillTime="
+ fillTime
+ ", symbol="
+ symbol
+ ", side="
+ side
+ ", size="
+ size
+ ", price="
+ price
+ ", fillType="
+ fillType
+ " ]";
}
}
| timmolter/XChange | xchange-cryptofacilities/src/main/java/org/knowm/xchange/cryptofacilities/dto/marketdata/CryptoFacilitiesFill.java | Java | mit | 2,512 |
package aima.gui.framework;
import java.awt.Color;
import aima.core.agent.Action;
import aima.core.agent.Agent;
import aima.core.agent.Environment;
import aima.core.agent.EnvironmentState;
import aima.core.util.datastructure.Point2D;
/**
* Simple graphical environment view without content but with some useful
* transformation features. The transformation features allow to scale
* and translate 2D world coordinates into view coordinates. When creating
* subclasses, it should normally be sufficient to override the method
* {@link #paintComponent(java.awt.Graphics)}.
*
* @author Ruediger Lunde
*/
public class EmptyEnvironmentView extends AgentAppEnvironmentView {
private static final long serialVersionUID = 1L;
private int borderTop = 10;
private int borderLeft = 10;
private int borderBottom = 10;
private int borderRight = 10;
private double offsetX;
private double offsetY;
private double scale;
/**
* Specifies the number of pixels left blank on each side of the agent view
* panel.
*/
public void setBorder(int top, int left, int bottom, int right) {
borderTop = top;
borderLeft = left;
borderBottom = bottom;
borderRight = right;
}
/**
* Specifies a bounding box in world coordinates. The resulting
* transformation is able to display everything within this bounding box
* without scrolling.
*/
public void adjustTransformation(double minXW, double minYW, double maxXW,
double maxYW) {
// adjust coordinates relative to the left upper corner of the graph
// area
double scaleX = 1f;
double scaleY = 1f;
if (maxXW > minXW)
scaleX = (getWidth() - borderLeft - borderRight) / (maxXW - minXW);
if (maxYW > minYW)
scaleY = (getHeight() - borderTop - borderBottom) / (maxYW - minYW);
offsetX = -minXW;
offsetY = -minYW;
scale = Math.min(scaleX, scaleY);
}
/** Returns the x_view of a given point in world coordinates. */
protected int x(Point2D xyW) {
return x(xyW.getX());
}
/** Returns the y_view of a given point in world coordinates. */
protected int y(Point2D xyW) {
return y(xyW.getY());
}
/** Returns the x_view of a given x-value in world coordinates. */
protected int x(double xW) {
return (int) Math.round(scale * (xW + offsetX) + borderLeft);
}
/** Returns the y_view of a given y-value in world coordinates. */
protected int y(double yW) {
return (int) Math.round(scale * (yW + offsetY) + borderTop);
}
/** Transforms a given world length into view length. */
protected int scale(int length) {
return (int) Math.round(scale * length);
}
/** Stores the model and initiates painting. */
@Override
public void setEnvironment(Environment env) {
super.setEnvironment(env);
repaint();
}
@Override
public void agentActed(Agent agent, Action action,
EnvironmentState resultingState) {
repaint();
}
@Override
public void agentAdded(Agent agent, EnvironmentState resultingState) {
repaint();
}
/**
* Shows a graphical representation of the agent in its environment.
* Override this dummy implementation to get a useful view of the agent!
*/
@Override
public void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
g2.setBackground(Color.white);
g2.clearRect(0, 0, getWidth(), getHeight());
}
} | futuristixa/aima-java | aima-gui/src/main/java/aima/gui/framework/EmptyEnvironmentView.java | Java | mit | 3,408 |
package us.kbase.jkidl;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class ParseNode {
private String name;
private Map<String, String> props = new LinkedHashMap<String, String>();
private List<ParseNode> children = new ArrayList<ParseNode>();
public ParseNode(String name) {
this.name = name;
}
public void addChild(ParseNode child) {
children.add(child);
}
public void setProperty(String name, String value) {
props.put(name, value);
}
public String getName() {
return name;
}
public Map<String, String> getProps() {
return props;
}
public List<ParseNode> getChildren() {
return children;
}
public void printTreeInfo() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
try {
mapper.writeValue(System.out, this);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
| kbase/java_type_generator | src/us/kbase/jkidl/ParseNode.java | Java | mit | 1,075 |
package sun.util.resources;
import java.util.ListResourceBundle;
public final class CalendarData_el_CY extends LocaleNamesBundle {
protected final Object[][] getContents() {
return new Object[][] {
{ "minimalDaysInFirstWeek", "1" },
};
}
}
| Distrotech/icedtea7-2.3 | generated/sun/util/resources/CalendarData_el_CY.java | Java | gpl-2.0 | 278 |
/*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @key stress gc
*
* @summary converted from VM Testbase gc/gctests/WeakReference/weak002.
* VM Testbase keywords: [gc, stress, stressopt, nonconcurrent]
* VM Testbase readme:
* DESCRIPTION
* The test checks that Garbage Collector correctly works with
* WeakReferences. It also checks that no unexpected exceptions and errors
* are thrown or the JVM is not crashed.
* The test starts a number of threads. Each thread run tests for some time
* or serveral iterations. See javadoc StressOptions for configuration.
* First of all each test defines what type to check (there are 10 types
* totally). As soon as the type is defined, a WeakReference is created that
* refers to an array of tested type and is registered with in a queue. A
* WeakReference for NonbranchyTree class does not refer to an array, but to
* instances of the class.
* After that a thread performs next checks for the reference:
* 1. The reference is in queue after GC is provoked with
* Algorithms.eatMemory() method (a single thread eats the memory).
* 2. queue.remove() returns reference from the queue.
* 3. queue.poll() returns null.
* 4. reference.clear() does not throw any exception.
* The test extends ThreadedGCTest and implements GarbageProducerAware and
* MemoryStrategyAware interfaces. The corresponding javadoc documentation
* for additional test configuration.
*
* @library /vmTestbase
* /test/lib
* @run driver jdk.test.lib.FileInstaller . .
* @run main/othervm gc.gctests.WeakReference.weak001.weak001 -ms high
*/
| md-5/jdk10 | test/hotspot/jtreg/vmTestbase/gc/gctests/WeakReference/weak002/TestDescription.java | Java | gpl-2.0 | 2,712 |
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.reflect;
import sun.reflect.CallerSensitive;
import sun.reflect.MethodAccessor;
import sun.reflect.Reflection;
import sun.reflect.generics.repository.MethodRepository;
import sun.reflect.generics.factory.CoreReflectionFactory;
import sun.reflect.generics.factory.GenericsFactory;
import sun.reflect.generics.scope.MethodScope;
import sun.reflect.annotation.AnnotationType;
import sun.reflect.annotation.AnnotationParser;
import java.lang.annotation.Annotation;
import java.lang.annotation.AnnotationFormatError;
import java.nio.ByteBuffer;
import java.util.Map;
/**
* A {@code Method} provides information about, and access to, a single method
* on a class or interface. The reflected method may be a class method
* or an instance method (including an abstract method).
*
* <p>A {@code Method} permits widening conversions to occur when matching the
* actual parameters to invoke with the underlying method's formal
* parameters, but it throws an {@code IllegalArgumentException} if a
* narrowing conversion would occur.
*
* @see Member
* @see java.lang.Class
* @see java.lang.Class#getMethods()
* @see java.lang.Class#getMethod(String, Class[])
* @see java.lang.Class#getDeclaredMethods()
* @see java.lang.Class#getDeclaredMethod(String, Class[])
*
* @author Kenneth Russell
* @author Nakul Saraiya
*/
public final
class Method extends AccessibleObject implements GenericDeclaration,
Member {
private Class<?> clazz;
private int slot;
// This is guaranteed to be interned by the VM in the 1.4
// reflection implementation
private String name;
private Class<?> returnType;
private Class<?>[] parameterTypes;
private Class<?>[] exceptionTypes;
private int modifiers;
// Generics and annotations support
private transient String signature;
// generic info repository; lazily initialized
private transient MethodRepository genericInfo;
private byte[] annotations;
private byte[] parameterAnnotations;
private byte[] annotationDefault;
private volatile MethodAccessor methodAccessor;
// For sharing of MethodAccessors. This branching structure is
// currently only two levels deep (i.e., one root Method and
// potentially many Method objects pointing to it.)
private Method root;
// Generics infrastructure
private String getGenericSignature() {return signature;}
// Accessor for factory
private GenericsFactory getFactory() {
// create scope and factory
return CoreReflectionFactory.make(this, MethodScope.make(this));
}
// Accessor for generic info repository
private MethodRepository getGenericInfo() {
// lazily initialize repository if necessary
if (genericInfo == null) {
// create and cache generic info repository
genericInfo = MethodRepository.make(getGenericSignature(),
getFactory());
}
return genericInfo; //return cached repository
}
/**
* Package-private constructor used by ReflectAccess to enable
* instantiation of these objects in Java code from the java.lang
* package via sun.reflect.LangReflectAccess.
*/
Method(Class<?> declaringClass,
String name,
Class<?>[] parameterTypes,
Class<?> returnType,
Class<?>[] checkedExceptions,
int modifiers,
int slot,
String signature,
byte[] annotations,
byte[] parameterAnnotations,
byte[] annotationDefault)
{
this.clazz = declaringClass;
this.name = name;
this.parameterTypes = parameterTypes;
this.returnType = returnType;
this.exceptionTypes = checkedExceptions;
this.modifiers = modifiers;
this.slot = slot;
this.signature = signature;
this.annotations = annotations;
this.parameterAnnotations = parameterAnnotations;
this.annotationDefault = annotationDefault;
}
/**
* Package-private routine (exposed to java.lang.Class via
* ReflectAccess) which returns a copy of this Method. The copy's
* "root" field points to this Method.
*/
Method copy() {
// This routine enables sharing of MethodAccessor objects
// among Method objects which refer to the same underlying
// method in the VM. (All of this contortion is only necessary
// because of the "accessibility" bit in AccessibleObject,
// which implicitly requires that new java.lang.reflect
// objects be fabricated for each reflective call on Class
// objects.)
Method res = new Method(clazz, name, parameterTypes, returnType,
exceptionTypes, modifiers, slot, signature,
annotations, parameterAnnotations, annotationDefault);
res.root = this;
// Might as well eagerly propagate this if already present
res.methodAccessor = methodAccessor;
return res;
}
/**
* Returns the {@code Class} object representing the class or interface
* that declares the method represented by this {@code Method} object.
*/
public Class<?> getDeclaringClass() {
return clazz;
}
/**
* Returns the name of the method represented by this {@code Method}
* object, as a {@code String}.
*/
public String getName() {
return name;
}
/**
* Returns the Java language modifiers for the method represented
* by this {@code Method} object, as an integer. The {@code Modifier} class should
* be used to decode the modifiers.
*
* @see Modifier
*/
public int getModifiers() {
return modifiers;
}
/**
* Returns an array of {@code TypeVariable} objects that represent the
* type variables declared by the generic declaration represented by this
* {@code GenericDeclaration} object, in declaration order. Returns an
* array of length 0 if the underlying generic declaration declares no type
* variables.
*
* @return an array of {@code TypeVariable} objects that represent
* the type variables declared by this generic declaration
* @throws GenericSignatureFormatError if the generic
* signature of this generic declaration does not conform to
* the format specified in
* <cite>The Java™ Virtual Machine Specification</cite>
* @since 1.5
*/
public TypeVariable<Method>[] getTypeParameters() {
if (getGenericSignature() != null)
return (TypeVariable<Method>[])getGenericInfo().getTypeParameters();
else
return (TypeVariable<Method>[])new TypeVariable[0];
}
/**
* Returns a {@code Class} object that represents the formal return type
* of the method represented by this {@code Method} object.
*
* @return the return type for the method this object represents
*/
public Class<?> getReturnType() {
return returnType;
}
/**
* Returns a {@code Type} object that represents the formal return
* type of the method represented by this {@code Method} object.
*
* <p>If the return type is a parameterized type,
* the {@code Type} object returned must accurately reflect
* the actual type parameters used in the source code.
*
* <p>If the return type is a type variable or a parameterized type, it
* is created. Otherwise, it is resolved.
*
* @return a {@code Type} object that represents the formal return
* type of the underlying method
* @throws GenericSignatureFormatError
* if the generic method signature does not conform to the format
* specified in
* <cite>The Java™ Virtual Machine Specification</cite>
* @throws TypeNotPresentException if the underlying method's
* return type refers to a non-existent type declaration
* @throws MalformedParameterizedTypeException if the
* underlying method's return typed refers to a parameterized
* type that cannot be instantiated for any reason
* @since 1.5
*/
public Type getGenericReturnType() {
if (getGenericSignature() != null) {
return getGenericInfo().getReturnType();
} else { return getReturnType();}
}
/**
* Returns an array of {@code Class} objects that represent the formal
* parameter types, in declaration order, of the method
* represented by this {@code Method} object. Returns an array of length
* 0 if the underlying method takes no parameters.
*
* @return the parameter types for the method this object
* represents
*/
public Class<?>[] getParameterTypes() {
return (Class<?>[]) parameterTypes.clone();
}
/**
* Returns an array of {@code Type} objects that represent the formal
* parameter types, in declaration order, of the method represented by
* this {@code Method} object. Returns an array of length 0 if the
* underlying method takes no parameters.
*
* <p>If a formal parameter type is a parameterized type,
* the {@code Type} object returned for it must accurately reflect
* the actual type parameters used in the source code.
*
* <p>If a formal parameter type is a type variable or a parameterized
* type, it is created. Otherwise, it is resolved.
*
* @return an array of Types that represent the formal
* parameter types of the underlying method, in declaration order
* @throws GenericSignatureFormatError
* if the generic method signature does not conform to the format
* specified in
* <cite>The Java™ Virtual Machine Specification</cite>
* @throws TypeNotPresentException if any of the parameter
* types of the underlying method refers to a non-existent type
* declaration
* @throws MalformedParameterizedTypeException if any of
* the underlying method's parameter types refer to a parameterized
* type that cannot be instantiated for any reason
* @since 1.5
*/
public Type[] getGenericParameterTypes() {
if (getGenericSignature() != null)
return getGenericInfo().getParameterTypes();
else
return getParameterTypes();
}
/**
* Returns an array of {@code Class} objects that represent
* the types of the exceptions declared to be thrown
* by the underlying method
* represented by this {@code Method} object. Returns an array of length
* 0 if the method declares no exceptions in its {@code throws} clause.
*
* @return the exception types declared as being thrown by the
* method this object represents
*/
public Class<?>[] getExceptionTypes() {
return (Class<?>[]) exceptionTypes.clone();
}
/**
* Returns an array of {@code Type} objects that represent the
* exceptions declared to be thrown by this {@code Method} object.
* Returns an array of length 0 if the underlying method declares
* no exceptions in its {@code throws} clause.
*
* <p>If an exception type is a type variable or a parameterized
* type, it is created. Otherwise, it is resolved.
*
* @return an array of Types that represent the exception types
* thrown by the underlying method
* @throws GenericSignatureFormatError
* if the generic method signature does not conform to the format
* specified in
* <cite>The Java™ Virtual Machine Specification</cite>
* @throws TypeNotPresentException if the underlying method's
* {@code throws} clause refers to a non-existent type declaration
* @throws MalformedParameterizedTypeException if
* the underlying method's {@code throws} clause refers to a
* parameterized type that cannot be instantiated for any reason
* @since 1.5
*/
public Type[] getGenericExceptionTypes() {
Type[] result;
if (getGenericSignature() != null &&
((result = getGenericInfo().getExceptionTypes()).length > 0))
return result;
else
return getExceptionTypes();
}
/**
* Compares this {@code Method} against the specified object. Returns
* true if the objects are the same. Two {@code Methods} are the same if
* they were declared by the same class and have the same name
* and formal parameter types and return type.
*/
public boolean equals(Object obj) {
if (obj != null && obj instanceof Method) {
Method other = (Method)obj;
if ((getDeclaringClass() == other.getDeclaringClass())
&& (getName() == other.getName())) {
if (!returnType.equals(other.getReturnType()))
return false;
/* Avoid unnecessary cloning */
Class<?>[] params1 = parameterTypes;
Class<?>[] params2 = other.parameterTypes;
if (params1.length == params2.length) {
for (int i = 0; i < params1.length; i++) {
if (params1[i] != params2[i])
return false;
}
return true;
}
}
}
return false;
}
/**
* Returns a hashcode for this {@code Method}. The hashcode is computed
* as the exclusive-or of the hashcodes for the underlying
* method's declaring class name and the method's name.
*/
public int hashCode() {
return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
}
/**
* Returns a string describing this {@code Method}. The string is
* formatted as the method access modifiers, if any, followed by
* the method return type, followed by a space, followed by the
* class declaring the method, followed by a period, followed by
* the method name, followed by a parenthesized, comma-separated
* list of the method's formal parameter types. If the method
* throws checked exceptions, the parameter list is followed by a
* space, followed by the word throws followed by a
* comma-separated list of the thrown exception types.
* For example:
* <pre>
* public boolean java.lang.Object.equals(java.lang.Object)
* </pre>
*
* <p>The access modifiers are placed in canonical order as
* specified by "The Java Language Specification". This is
* {@code public}, {@code protected} or {@code private} first,
* and then other modifiers in the following order:
* {@code abstract}, {@code static}, {@code final},
* {@code synchronized}, {@code native}, {@code strictfp}.
*/
public String toString() {
try {
StringBuilder sb = new StringBuilder();
int mod = getModifiers() & Modifier.methodModifiers();
if (mod != 0) {
sb.append(Modifier.toString(mod)).append(' ');
}
sb.append(Field.getTypeName(getReturnType())).append(' ');
sb.append(Field.getTypeName(getDeclaringClass())).append('.');
sb.append(getName()).append('(');
Class<?>[] params = parameterTypes; // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(Field.getTypeName(params[j]));
if (j < (params.length - 1))
sb.append(',');
}
sb.append(')');
Class<?>[] exceptions = exceptionTypes; // avoid clone
if (exceptions.length > 0) {
sb.append(" throws ");
for (int k = 0; k < exceptions.length; k++) {
sb.append(exceptions[k].getName());
if (k < (exceptions.length - 1))
sb.append(',');
}
}
return sb.toString();
} catch (Exception e) {
return "<" + e + ">";
}
}
/**
* Returns a string describing this {@code Method}, including
* type parameters. The string is formatted as the method access
* modifiers, if any, followed by an angle-bracketed
* comma-separated list of the method's type parameters, if any,
* followed by the method's generic return type, followed by a
* space, followed by the class declaring the method, followed by
* a period, followed by the method name, followed by a
* parenthesized, comma-separated list of the method's generic
* formal parameter types.
*
* If this method was declared to take a variable number of
* arguments, instead of denoting the last parameter as
* "<tt><i>Type</i>[]</tt>", it is denoted as
* "<tt><i>Type</i>...</tt>".
*
* A space is used to separate access modifiers from one another
* and from the type parameters or return type. If there are no
* type parameters, the type parameter list is elided; if the type
* parameter list is present, a space separates the list from the
* class name. If the method is declared to throw exceptions, the
* parameter list is followed by a space, followed by the word
* throws followed by a comma-separated list of the generic thrown
* exception types. If there are no type parameters, the type
* parameter list is elided.
*
* <p>The access modifiers are placed in canonical order as
* specified by "The Java Language Specification". This is
* {@code public}, {@code protected} or {@code private} first,
* and then other modifiers in the following order:
* {@code abstract}, {@code static}, {@code final},
* {@code synchronized}, {@code native}, {@code strictfp}.
*
* @return a string describing this {@code Method},
* include type parameters
*
* @since 1.5
*/
public String toGenericString() {
try {
StringBuilder sb = new StringBuilder();
int mod = getModifiers() & Modifier.methodModifiers();
if (mod != 0) {
sb.append(Modifier.toString(mod)).append(' ');
}
TypeVariable<?>[] typeparms = getTypeParameters();
if (typeparms.length > 0) {
boolean first = true;
sb.append('<');
for(TypeVariable<?> typeparm: typeparms) {
if (!first)
sb.append(',');
// Class objects can't occur here; no need to test
// and call Class.getName().
sb.append(typeparm.toString());
first = false;
}
sb.append("> ");
}
Type genRetType = getGenericReturnType();
sb.append( ((genRetType instanceof Class<?>)?
Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
.append(' ');
sb.append(Field.getTypeName(getDeclaringClass())).append('.');
sb.append(getName()).append('(');
Type[] params = getGenericParameterTypes();
for (int j = 0; j < params.length; j++) {
String param = (params[j] instanceof Class)?
Field.getTypeName((Class)params[j]):
(params[j].toString());
if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
param = param.replaceFirst("\\[\\]$", "...");
sb.append(param);
if (j < (params.length - 1))
sb.append(',');
}
sb.append(')');
Type[] exceptions = getGenericExceptionTypes();
if (exceptions.length > 0) {
sb.append(" throws ");
for (int k = 0; k < exceptions.length; k++) {
sb.append((exceptions[k] instanceof Class)?
((Class)exceptions[k]).getName():
exceptions[k].toString());
if (k < (exceptions.length - 1))
sb.append(',');
}
}
return sb.toString();
} catch (Exception e) {
return "<" + e + ">";
}
}
/**
* Invokes the underlying method represented by this {@code Method}
* object, on the specified object with the specified parameters.
* Individual parameters are automatically unwrapped to match
* primitive formal parameters, and both primitive and reference
* parameters are subject to method invocation conversions as
* necessary.
*
* <p>If the underlying method is static, then the specified {@code obj}
* argument is ignored. It may be null.
*
* <p>If the number of formal parameters required by the underlying method is
* 0, the supplied {@code args} array may be of length 0 or null.
*
* <p>If the underlying method is an instance method, it is invoked
* using dynamic method lookup as documented in The Java Language
* Specification, Second Edition, section 15.12.4.4; in particular,
* overriding based on the runtime type of the target object will occur.
*
* <p>If the underlying method is static, the class that declared
* the method is initialized if it has not already been initialized.
*
* <p>If the method completes normally, the value it returns is
* returned to the caller of invoke; if the value has a primitive
* type, it is first appropriately wrapped in an object. However,
* if the value has the type of an array of a primitive type, the
* elements of the array are <i>not</i> wrapped in objects; in
* other words, an array of primitive type is returned. If the
* underlying method return type is void, the invocation returns
* null.
*
* @param obj the object the underlying method is invoked from
* @param args the arguments used for the method call
* @return the result of dispatching the method represented by
* this object on {@code obj} with parameters
* {@code args}
*
* @exception IllegalAccessException if this {@code Method} object
* is enforcing Java language access control and the underlying
* method is inaccessible.
* @exception IllegalArgumentException if the method is an
* instance method and the specified object argument
* is not an instance of the class or interface
* declaring the underlying method (or of a subclass
* or implementor thereof); if the number of actual
* and formal parameters differ; if an unwrapping
* conversion for primitive arguments fails; or if,
* after possible unwrapping, a parameter value
* cannot be converted to the corresponding formal
* parameter type by a method invocation conversion.
* @exception InvocationTargetException if the underlying method
* throws an exception.
* @exception NullPointerException if the specified object is null
* and the method is an instance method.
* @exception ExceptionInInitializerError if the initialization
* provoked by this method fails.
*/
@CallerSensitive
public Object invoke(Object obj, Object... args)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
// Until there is hotspot @CallerSensitive support
// can't call Reflection.getCallerClass() here
// Workaround for now: add a frame getCallerClass to
// make the caller at stack depth 2
Class<?> caller = getCallerClass();
checkAccess(caller, clazz, obj, modifiers);
}
}
MethodAccessor ma = methodAccessor; // read volatile
if (ma == null) {
ma = acquireMethodAccessor();
}
return ma.invoke(obj, args);
}
/*
* This method makes the frame count to be 2 to find the caller
*/
@CallerSensitive
private Class<?> getCallerClass() {
// Reflection.getCallerClass() currently returns the frame at depth 2
// before the hotspot support is in.
return Reflection.getCallerClass();
}
/**
* Returns {@code true} if this method is a bridge
* method; returns {@code false} otherwise.
*
* @return true if and only if this method is a bridge
* method as defined by the Java Language Specification.
* @since 1.5
*/
public boolean isBridge() {
return (getModifiers() & Modifier.BRIDGE) != 0;
}
/**
* Returns {@code true} if this method was declared to take
* a variable number of arguments; returns {@code false}
* otherwise.
*
* @return {@code true} if an only if this method was declared to
* take a variable number of arguments.
* @since 1.5
*/
public boolean isVarArgs() {
return (getModifiers() & Modifier.VARARGS) != 0;
}
/**
* Returns {@code true} if this method is a synthetic
* method; returns {@code false} otherwise.
*
* @return true if and only if this method is a synthetic
* method as defined by the Java Language Specification.
* @since 1.5
*/
public boolean isSynthetic() {
return Modifier.isSynthetic(getModifiers());
}
// NOTE that there is no synchronization used here. It is correct
// (though not efficient) to generate more than one MethodAccessor
// for a given Method. However, avoiding synchronization will
// probably make the implementation more scalable.
private MethodAccessor acquireMethodAccessor() {
// First check to see if one has been created yet, and take it
// if so
MethodAccessor tmp = null;
if (root != null) tmp = root.getMethodAccessor();
if (tmp != null) {
methodAccessor = tmp;
} else {
// Otherwise fabricate one and propagate it up to the root
tmp = reflectionFactory.newMethodAccessor(this);
setMethodAccessor(tmp);
}
return tmp;
}
// Returns MethodAccessor for this Method object, not looking up
// the chain to the root
MethodAccessor getMethodAccessor() {
return methodAccessor;
}
// Sets the MethodAccessor for this Method object and
// (recursively) its root
void setMethodAccessor(MethodAccessor accessor) {
methodAccessor = accessor;
// Propagate up
if (root != null) {
root.setMethodAccessor(accessor);
}
}
/**
* @throws NullPointerException {@inheritDoc}
* @since 1.5
*/
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
if (annotationClass == null)
throw new NullPointerException();
return (T) declaredAnnotations().get(annotationClass);
}
/**
* @since 1.5
*/
public Annotation[] getDeclaredAnnotations() {
return AnnotationParser.toArray(declaredAnnotations());
}
private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
if (declaredAnnotations == null) {
declaredAnnotations = AnnotationParser.parseAnnotations(
annotations, sun.misc.SharedSecrets.getJavaLangAccess().
getConstantPool(getDeclaringClass()),
getDeclaringClass());
}
return declaredAnnotations;
}
/**
* Returns the default value for the annotation member represented by
* this {@code Method} instance. If the member is of a primitive type,
* an instance of the corresponding wrapper type is returned. Returns
* null if no default is associated with the member, or if the method
* instance does not represent a declared member of an annotation type.
*
* @return the default value for the annotation member represented
* by this {@code Method} instance.
* @throws TypeNotPresentException if the annotation is of type
* {@link Class} and no definition can be found for the
* default class value.
* @since 1.5
*/
public Object getDefaultValue() {
if (annotationDefault == null)
return null;
Class<?> memberType = AnnotationType.invocationHandlerReturnType(
getReturnType());
Object result = AnnotationParser.parseMemberValue(
memberType, ByteBuffer.wrap(annotationDefault),
sun.misc.SharedSecrets.getJavaLangAccess().
getConstantPool(getDeclaringClass()),
getDeclaringClass());
if (result instanceof sun.reflect.annotation.ExceptionProxy)
throw new AnnotationFormatError("Invalid default: " + this);
return result;
}
/**
* Returns an array of arrays that represent the annotations on the formal
* parameters, in declaration order, of the method represented by
* this {@code Method} object. (Returns an array of length zero if the
* underlying method is parameterless. If the method has one or more
* parameters, a nested array of length zero is returned for each parameter
* with no annotations.) The annotation objects contained in the returned
* arrays are serializable. The caller of this method is free to modify
* the returned arrays; it will have no effect on the arrays returned to
* other callers.
*
* @return an array of arrays that represent the annotations on the formal
* parameters, in declaration order, of the method represented by this
* Method object
* @since 1.5
*/
public Annotation[][] getParameterAnnotations() {
int numParameters = parameterTypes.length;
if (parameterAnnotations == null)
return new Annotation[numParameters][0];
Annotation[][] result = AnnotationParser.parseParameterAnnotations(
parameterAnnotations,
sun.misc.SharedSecrets.getJavaLangAccess().
getConstantPool(getDeclaringClass()),
getDeclaringClass());
if (result.length != numParameters)
throw new java.lang.annotation.AnnotationFormatError(
"Parameter annotations don't match number of parameters");
return result;
}
}
| greghaskins/openjdk-jdk7u-jdk | src/share/classes/java/lang/reflect/Method.java | Java | gpl-2.0 | 32,437 |
/*
This file is part of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Cyclos is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package nl.strohalm.cyclos.services.accounts.guarantees;
import java.math.BigDecimal;
import nl.strohalm.cyclos.entities.accounts.guarantees.GuaranteeType.FeeType;
import nl.strohalm.cyclos.utils.DataObject;
public class GuaranteeFeeVO extends DataObject {
private static final long serialVersionUID = -5216565293055600738L;
private FeeType type;
private BigDecimal fee;
public BigDecimal getFee() {
return fee;
}
public FeeType getType() {
return type;
}
public void setFee(final BigDecimal fee) {
this.fee = fee;
}
public void setType(final FeeType feeType) {
type = feeType;
}
}
| zbanga/open-cyclos | src/nl/strohalm/cyclos/services/accounts/guarantees/GuaranteeFeeVO.java | Java | gpl-2.0 | 1,512 |
/*
* 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.xnet.provider.jsse;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import javax.security.auth.x500.X500Principal;
import libcore.io.Streams;
/**
*
* Represents certificate request message
* @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.4.
* Certificate request</a>
*/
public class CertificateRequest extends Message {
/**
* Requested certificate types
*/
final byte[] certificate_types;
/**
* Certificate authorities
*/
final X500Principal[] certificate_authorities;
/**
* Requested certificate types as Strings
* ("RSA", "DSA", "DH_RSA" or "DH_DSA")
*/
private String[] types;
/**
* Encoded form of certificate authorities
*/
private byte[][] encoded_principals;
/**
* Creates outbound message
*
* @param certificate_types
* @param accepted - array of certificate authority certificates
*/
public CertificateRequest(byte[] certificate_types,
X509Certificate[] accepted) {
if (accepted == null) {
fatalAlert(AlertProtocol.INTERNAL_ERROR,
"CertificateRequest: array of certificate authority certificates is null");
}
this.certificate_types = certificate_types;
int totalPrincipalsLength = 0;
certificate_authorities = new X500Principal[accepted.length];
encoded_principals = new byte[accepted.length][];
for (int i = 0; i < accepted.length; i++) {
certificate_authorities[i] = accepted[i].getIssuerX500Principal();
encoded_principals[i] = certificate_authorities[i].getEncoded();
totalPrincipalsLength += encoded_principals[i].length + 2;
}
length = 3 + certificate_types.length + totalPrincipalsLength;
}
/**
* Creates inbound message
*
* @param in
* @param length
* @throws IOException
*/
public CertificateRequest(HandshakeIODataStream in, int length) throws IOException {
int size = in.readUint8();
certificate_types = new byte[size];
Streams.readFully(in, certificate_types);
size = in.readUint16();
int totalPrincipalsLength = 0;
int principalLength = 0;
ArrayList<X500Principal> principals = new ArrayList<X500Principal>();
while (totalPrincipalsLength < size) {
principalLength = in.readUint16(); // encoded X500Principal size
principals.add(new X500Principal(in));
totalPrincipalsLength += 2;
totalPrincipalsLength += principalLength;
}
certificate_authorities = principals.toArray(new X500Principal[principals.size()]);
this.length = 3 + certificate_types.length + totalPrincipalsLength;
if (this.length != length) {
fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect CertificateRequest");
}
}
/**
* Sends message
*
* @param out
*/
@Override
public void send(HandshakeIODataStream out) {
out.writeUint8(certificate_types.length);
for (int i = 0; i < certificate_types.length; i++) {
out.write(certificate_types[i]);
}
int authoritiesLength = 0;
for (int i = 0; i < certificate_authorities.length; i++) {
authoritiesLength += encoded_principals[i].length +2;
}
out.writeUint16(authoritiesLength);
for (int i = 0; i < certificate_authorities.length; i++) {
out.writeUint16(encoded_principals[i].length);
out.write(encoded_principals[i]);
}
}
/**
* Returns message type
*
* @return
*/
@Override
public int getType() {
return Handshake.CERTIFICATE_REQUEST;
}
/**
* Returns requested certificate types as array of strings
*/
public String[] getTypesAsString() {
if (types == null) {
types = new String[certificate_types.length];
for (int i = 0; i < types.length; i++) {
String type = CipherSuite.getClientKeyType(certificate_types[i]);
if (type == null) {
fatalAlert(AlertProtocol.DECODE_ERROR,
"DECODE ERROR: incorrect CertificateRequest");
}
types[i] = type;
}
}
return types;
}
}
| xdajog/samsung_sources_i927 | libcore/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java | Java | gpl-2.0 | 5,322 |
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.api.consumer;
import java.util.List;
import jdk.jfr.Description;
import jdk.jfr.Event;
import jdk.jfr.Label;
import jdk.jfr.Recording;
import jdk.jfr.ValueDescriptor;
import jdk.jfr.consumer.RecordedEvent;
import jdk.test.lib.Asserts;
import jdk.test.lib.jfr.Events;
/**
* @test
* @summary Verifies that the recorded value descriptors are correct
* @key jfr
* @requires vm.hasJFR
* @library /test/lib
* @run main/othervm jdk.jfr.api.consumer.TestValueDescriptorRecorded
*/
public class TestValueDescriptorRecorded {
private static class MyEvent extends Event {
@Label("myLabel")
@Description("myDescription")
int myValue;
}
public static void main(String[] args) throws Throwable {
Recording r = new Recording();
r.enable(MyEvent.class).withoutStackTrace();
r.start();
MyEvent event = new MyEvent();
event.commit();
r.stop();
List<RecordedEvent> events = Events.fromRecording(r);
Events.hasEvents(events);
RecordedEvent recordedEvent = events.get(0);
for (ValueDescriptor desc : recordedEvent.getFields()) {
if ("myValue".equals(desc.getName())) {
Asserts.assertEquals(desc.getLabel(), "myLabel");
Asserts.assertEquals(desc.getDescription(), "myDescription");
Asserts.assertEquals(desc.getTypeName(), int.class.getName());
Asserts.assertFalse(desc.isArray());
Asserts.assertNull(desc.getContentType());
}
}
}
}
| md-5/jdk10 | test/jdk/jdk/jfr/api/consumer/TestValueDescriptorRecorded.java | Java | gpl-2.0 | 2,784 |
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package hello;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
public class HelloAreaChart extends Application {
@Override public void start(Stage stage) {
stage.setTitle("Hello AreaChart");
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
final AreaChart<Number,Number> ac = new AreaChart<Number,Number>(xAxis,yAxis);
xAxis.setLabel("X Axis");
yAxis.setLabel("Y Axis");
ac.setTitle("HelloAreaChart");
// // add starting data
ObservableList<XYChart.Data> data = FXCollections.observableArrayList();
XYChart.Series series = new XYChart.Series();
series.setName("Data Series 1");
// for (int i=0; i<10; i++) series.getData().add(new XYChart.Data(Math.random()*100, Math.random()*100));
series.getData().add(new XYChart.Data(20d, 50d));
series.getData().add(new XYChart.Data(40d, 80d));
series.getData().add(new XYChart.Data(50d, 90d));
series.getData().add(new XYChart.Data(70d, 30d));
series.getData().add(new XYChart.Data(90d, 20d));
Scene scene = new Scene(ac,800,600);
ac.getData().add(series);
stage.setScene(scene);
stage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}
}
| teamfx/openjfx-9-dev-rt | apps/toys/Hello/src/main/java/hello/HelloAreaChart.java | Java | gpl-2.0 | 2,852 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2015 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb.compiler;
import java.util.Set;
import junit.framework.TestCase;
import org.apache.commons.lang3.StringUtils;
public class TestClassMatcher extends TestCase {
static String testClasses = "org.voltdb.utils.BinaryDeque\n" +
"org.voltdb.utils.BinaryDeque$BinaryDequeTruncator\n" +
"org.voltdb.utils.BuildDirectoryUtils\n" +
"org.voltdb.utils.ByteArrayUtils\n" +
"org.voltdb.utils.CLibrary\n" +
"org.voltdb.utils.CLibrary$Rlimit\n" +
"org.voltdb.utils.CSVLoader\n";
boolean strContains(String[] list, String pattern) {
for (String s : list) {
if (s.equals(pattern)) {
return true;
}
}
return false;
}
public void testSimple() {
ClassMatcher cm = new ClassMatcher();
cm.m_classList = testClasses;
cm.addPattern("org.**.B*");
Set<String> matchedClasses = cm.getMatchedClassList();
String[] out = matchedClasses.toArray(new String[matchedClasses.size()]);
assertEquals(3, out.length);
assertTrue(strContains(out, "org.voltdb.utils.BinaryDeque"));
assertTrue(strContains(out, "org.voltdb.utils.BuildDirectoryUtils"));
assertTrue(strContains(out, "org.voltdb.utils.ByteArrayUtils"));
cm = new ClassMatcher();
cm.m_classList = testClasses;
cm.addPattern("**BinaryDeque");
matchedClasses = cm.getMatchedClassList();
out = matchedClasses.toArray(new String[matchedClasses.size()]);
assertEquals(1, out.length);
assertTrue(strContains(out, "org.voltdb.utils.BinaryDeque"));
cm = new ClassMatcher();
cm.m_classList = testClasses;
cm.addPattern("*.voltdb.*.CLibrary");
matchedClasses = cm.getMatchedClassList();
out = matchedClasses.toArray(new String[matchedClasses.size()]);
assertEquals(1, out.length);
assertTrue(strContains(out, "org.voltdb.utils.CLibrary"));
cm = new ClassMatcher();
cm.m_classList = testClasses;
cm.addPattern("*.voltdb.*CLibrary");
matchedClasses = cm.getMatchedClassList();
out = matchedClasses.toArray(new String[matchedClasses.size()]);
assertEquals(0, out.length);
}
public void testEng7223() {
String[] classes = {
"voter.ContestantWinningStates",
"voter.ContestantWinningStates$OrderByVotesDesc",
"voter.ContestantWinningStates$Result"
};
// Should match the outer class, not the nested ones.
ClassMatcher cm = new ClassMatcher();
cm.m_classList = StringUtils.join(classes, '\n');
cm.addPattern("**.*Cont*");
Set<String> matchedClasses = cm.getMatchedClassList();
String[] out = matchedClasses.toArray(new String[matchedClasses.size()]);
assertEquals(1, out.length);
assertTrue(strContains(out, "voter.ContestantWinningStates"));
// Make sure '.' is literal, and not treated as a regex "match any character".
cm = new ClassMatcher();
cm.m_classList = StringUtils.join(classes, '\n');
cm.addPattern("**.*Cont.*");
matchedClasses = cm.getMatchedClassList();
out = matchedClasses.toArray(new String[matchedClasses.size()]);
assertEquals(0, out.length);
}
}
| wolffcm/voltdb | tests/frontend/org/voltdb/compiler/TestClassMatcher.java | Java | agpl-3.0 | 4,623 |
// This file is part of OpenTSDB.
// Copyright (C) 2015 The OpenTSDB Authors.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version. This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.query.expression;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;
import net.opentsdb.core.SeekableView;
import net.opentsdb.core.SeekableViewsForTest;
import net.opentsdb.core.TSQuery;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.sun.java_cup.internal.runtime.Scanner;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "javax.xml.*",
"ch.qos.*", "org.slf4j.*",
"com.sum.*", "org.xml.*"})
@PrepareForTest({ TSQuery.class, Scanner.class })
public class TestSumSeries extends BaseTimeSyncedIteratorTest {
private static long START_TIME = 1356998400000L;
private static int INTERVAL = 60000;
private static int NUM_POINTS = 5;
private TSQuery data_query;
private SeekableView view;
private DataPoints dps;
private DataPoints[] group_bys;
private List<DataPoints[]> query_results;
private List<String> params;
private SumSeries func;
@Before
public void beforeLocal() throws Exception {
view = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, true, 1, 1);
data_query = mock(TSQuery.class);
when(data_query.startTime()).thenReturn(START_TIME);
when(data_query.endTime()).thenReturn(START_TIME + (INTERVAL * NUM_POINTS));
dps = PowerMockito.mock(DataPoints.class);
when(dps.iterator()).thenReturn(view);
when(dps.metricName()).thenReturn(METRIC_STRING);
when(dps.metricUID()).thenReturn(new byte[] {0,0,1});
group_bys = new DataPoints[] { dps };
query_results = new ArrayList<DataPoints[]>(1);
query_results.add(group_bys);
params = new ArrayList<String>(1);
func = new SumSeries(tsdb);
}
@Test
public void sumOneSeriesEach() throws Exception {
SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, true, 10, 1);
DataPoints dps2 = PowerMockito.mock(DataPoints.class);
when(dps2.iterator()).thenReturn(view2);
when(dps2.metricName()).thenReturn("sys.mem");
when(dps2.metricUID()).thenReturn(new byte[] {0,0,2});
group_bys = new DataPoints[] { dps2 };
query_results.add(group_bys);
final DataPoints[] results = func.evaluate(data_query, query_results, params);
assertEquals(1, results.length);
assertEquals(METRIC_STRING, results[0].metricName());
long ts = START_TIME;
double v = 11;
for (DataPoint dp : results[0]) {
assertEquals(ts, dp.timestamp());
assertEquals(v, dp.toDouble(), 0.001);
v += 2;
ts += INTERVAL;
}
}
@Test
public void sumMultipleSeriesEach() throws Exception {
oneExtraSameE();
queryAB_Dstar();
query_results.clear();
query_results.add(results.get("1").getValue());
query_results.add(results.get("0").getValue());
final DataPoints[] results = func.evaluate(data_query,
query_results, params);
assertEquals(3, results.length);
final int vals[] = new int[] { 12, 18, 17 };
for (int i = 0; i < results.length; i++) {
long ts = 1431561600000l;
final SeekableView it = results[i].iterator();
while (it.hasNext()) {
final DataPoint dp = it.next();
assertEquals(ts, dp.timestamp());
assertEquals(vals[i], dp.toDouble(), 0.0001);
if (i < 2) {
vals[i] += 2;
} else {
vals[i]++;
}
ts += INTERVAL;
}
}
}
@Test (expected = IllegalArgumentException.class)
public void sumOneResultSet() throws Exception {
func.evaluate(data_query, query_results, params);
}
@Test (expected = IllegalArgumentException.class)
public void sumTooManyResultSets() throws Exception {
SeekableView view2 = SeekableViewsForTest.generator(START_TIME, INTERVAL,
NUM_POINTS, true, 10, 1);
DataPoints dps2 = PowerMockito.mock(DataPoints.class);
when(dps2.iterator()).thenReturn(view2);
when(dps2.metricName()).thenReturn("sys.mem");
when(dps2.metricUID()).thenReturn(new byte[] {0,0,2});
group_bys = new DataPoints[] { dps2 };
// doesn't matter what they are
for (int i = 0; i < 100; i++) {
query_results.add(group_bys);
}
func.evaluate(data_query, query_results, params);
}
@Test (expected = IllegalArgumentException.class)
public void evaluateNullQuery() throws Exception {
params.add("1");
func.evaluate(null, query_results, params);
}
@Test
public void evaluateNullResults() throws Exception {
params.add("1");
final DataPoints[] results = func.evaluate(data_query, null, params);
assertEquals(0, results.length);
}
@Test (expected = IllegalArgumentException.class)
public void evaluateNullParams() throws Exception {
func.evaluate(data_query, query_results, null);
}
@Test
public void evaluateEmptyResults() throws Exception {
params.add("1");
final DataPoints[] results = func.evaluate(data_query,
Collections.<DataPoints[]>emptyList(), params);
assertEquals(0, results.length);
}
@Test
public void writeStringField() throws Exception {
params.add("1");
assertEquals("sumSeries(inner_expression)",
func.writeStringField(params, "inner_expression"));
assertEquals("sumSeries(null)", func.writeStringField(params, null));
assertEquals("sumSeries()", func.writeStringField(params, ""));
assertEquals("sumSeries(inner_expression)",
func.writeStringField(null, "inner_expression"));
}
}
| manolama/opentsdb | test/query/expression/TestSumSeries.java | Java | lgpl-2.1 | 6,720 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInsight.daemon.quickFix;
import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase;
import com.intellij.testFramework.LightProjectDescriptor;
import org.jetbrains.annotations.NotNull;
import static com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase.JAVA_15;
public class NormalizeRecordComponentFixTest extends LightQuickFixParameterizedTestCase {
@Override
protected @NotNull LightProjectDescriptor getProjectDescriptor() {
return JAVA_15;
}
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/normalizeRecordComponent";
}
}
| siosio/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/quickFix/NormalizeRecordComponentFixTest.java | Java | apache-2.0 | 1,267 |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.uif.util;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.kuali.rice.krad.datadictionary.Copyable;
import org.kuali.rice.krad.uif.component.DelayedCopy;
/**
* List implementation for internal use by a lifecycle element.
*
* <p>Mutability of the list will follow the semantics for the lifecycle element.</p>
*
* @author Kuali Rice Team ([email protected])
* @param <T> list item type
*/
public class LifecycleAwareList<T> implements List<T>, Copyable, Serializable {
private static final long serialVersionUID = -8971217230511446882L;
/**
* Delegating list iterator proxy.
*
* @author Kuali Rice Team ([email protected])
*/
private class ListIter implements ListIterator<T> {
private final ListIterator<T> delegate;
/**
* @see LifecycleAwareList#listIterator()
*/
private ListIter() {
this.delegate = LifecycleAwareList.this.delegate.listIterator();
}
/**
* @see LifecycleAwareList#listIterator(int)
*/
private ListIter(int index) {
this.delegate = LifecycleAwareList.this.delegate.listIterator(index);
}
@Override
public boolean hasNext() {
return this.delegate.hasNext();
}
@Override
public T next() {
return this.delegate.next();
}
@Override
public boolean hasPrevious() {
return this.delegate.hasPrevious();
}
@Override
public T previous() {
return this.delegate.previous();
}
@Override
public int nextIndex() {
return this.delegate.nextIndex();
}
@Override
public int previousIndex() {
return this.delegate.previousIndex();
}
@Override
public void remove() {
lifecycleElement.checkMutable(true);
this.delegate.remove();
}
@Override
public void set(T e) {
lifecycleElement.checkMutable(true);
this.delegate.set(e);
}
@Override
public void add(T e) {
lifecycleElement.checkMutable(true);
this.delegate.add(e);
}
}
/**
* Delegating iterator proxy.
*
* @author Kuali Rice Team ([email protected])
*/
private class Iter implements Iterator<T> {
private final Iterator<T> delegate;
/**
* @see LifecycleAwareList#iterator()
*/
private Iter() {
this.delegate = LifecycleAwareList.this.delegate.iterator();
}
@Override
public boolean hasNext() {
return this.delegate.hasNext();
}
@Override
public T next() {
return this.delegate.next();
}
@Override
public void remove() {
lifecycleElement.checkMutable(true);
this.delegate.remove();
}
}
/**
* The component this list is related to.
*/
private final LifecycleElement lifecycleElement;
/**
* Delegating list implementation.
*/
@DelayedCopy(inherit = true)
private List<T> delegate;
/**
* Create a new list instance.
*
* @param lifecycleElement The lifecycle element to use for mutability checks.
*/
public LifecycleAwareList(LifecycleElement lifecycleElement) {
this.lifecycleElement = lifecycleElement;
this.delegate = Collections.emptyList();
}
/**
* Create a new list instance, based on another list.
*
* @param lifecycleElement The lifecycle element to use for mutability checks.
* @param delegate The list to wrap.
*/
public LifecycleAwareList(LifecycleElement lifecycleElement, List<T> delegate) {
this.lifecycleElement = lifecycleElement;
List<T> wrapped = delegate;
while (wrapped instanceof LifecycleAwareList) {
wrapped = ((LifecycleAwareList<T>) wrapped).delegate;
}
this.delegate = delegate;
}
/**
* Ensure that the delegate list can be modified.
*/
private void ensureMutable() {
lifecycleElement.checkMutable(true);
if (delegate == Collections.EMPTY_LIST) {
delegate = new ArrayList<T>();
}
}
@Override
public int size() {
return this.delegate.size();
}
@Override
public boolean isEmpty() {
return this.delegate.isEmpty();
}
@Override
public boolean contains(Object o) {
return this.delegate.contains(o);
}
@Override
public Iterator<T> iterator() {
return new Iter();
}
@Override
public Object[] toArray() {
return this.delegate.toArray();
}
@Override
public <A> A[] toArray(A[] a) {
return this.delegate.toArray(a);
}
@Override
public boolean add(T e) {
ensureMutable();
return this.delegate.add(e);
}
@Override
public boolean remove(Object o) {
lifecycleElement.checkMutable(true);
return delegate != Collections.EMPTY_LIST && delegate.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return this.delegate.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends T> c) {
ensureMutable();
return this.delegate.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
ensureMutable();
return this.delegate.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c) {
lifecycleElement.checkMutable(true);
return delegate != Collections.EMPTY_LIST && this.delegate.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
lifecycleElement.checkMutable(true);
return delegate != Collections.EMPTY_LIST && this.delegate.retainAll(c);
}
@Override
public void clear() {
if (this.delegate != Collections.EMPTY_LIST) {
this.delegate.clear();
}
}
@Override
public boolean equals(Object o) {
return this.delegate.equals(o);
}
@Override
public int hashCode() {
return this.delegate.hashCode();
}
@Override
public T get(int index) {
return this.delegate.get(index);
}
@Override
public T set(int index, T element) {
lifecycleElement.checkMutable(true);
return this.delegate.set(index, element);
}
@Override
public void add(int index, T element) {
ensureMutable();
this.delegate.add(index, element);
}
@Override
public T remove(int index) {
lifecycleElement.checkMutable(true);
return this.delegate.remove(index);
}
@Override
public int indexOf(Object o) {
return this.delegate.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return this.delegate.lastIndexOf(o);
}
@Override
public ListIterator<T> listIterator() {
ensureMutable();
return new ListIter();
}
@Override
public ListIterator<T> listIterator(int index) {
ensureMutable();
return new ListIter(index);
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
return new LifecycleAwareList<T>(lifecycleElement, this.delegate.subList(fromIndex, toIndex));
}
/**
* @see java.lang.Object#clone()
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| ricepanda/rice-git2 | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/util/LifecycleAwareList.java | Java | apache-2.0 | 8,847 |
/*
* 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.server;
import java.io.Serializable;
import java.util.function.BiPredicate;
/**
* A {@link BiPredicate} that is also {@link Serializable}.
*
* @author Vaadin Ltd
* @since 8.0
* @param <T>
* the type of the first input to the predicate
* @param <U>
* the type of the second input to the predicate
*/
public interface SerializableBiPredicate<T, U>
extends BiPredicate<T, U>, Serializable {
// Only method inherited from BiPredicate
}
| Darsstar/framework | server/src/main/java/com/vaadin/server/SerializableBiPredicate.java | Java | apache-2.0 | 1,092 |
// Copyright 2000-2018 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.siyeh.ig.fixes.controlflow;
import com.intellij.codeInsight.daemon.quickFix.LightQuickFixParameterizedTestCase;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;
import com.siyeh.ig.LightJavaInspectionTestCase;
import com.siyeh.ig.controlflow.SwitchStatementsWithoutDefaultInspection;
import org.jetbrains.annotations.NotNull;
public class CreateDefaultBranchCompletenessFixTest extends LightQuickFixParameterizedTestCase {
@Override
protected LocalInspectionTool @NotNull [] configureLocalInspectionTools() {
return new SwitchStatementsWithoutDefaultInspection[]{new SwitchStatementsWithoutDefaultInspection()};
}
@Override
protected String getBasePath() {
return "/com/siyeh/igfixes/controlflow/create_default_completeness";
}
@Override
protected @NotNull LightProjectDescriptor getProjectDescriptor() {
return LightJavaCodeInsightFixtureTestCase.JAVA_17;
}
@NotNull
@Override
protected String getTestDataPath() {
return PathManagerEx.getCommunityHomePath() + LightJavaInspectionTestCase.INSPECTION_GADGETS_TEST_DATA_PATH;
}
}
| jwren/intellij-community | plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/controlflow/CreateDefaultBranchCompletenessFixTest.java | Java | apache-2.0 | 1,431 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.metrics.stats.extended;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSource.Numeric;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.aggregations.support.ValuesSourceParserHelper;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
public class ExtendedStatsAggregationBuilder
extends ValuesSourceAggregationBuilder.LeafOnly<ValuesSource.Numeric, ExtendedStatsAggregationBuilder> {
public static final String NAME = "extended_stats";
private static final ObjectParser<ExtendedStatsAggregationBuilder, Void> PARSER;
static {
PARSER = new ObjectParser<>(ExtendedStatsAggregationBuilder.NAME);
ValuesSourceParserHelper.declareNumericFields(PARSER, true, true, false);
PARSER.declareDouble(ExtendedStatsAggregationBuilder::sigma, ExtendedStatsAggregator.SIGMA_FIELD);
}
public static AggregationBuilder parse(String aggregationName, XContentParser parser) throws IOException {
return PARSER.parse(parser, new ExtendedStatsAggregationBuilder(aggregationName), null);
}
private double sigma = 2.0;
public ExtendedStatsAggregationBuilder(String name) {
super(name, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
}
protected ExtendedStatsAggregationBuilder(ExtendedStatsAggregationBuilder clone,
Builder factoriesBuilder, Map<String, Object> metaData) {
super(clone, factoriesBuilder, metaData);
this.sigma = clone.sigma;
}
@Override
protected AggregationBuilder shallowCopy(Builder factoriesBuilder, Map<String, Object> metaData) {
return new ExtendedStatsAggregationBuilder(this, factoriesBuilder, metaData);
}
/**
* Read from a stream.
*/
public ExtendedStatsAggregationBuilder(StreamInput in) throws IOException {
super(in, ValuesSourceType.NUMERIC, ValueType.NUMERIC);
sigma = in.readDouble();
}
@Override
protected void innerWriteTo(StreamOutput out) throws IOException {
out.writeDouble(sigma);
}
public ExtendedStatsAggregationBuilder sigma(double sigma) {
if (sigma < 0.0) {
throw new IllegalArgumentException("[sigma] must be greater than or equal to 0. Found [" + sigma + "] in [" + name + "]");
}
this.sigma = sigma;
return this;
}
public double sigma() {
return sigma;
}
@Override
protected ExtendedStatsAggregatorFactory innerBuild(SearchContext context, ValuesSourceConfig<Numeric> config,
AggregatorFactory<?> parent, Builder subFactoriesBuilder) throws IOException {
return new ExtendedStatsAggregatorFactory(name, config, sigma, context, parent, subFactoriesBuilder, metaData);
}
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
builder.field(ExtendedStatsAggregator.SIGMA_FIELD.getPreferredName(), sigma);
return builder;
}
@Override
protected int innerHashCode() {
return Objects.hash(sigma);
}
@Override
protected boolean innerEquals(Object obj) {
ExtendedStatsAggregationBuilder other = (ExtendedStatsAggregationBuilder) obj;
return Objects.equals(sigma, other.sigma);
}
@Override
public String getType() {
return NAME;
}
}
| strapdata/elassandra | server/src/main/java/org/elasticsearch/search/aggregations/metrics/stats/extended/ExtendedStatsAggregationBuilder.java | Java | apache-2.0 | 5,101 |
/*
* Copyright 2012-2013 eBay Software Foundation and ios-driver committers
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.uiautomation.ios.command.uiautomation;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.uiautomation.ios.communication.WebDriverLikeRequest;
import org.uiautomation.ios.IOSServerManager;
import org.uiautomation.ios.command.UIAScriptHandler;
import org.uiautomation.ios.utils.CoordinateUtils;
import org.uiautomation.ios.utils.JSTemplate;
import org.uiautomation.ios.drivers.RemoteIOSWebDriver;
import org.uiautomation.ios.wkrdp.model.NodeId;
import org.uiautomation.ios.wkrdp.model.RemoteWebElement;
import org.uiautomation.ios.wkrdp.model.RemoteWebNativeBackedElement;
public class FlickNHandler extends UIAScriptHandler {
// dragFromToForDuration()'s duration argument must be in [0.5 .. 60.0).
private static final JSTemplate plainFromElementTemplate = new JSTemplate(
"var element = UIAutomation.cache.get(%:nodeId$d, false);" +
"var status = Number(!element.isVisible());" +
"if (status == 0) {" +
"var hp = element.hitpoint();" +
"var toX = hp.x + %:offsetX$d;" +
"var toY = hp.y + %:offsetY$d;" +
"if (toX < 0) {toX = 0} else if (toX >= %:screenSizeX$d) {toX = %:screenSizeX$d - 1}" +
"if (toY < 0) {toY = 0} else if (toY >= %:screenSizeY$d) {toY = %:screenSizeY$d - 1}" +
"var dx = toX - hp.x;" +
"var dy = toY - hp.y;" +
"var distance = Math.sqrt(dx*dx + dy*dy);" +
"var duration = distance / %:speed$f;" +
"if (duration < 0.5) {" +
"UIATarget.localTarget().flickFromTo(hp, {x:toX, y:toY});" +
"} else {" +
"if (duration >= 60.0) {duration = 59.9}" +
"UIATarget.localTarget().dragFromToForDuration(hp, {x:toX, y:toY}, duration);" +
"}" +
"}" +
"UIAutomation.createJSONResponse('%:sessionId$s', status, '');",
"sessionId", "nodeId", "screenSizeX", "screenSizeY", "offsetX", "offsetY", "speed");
private static final JSTemplate fromToTemplate = new JSTemplate(
"var duration = %:duration$f;" +
"if (duration < 0.5) {" +
"UIATarget.localTarget().flickFromTo({x:%:fromX$d, y:%:fromY$d}, {x:%:toX$d, y:%:toY$d});" +
"} else {" +
"if (duration >= 60.0) {duration = 59.9}" +
"UIATarget.localTarget().dragFromToForDuration({x:%:fromX$d, y:%:fromY$d}, {x:%:toX$d, y:%:toY$d}, duration);" +
"}" +
"UIAutomation.createJSONResponse('%:sessionId$s', 0, '')",
"sessionId", "fromX", "fromY", "toX", "toY", "duration");
public FlickNHandler(IOSServerManager driver, WebDriverLikeRequest request) throws Exception {
super(driver, request);
JSONObject payload = request.getPayload();
Dimension screenSize = getNativeDriver().getScreenSize();
String elementId = payload.optString("element");
if (!payload.isNull("element") && !elementId.equals("")) {
Point offset = new Point(payload.getInt("xoffset"), payload.getInt("yoffset"));
double speed = payload.optDouble("speed", 1.0);
if (RemoteIOSWebDriver.isPlainElement(elementId)) {
NodeId nodeId = RemoteIOSWebDriver.plainNodeId(elementId);
plainFlickFromElement(request, screenSize, offset, speed, nodeId.getId());
} else {
nativeFlickFromElement(request, screenSize, offset, speed, elementId);
}
} else {
double speedX = payload.optDouble("xspeed", 1.0);
double speedY = payload.optDouble("yspeed", 1.0);
flickFromCenter(request, screenSize, speedX, speedY);
}
}
private void plainFlickFromElement(WebDriverLikeRequest request, Dimension screenSize, Point offset, double speed,
int nodeId) {
String js = plainFromElementTemplate.generate(
request.getSession(),
nodeId,
screenSize.getWidth(),
screenSize.getHeight(),
offset.getX(),
offset.getY(),
speed);
setJS(js);
}
private void nativeFlickFromElement(WebDriverLikeRequest request, Dimension screenSize, Point offset, double speed,
String elementId) throws Exception {
RemoteWebNativeBackedElement element = (RemoteWebNativeBackedElement) getWebDriver().createElement(elementId);
Point fromPoint = element.getLocation(RemoteWebElement.ElementPosition.CENTER);
Point toPoint = new Point(fromPoint.getX() + offset.getX(), fromPoint.getY() + offset.getY());
fromPoint = CoordinateUtils.forcePointOnScreen(fromPoint, screenSize);
toPoint = CoordinateUtils.forcePointOnScreen(toPoint, screenSize);
int dx = toPoint.getX() - fromPoint.getX();
int dy = toPoint.getY() - fromPoint.getY();
double distance = Math.sqrt(dx*dx + dy*dy);
double duration = distance / speed;
setJS(fromToTemplate.generate(
request.getSession(),
fromPoint.getX(),
fromPoint.getY(),
toPoint.getX(),
toPoint.getY(),
duration));
}
private void flickFromCenter(WebDriverLikeRequest request, Dimension screenSize, double speedX, double speedY) {
Point fromPoint = CoordinateUtils.getScreenCenter(screenSize);
// Convert "flick from center at given speed vector" to "drag from center to edge for duration".
double duration = Math.min(
fromPoint.getX() / Math.abs(speedX),
fromPoint.getY() / Math.abs(speedY));
Point toPoint = new Point(
(int)(fromPoint.getX() + speedX * duration),
(int)(fromPoint.getY() + speedY * duration));
toPoint = CoordinateUtils.forcePointOnScreen(toPoint, screenSize);
setJS(fromToTemplate.generate(
request.getSession(),
fromPoint.getX(),
fromPoint.getY(),
toPoint.getX(),
toPoint.getY(),
duration));
}
@Override
public JSONObject configurationDescription() throws JSONException {
return noConfigDefined();
}
}
| azaytsev/ios-driver | server/src/main/java/org/uiautomation/ios/command/uiautomation/FlickNHandler.java | Java | apache-2.0 | 6,522 |
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.dmn.client.commands.factory.canvas;
import org.kie.workbench.common.dmn.client.widgets.grid.model.DMNGridColumn;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.command.AbstractCanvasCommand;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommandResultBuilder;
import org.kie.workbench.common.stunner.core.client.command.CanvasViolation;
import org.kie.workbench.common.stunner.core.command.CommandResult;
public class SetComponentWidthCanvasCommand extends AbstractCanvasCommand {
private final DMNGridColumn uiColumn;
private final double oldWidth;
private final double width;
public SetComponentWidthCanvasCommand(final DMNGridColumn uiColumn,
final double oldWidth,
final double width) {
this.uiColumn = uiColumn;
this.oldWidth = oldWidth;
this.width = width;
}
@Override
public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler context) {
try {
uiColumn.setWidth(width);
uiColumn.getGridWidget().batch();
} catch (Exception e) {
return CanvasCommandResultBuilder.failed();
}
return CanvasCommandResultBuilder.SUCCESS;
}
@Override
public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler context) {
try {
uiColumn.setWidth(oldWidth);
uiColumn.getGridWidget().batch();
} catch (Exception e) {
return CanvasCommandResultBuilder.failed();
}
return CanvasCommandResultBuilder.SUCCESS;
}
}
| jomarko/kie-wb-common | kie-wb-common-dmn/kie-wb-common-dmn-client/src/main/java/org/kie/workbench/common/dmn/client/commands/factory/canvas/SetComponentWidthCanvasCommand.java | Java | apache-2.0 | 2,379 |
/*=========================================================================
* Copyright (c) 2010-2014 Pivotal Software, Inc. All Rights Reserved.
* This product is protected by U.S. and international copyright
* and intellectual property laws. Pivotal products are covered by
* one or more patents listed at http://www.pivotal.io/patents.
*=========================================================================
*/
package com.gemstone.gemfire.internal.cache;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import com.gemstone.gemfire.internal.InternalStatisticsDisabledException;
import com.gemstone.gemfire.internal.util.concurrent.CustomEntryConcurrentHashMap.HashEntry;
// macros whose definition changes this class:
// disk: DISK
// lru: LRU
// stats: STATS
// versioned: VERSIONED
// offheap: OFFHEAP
// One of the following key macros must be defined:
// key object: KEY_OBJECT
// key int: KEY_INT
// key long: KEY_LONG
// key uuid: KEY_UUID
// key string1: KEY_STRING1
// key string2: KEY_STRING2
/**
* Do not modify this class. It was generated.
* Instead modify LeafRegionEntry.cpp and then run
* bin/generateRegionEntryClasses.sh from the directory
* that contains your build.xml.
*/
public class VMStatsRegionEntryHeapStringKey1 extends VMStatsRegionEntryHeap {
public VMStatsRegionEntryHeapStringKey1 (RegionEntryContext context, String key,
Object value
, boolean byteEncode
) {
super(context,
value
);
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// caller has already confirmed that key.length <= MAX_INLINE_STRING_KEY
long tmpBits1 = 0L;
if (byteEncode) {
for (int i=key.length()-1; i >= 0; i--) {
// Note: we know each byte is <= 0x7f so the "& 0xff" is not needed. But I added it in to keep findbugs happy.
tmpBits1 |= (byte)key.charAt(i) & 0xff;
tmpBits1 <<= 8;
}
tmpBits1 |= 1<<6;
} else {
for (int i=key.length()-1; i >= 0; i--) {
tmpBits1 |= key.charAt(i);
tmpBits1 <<= 16;
}
}
tmpBits1 |= key.length();
this.bits1 = tmpBits1;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// common code
protected int hash;
private HashEntry<Object, Object> next;
@SuppressWarnings("unused")
private volatile long lastModified;
private static final AtomicLongFieldUpdater<VMStatsRegionEntryHeapStringKey1> lastModifiedUpdater
= AtomicLongFieldUpdater.newUpdater(VMStatsRegionEntryHeapStringKey1.class, "lastModified");
private volatile Object value;
@Override
protected final Object getValueField() {
return this.value;
}
@Override
protected void setValueField(Object v) {
this.value = v;
}
protected long getlastModifiedField() {
return lastModifiedUpdater.get(this);
}
protected boolean compareAndSetLastModifiedField(long expectedValue, long newValue) {
return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
}
/**
* @see HashEntry#getEntryHash()
*/
public final int getEntryHash() {
return this.hash;
}
protected void setEntryHash(int v) {
this.hash = v;
}
/**
* @see HashEntry#getNextEntry()
*/
public final HashEntry<Object, Object> getNextEntry() {
return this.next;
}
/**
* @see HashEntry#setNextEntry
*/
public final void setNextEntry(final HashEntry<Object, Object> n) {
this.next = n;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// stats code
@Override
public final void updateStatsForGet(boolean hit, long time)
{
setLastAccessed(time);
if (hit) {
incrementHitCount();
} else {
incrementMissCount();
}
}
@Override
protected final void setLastModified(long lastModified) {
_setLastModified(lastModified);
if (!DISABLE_ACCESS_TIME_UPDATE_ON_PUT) {
setLastAccessed(lastModified);
}
}
private volatile long lastAccessed;
private volatile int hitCount;
private volatile int missCount;
private static final AtomicIntegerFieldUpdater<VMStatsRegionEntryHeapStringKey1> hitCountUpdater
= AtomicIntegerFieldUpdater.newUpdater(VMStatsRegionEntryHeapStringKey1.class, "hitCount");
private static final AtomicIntegerFieldUpdater<VMStatsRegionEntryHeapStringKey1> missCountUpdater
= AtomicIntegerFieldUpdater.newUpdater(VMStatsRegionEntryHeapStringKey1.class, "missCount");
@Override
public final long getLastAccessed() throws InternalStatisticsDisabledException {
return this.lastAccessed;
}
private void setLastAccessed(long lastAccessed) {
this.lastAccessed = lastAccessed;
}
@Override
public final long getHitCount() throws InternalStatisticsDisabledException {
return this.hitCount & 0xFFFFFFFFL;
}
@Override
public final long getMissCount() throws InternalStatisticsDisabledException {
return this.missCount & 0xFFFFFFFFL;
}
private void incrementHitCount() {
hitCountUpdater.incrementAndGet(this);
}
private void incrementMissCount() {
missCountUpdater.incrementAndGet(this);
}
@Override
public final void resetCounts() throws InternalStatisticsDisabledException {
hitCountUpdater.set(this,0);
missCountUpdater.set(this,0);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
@Override
public final void txDidDestroy(long currTime) {
setLastModified(currTime);
setLastAccessed(currTime);
this.hitCount = 0;
this.missCount = 0;
}
@Override
public boolean hasStats() {
return true;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// key code
private final long bits1;
private int getKeyLength() {
return (int) (this.bits1 & 0x003fL);
}
private int getEncoding() {
// 0 means encoded as char
// 1 means encoded as bytes that are all <= 0x7f;
return (int) (this.bits1 >> 6) & 0x03;
}
@Override
public final Object getKey() {
int keylen = getKeyLength();
char[] chars = new char[keylen];
long tmpBits1 = this.bits1;
if (getEncoding() == 1) {
for (int i=0; i < keylen; i++) {
tmpBits1 >>= 8;
chars[i] = (char) (tmpBits1 & 0x00ff);
}
} else {
for (int i=0; i < keylen; i++) {
tmpBits1 >>= 16;
chars[i] = (char) (tmpBits1 & 0x00FFff);
}
}
return new String(chars);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
@Override
public boolean isKeyEqual(Object k) {
if (k instanceof String) {
String str = (String)k;
int keylen = getKeyLength();
if (str.length() == keylen) {
long tmpBits1 = this.bits1;
if (getEncoding() == 1) {
for (int i=0; i < keylen; i++) {
tmpBits1 >>= 8;
char c = (char) (tmpBits1 & 0x00ff);
if (str.charAt(i) != c) {
return false;
}
}
} else {
for (int i=0; i < keylen; i++) {
tmpBits1 >>= 16;
char c = (char) (tmpBits1 & 0x00FFff);
if (str.charAt(i) != c) {
return false;
}
}
}
return true;
}
}
return false;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
}
| ysung-pivotal/incubator-geode | gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/VMStatsRegionEntryHeapStringKey1.java | Java | apache-2.0 | 7,448 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.keycloak.testsuite.admin.test.role;
import org.jboss.arquillian.graphene.findby.FindByJQuery;
import org.jboss.arquillian.graphene.page.Page;
import org.junit.Test;
import org.keycloak.testsuite.admin.page.settings.RolesPage;
import org.keycloak.testsuite.admin.model.Role;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Ignore;
import org.keycloak.testsuite.admin.AbstractKeycloakTest;
import org.keycloak.testsuite.admin.fragment.FlashMessage;
import org.keycloak.testsuite.admin.page.settings.user.UserPage;
import static org.openqa.selenium.By.id;
import org.openqa.selenium.support.ui.Select;
/**
*
* @author Petr Mensik
*/
public class AddNewRoleTest extends AbstractKeycloakTest<RolesPage> {
@Page
private UserPage userPage;
@FindByJQuery(".alert")
private FlashMessage flashMessage;
@Before
public void beforeTestAddNewRole() {
navigation.roles();
}
@Test
public void testAddNewRole() {
Role role = new Role("role1");
page.addRole(role);
flashMessage.waitUntilPresent();
assertTrue(flashMessage.getText(), flashMessage.isSuccess());
navigation.roles();
assertEquals("role1", page.findRole(role.getName()).getName());
page.deleteRole(role);
}
@Ignore
@Test
public void testAddNewRoleWithLongName() {
String name = "hjewr89y1894yh98(*&*&$jhjkashd)*(&y8934h*&@#hjkahsdj";
page.addRole(new Role(name));
assertNotNull(page.findRole(name));
navigation.roles();
page.deleteRole(name);
}
@Test
public void testAddExistingRole() {
Role role = new Role("role2");
page.addRole(role);
flashMessage.waitUntilPresent();
assertTrue(flashMessage.getText(), flashMessage.isSuccess());
navigation.roles();
page.addRole(role);
flashMessage.waitUntilPresent();
assertTrue(flashMessage.getText(), flashMessage.isDanger());
navigation.roles();
page.deleteRole(role);
}
@Test
public void testRoleIsAvailableForUsers() {
Role role = new Role("User role");
page.addRole(role);
flashMessage.waitUntilPresent();
assertTrue(flashMessage.getText(), flashMessage.isSuccess());
navigation.users();
userPage.showAllUsers();
userPage.goToUser("admin");
navigation.roleMappings("Admin");
Select rolesSelect = new Select(driver.findElement(id("available")));
assertEquals("User role should be present in admin role mapping",
role.getName(), rolesSelect.getOptions().get(0).getText());
navigation.roles();
page.deleteRole(role);
}
}
| anaerobic/keycloak | testsuite/integration-arquillian/src/test/java/org/keycloak/testsuite/admin/test/role/AddNewRoleTest.java | Java | apache-2.0 | 2,921 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.hypervisor.vmware.mo;
public enum VmwareHostType {
ESXi, ESX
}
| wido/cloudstack | vmware-base/src/main/java/com/cloud/hypervisor/vmware/mo/VmwareHostType.java | Java | apache-2.0 | 887 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/monitoring.proto
package com.google.api;
public interface MonitoringOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.api.Monitoring)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Monitoring configurations for sending metrics to the producer project.
* There can be multiple producer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one producer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination producer_destinations = 1;</code>
*/
java.util.List<com.google.api.Monitoring.MonitoringDestination>
getProducerDestinationsList();
/**
* <pre>
* Monitoring configurations for sending metrics to the producer project.
* There can be multiple producer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one producer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination producer_destinations = 1;</code>
*/
com.google.api.Monitoring.MonitoringDestination getProducerDestinations(int index);
/**
* <pre>
* Monitoring configurations for sending metrics to the producer project.
* There can be multiple producer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one producer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination producer_destinations = 1;</code>
*/
int getProducerDestinationsCount();
/**
* <pre>
* Monitoring configurations for sending metrics to the producer project.
* There can be multiple producer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one producer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination producer_destinations = 1;</code>
*/
java.util.List<? extends com.google.api.Monitoring.MonitoringDestinationOrBuilder>
getProducerDestinationsOrBuilderList();
/**
* <pre>
* Monitoring configurations for sending metrics to the producer project.
* There can be multiple producer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one producer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination producer_destinations = 1;</code>
*/
com.google.api.Monitoring.MonitoringDestinationOrBuilder getProducerDestinationsOrBuilder(
int index);
/**
* <pre>
* Monitoring configurations for sending metrics to the consumer project.
* There can be multiple consumer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one consumer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination consumer_destinations = 2;</code>
*/
java.util.List<com.google.api.Monitoring.MonitoringDestination>
getConsumerDestinationsList();
/**
* <pre>
* Monitoring configurations for sending metrics to the consumer project.
* There can be multiple consumer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one consumer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination consumer_destinations = 2;</code>
*/
com.google.api.Monitoring.MonitoringDestination getConsumerDestinations(int index);
/**
* <pre>
* Monitoring configurations for sending metrics to the consumer project.
* There can be multiple consumer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one consumer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination consumer_destinations = 2;</code>
*/
int getConsumerDestinationsCount();
/**
* <pre>
* Monitoring configurations for sending metrics to the consumer project.
* There can be multiple consumer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one consumer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination consumer_destinations = 2;</code>
*/
java.util.List<? extends com.google.api.Monitoring.MonitoringDestinationOrBuilder>
getConsumerDestinationsOrBuilderList();
/**
* <pre>
* Monitoring configurations for sending metrics to the consumer project.
* There can be multiple consumer destinations, each one must have a
* different monitored resource type. A metric can be used in at most
* one consumer destination.
* </pre>
*
* <code>repeated .google.api.Monitoring.MonitoringDestination consumer_destinations = 2;</code>
*/
com.google.api.Monitoring.MonitoringDestinationOrBuilder getConsumerDestinationsOrBuilder(
int index);
}
| speedycontrol/googleapis | output/com/google/api/MonitoringOrBuilder.java | Java | apache-2.0 | 5,122 |
/*
* 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 org.jetbrains.idea.maven.server;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.Function;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.SystemProperties;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.apache.maven.*;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
import org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.ResolutionListener;
import org.apache.maven.cli.MavenCli;
import org.apache.maven.execution.*;
import org.apache.maven.model.Activation;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.Profile;
import org.apache.maven.model.building.*;
import org.apache.maven.model.interpolation.ModelInterpolator;
import org.apache.maven.model.io.ModelReader;
import org.apache.maven.model.profile.DefaultProfileInjector;
import org.apache.maven.model.validation.ModelValidator;
import org.apache.maven.plugin.LegacySupport;
import org.apache.maven.plugin.PluginDescriptorCache;
import org.apache.maven.plugin.internal.PluginDependenciesResolver;
import org.apache.maven.profiles.activation.*;
import org.apache.maven.project.*;
import org.apache.maven.project.ProjectDependenciesResolver;
import org.apache.maven.project.inheritance.DefaultModelInheritanceAssembler;
import org.apache.maven.project.interpolation.AbstractStringBasedModelInterpolator;
import org.apache.maven.project.interpolation.ModelInterpolationException;
import org.apache.maven.project.path.DefaultPathTranslator;
import org.apache.maven.project.path.PathTranslator;
import org.apache.maven.project.validation.ModelValidationResult;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.building.*;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeResolutionListener;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.classworlds.ClassWorld;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.context.ContextException;
import org.codehaus.plexus.context.DefaultContext;
import org.codehaus.plexus.logging.BaseLoggerManager;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.graph.DependencyVisitor;
import org.eclipse.aether.internal.impl.DefaultArtifactResolver;
import org.eclipse.aether.internal.impl.DefaultRepositorySystem;
import org.eclipse.aether.repository.LocalRepositoryManager;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.spi.log.LoggerFactory;
import org.eclipse.aether.util.graph.manager.DependencyManagerUtils;
import org.eclipse.aether.util.graph.transformer.ConflictResolver;
import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator;
import org.eclipse.aether.util.graph.visitor.TreeDependencyVisitor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.model.*;
import org.jetbrains.idea.maven.server.embedder.*;
import org.jetbrains.idea.maven.server.embedder.MavenExecutionResult;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.*;
/**
* Overridden maven components:
* <p/>
* maven-compat:
* org.jetbrains.idea.maven.server.embedder.CustomMaven3RepositoryMetadataManager <-> org.apache.maven.artifact.repository.metadata.DefaultRepositoryMetadataManager
* org.jetbrains.idea.maven.server.embedder.CustomMaven3ArtifactResolver <-> org.apache.maven.artifact.resolver.DefaultArtifactResolver
* org.jetbrains.idea.maven.server.embedder.CustomMaven3ModelInterpolator <-> org.apache.maven.project.interpolation.StringSearchModelInterpolator
* <p/>
* maven-core:
* org.jetbrains.idea.maven.server.embedder.CustomMaven3ArtifactFactory <-> org.apache.maven.artifact.factory.DefaultArtifactFactory
* org.jetbrains.idea.maven.server.embedder.CustomPluginDescriptorCache <-> org.apache.maven.plugin.DefaultPluginDescriptorCache
* <p/>
* maven-model-builder:
* org.jetbrains.idea.maven.server.embedder.CustomMaven3ModelInterpolator2 <-> org.apache.maven.model.interpolation.StringSearchModelInterpolator
* org.jetbrains.idea.maven.server.embedder.CustomModelValidator <-> org.apache.maven.model.validation.ModelValidator
*/
public class Maven3ServerEmbedderImpl extends Maven3ServerEmbedder {
@NotNull private final DefaultPlexusContainer myContainer;
@NotNull private final Settings myMavenSettings;
private final ArtifactRepository myLocalRepository;
private final Maven3ServerConsoleLogger myConsoleWrapper;
private final Properties mySystemProperties;
private volatile MavenServerProgressIndicator myCurrentIndicator;
private MavenWorkspaceMap myWorkspaceMap;
private Date myBuildStartTime;
private boolean myAlwaysUpdateSnapshots;
@Nullable private Properties myUserProperties;
public Maven3ServerEmbedderImpl(MavenEmbedderSettings settings) throws RemoteException {
super(settings.getSettings());
if (settings.getWorkingDirectory() != null) {
System.setProperty("user.dir", settings.getWorkingDirectory());
}
if (settings.getMultiModuleProjectDirectory() != null) {
System.setProperty("maven.multiModuleProjectDirectory", settings.getMultiModuleProjectDirectory());
}
else {
// initialize maven.multiModuleProjectDirectory property to avoid failure in org.apache.maven.cli.MavenCli#initialize method
System.setProperty("maven.multiModuleProjectDirectory", "");
}
MavenServerSettings serverSettings = settings.getSettings();
File mavenHome = serverSettings.getMavenHome();
if (mavenHome != null) {
System.setProperty("maven.home", mavenHome.getPath());
}
myConsoleWrapper = new Maven3ServerConsoleLogger();
myConsoleWrapper.setThreshold(serverSettings.getLoggingLevel());
ClassWorld classWorld = new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());
MavenCli cli = new MavenCli(classWorld) {
@Override
protected void customizeContainer(PlexusContainer container) {
((DefaultPlexusContainer)container).setLoggerManager(new BaseLoggerManager() {
@Override
protected Logger createLogger(String s) {
return myConsoleWrapper;
}
});
}
};
SettingsBuilder settingsBuilder = null;
Class cliRequestClass;
try {
cliRequestClass = MavenCli.class.getClassLoader().loadClass("org.apache.maven.cli.MavenCli$CliRequest");
}
catch (ClassNotFoundException e) {
try {
cliRequestClass = MavenCli.class.getClassLoader().loadClass("org.apache.maven.cli.CliRequest");
settingsBuilder = new DefaultSettingsBuilderFactory().newInstance();
}
catch (ClassNotFoundException e1) {
throw new RuntimeException("unable to find maven CliRequest class");
}
}
Object cliRequest;
try {
List<String> commandLineOptions = new ArrayList<String>(serverSettings.getUserProperties().size());
for (Map.Entry<Object, Object> each : serverSettings.getUserProperties().entrySet()) {
commandLineOptions.add("-D" + each.getKey() + "=" + each.getValue());
}
if (serverSettings.getLoggingLevel() == MavenServerConsole.LEVEL_DEBUG) {
commandLineOptions.add("-X");
commandLineOptions.add("-e");
}
else if (serverSettings.getLoggingLevel() == MavenServerConsole.LEVEL_DISABLED) {
commandLineOptions.add("-q");
}
String mavenEmbedderCliOptions = System.getProperty(MavenServerEmbedder.MAVEN_EMBEDDER_CLI_ADDITIONAL_ARGS);
if (mavenEmbedderCliOptions != null) {
commandLineOptions.addAll(StringUtil.splitHonorQuotes(mavenEmbedderCliOptions, ' '));
}
if (commandLineOptions.contains("-U") || commandLineOptions.contains("--update-snapshots")) {
myAlwaysUpdateSnapshots = true;
}
//noinspection unchecked
Constructor constructor = cliRequestClass.getDeclaredConstructor(String[].class, ClassWorld.class);
constructor.setAccessible(true);
//noinspection SSBasedInspection
cliRequest = constructor.newInstance(commandLineOptions.toArray(new String[commandLineOptions.size()]), classWorld);
for (String each : new String[]{"initialize", "cli", "logging", "properties"}) {
Method m = MavenCli.class.getDeclaredMethod(each, cliRequestClass);
m.setAccessible(true);
m.invoke(cli, cliRequest);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
// reset threshold
try {
Method m = MavenCli.class.getDeclaredMethod("container", cliRequestClass);
m.setAccessible(true);
myContainer = (DefaultPlexusContainer)m.invoke(cli, cliRequest);
}
catch (Exception e) {
throw new RuntimeException(e);
}
myContainer.getLoggerManager().setThreshold(serverSettings.getLoggingLevel());
mySystemProperties = ReflectionUtil.getField(cliRequestClass, cliRequest, Properties.class, "systemProperties");
if (serverSettings.getProjectJdk() != null) {
mySystemProperties.setProperty("java.home", serverSettings.getProjectJdk());
}
if (settingsBuilder == null) {
settingsBuilder = ReflectionUtil.getField(MavenCli.class, cli, SettingsBuilder.class, "settingsBuilder");
}
myMavenSettings = buildSettings(settingsBuilder, serverSettings, mySystemProperties,
ReflectionUtil.getField(cliRequestClass, cliRequest, Properties.class, "userProperties"));
myLocalRepository = createLocalRepository();
}
private static Settings buildSettings(SettingsBuilder builder,
MavenServerSettings settings,
Properties systemProperties,
Properties userProperties) throws RemoteException {
SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
settingsRequest.setGlobalSettingsFile(settings.getGlobalSettingsFile());
settingsRequest.setUserSettingsFile(settings.getUserSettingsFile());
settingsRequest.setSystemProperties(systemProperties);
settingsRequest.setUserProperties(userProperties);
Settings result = new Settings();
try {
result = builder.build(settingsRequest).getEffectiveSettings();
}
catch (SettingsBuildingException e) {
Maven3ServerGlobals.getLogger().info(e);
}
result.setOffline(settings.isOffline());
if (settings.getLocalRepository() != null) {
result.setLocalRepository(settings.getLocalRepository().getPath());
}
if (result.getLocalRepository() == null) {
result.setLocalRepository(new File(SystemProperties.getUserHome(), ".m2/repository").getPath());
}
return result;
}
private static void warn(String message, Throwable e) {
try {
Maven3ServerGlobals.getLogger().warn(new RuntimeException(message, e));
}
catch (RemoteException e1) {
throw new RuntimeException(e1);
}
}
private static MavenExecutionResult handleException(Throwable e) {
if (e instanceof Error) throw (Error)e;
return new MavenExecutionResult(Collections.singletonList((Exception)e));
}
private static Collection<String> collectActivatedProfiles(MavenProject mavenProject)
throws RemoteException {
// for some reason project's active profiles do not contain parent's profiles - only local and settings'.
// parent's profiles do not contain settings' profiles.
List<Profile> profiles = new ArrayList<Profile>();
try {
while (mavenProject != null) {
profiles.addAll(mavenProject.getActiveProfiles());
mavenProject = mavenProject.getParent();
}
}
catch (Exception e) {
// don't bother user if maven failed to build parent project
Maven3ServerGlobals.getLogger().info(e);
}
return collectProfilesIds(profiles);
}
private static List<Exception> filterExceptions(List<Throwable> list) {
for (Throwable throwable : list) {
if (!(throwable instanceof Exception)) {
throw new RuntimeException(throwable);
}
}
return (List<Exception>)((List)list);
}
@NotNull
public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException {
Model result = MavenModelConverter.toNativeModel(model);
result = doInterpolate(result, basedir);
PathTranslator pathTranslator = new DefaultPathTranslator();
pathTranslator.alignToBaseDirectory(result, basedir);
return MavenModelConverter.convertModel(result, null);
}
public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException {
Model result = MavenModelConverter.toNativeModel(model);
new DefaultModelInheritanceAssembler().assembleModelInheritance(result, MavenModelConverter.toNativeModel(parentModel));
return MavenModelConverter.convertModel(result, null);
}
public static ProfileApplicationResult applyProfiles(MavenModel model,
File basedir,
MavenExplicitProfiles explicitProfiles,
Collection<String> alwaysOnProfiles) throws RemoteException {
Model nativeModel = MavenModelConverter.toNativeModel(model);
Collection<String> enabledProfiles = explicitProfiles.getEnabledProfiles();
Collection<String> disabledProfiles = explicitProfiles.getDisabledProfiles();
List<Profile> activatedPom = new ArrayList<Profile>();
List<Profile> activatedExternal = new ArrayList<Profile>();
List<Profile> activeByDefault = new ArrayList<Profile>();
List<Profile> rawProfiles = nativeModel.getProfiles();
List<Profile> expandedProfilesCache = null;
List<Profile> deactivatedProfiles = new ArrayList<Profile>();
for (int i = 0; i < rawProfiles.size(); i++) {
Profile eachRawProfile = rawProfiles.get(i);
if (disabledProfiles.contains(eachRawProfile.getId())) {
deactivatedProfiles.add(eachRawProfile);
continue;
}
boolean shouldAdd = enabledProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId());
Activation activation = eachRawProfile.getActivation();
if (activation != null) {
if (activation.isActiveByDefault()) {
activeByDefault.add(eachRawProfile);
}
// expand only if necessary
if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles();
Profile eachExpandedProfile = expandedProfilesCache.get(i);
for (ProfileActivator eachActivator : getProfileActivators(basedir)) {
try {
if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) {
shouldAdd = true;
break;
}
}
catch (ProfileActivationException e) {
Maven3ServerGlobals.getLogger().warn(e);
}
}
}
if (shouldAdd) {
if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) {
activatedPom.add(eachRawProfile);
}
else {
activatedExternal.add(eachRawProfile);
}
}
}
List<Profile> activatedProfiles = new ArrayList<Profile>(activatedPom.isEmpty() ? activeByDefault : activatedPom);
activatedProfiles.addAll(activatedExternal);
for (Profile each : activatedProfiles) {
new DefaultProfileInjector().injectProfile(nativeModel, each, null, null);
}
return new ProfileApplicationResult(MavenModelConverter.convertModel(nativeModel, null),
new MavenExplicitProfiles(collectProfilesIds(activatedProfiles),
collectProfilesIds(deactivatedProfiles))
);
}
@NotNull
private static Model doInterpolate(@NotNull Model result, File basedir) throws RemoteException {
try {
AbstractStringBasedModelInterpolator interpolator = new CustomMaven3ModelInterpolator(new DefaultPathTranslator());
interpolator.initialize();
Properties props = MavenServerUtil.collectSystemProperties();
ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props);
config.setBuildStartTime(new Date());
result = interpolator.interpolate(result, basedir, config, false);
}
catch (ModelInterpolationException e) {
Maven3ServerGlobals.getLogger().warn(e);
}
catch (InitializationException e) {
Maven3ServerGlobals.getLogger().error(e);
}
return result;
}
private static Collection<String> collectProfilesIds(List<Profile> profiles) {
Collection<String> result = new THashSet<String>();
for (Profile each : profiles) {
if (each.getId() != null) {
result.add(each.getId());
}
}
return result;
}
private static ProfileActivator[] getProfileActivators(File basedir) throws RemoteException {
SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator();
DefaultContext context = new DefaultContext();
context.put("SystemProperties", MavenServerUtil.collectSystemProperties());
try {
sysPropertyActivator.contextualize(context);
}
catch (ContextException e) {
Maven3ServerGlobals.getLogger().error(e);
return new ProfileActivator[0];
}
return new ProfileActivator[]{new MyFileProfileActivator(basedir), sysPropertyActivator, new JdkPrefixProfileActivator(),
new OperatingSystemProfileActivator()};
}
@SuppressWarnings({"unchecked"})
public <T> T getComponent(Class<T> clazz, String roleHint) {
try {
return (T)myContainer.lookup(clazz.getName(), roleHint);
}
catch (ComponentLookupException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings({"unchecked"})
public <T> T getComponent(Class<T> clazz) {
try {
return (T)myContainer.lookup(clazz.getName());
}
catch (ComponentLookupException e) {
throw new RuntimeException(e);
}
}
private ArtifactRepository createLocalRepository() {
try {
final ArtifactRepository localRepository =
getComponent(RepositorySystem.class).createLocalRepository(new File(myMavenSettings.getLocalRepository()));
final String customRepoId = System.getProperty("maven3.localRepository.id", "localIntelliJ");
if (customRepoId != null) {
// see details at https://youtrack.jetbrains.com/issue/IDEA-121292
localRepository.setId(customRepoId);
}
return localRepository;
}
catch (InvalidRepositoryException e) {
throw new RuntimeException(e);
// Legacy code.
}
//ArtifactRepositoryLayout layout = getComponent(ArtifactRepositoryLayout.class, "default");
//ArtifactRepositoryFactory factory = getComponent(ArtifactRepositoryFactory.class);
//
//String url = myMavenSettings.getLocalRepository();
//if (!url.startsWith("file:")) url = "file://" + url;
//
//ArtifactRepository localRepository = factory.createArtifactRepository("local", url, layout, null, null);
//
//boolean snapshotPolicySet = myMavenSettings.isOffline();
//if (!snapshotPolicySet && snapshotUpdatePolicy == MavenServerSettings.UpdatePolicy.ALWAYS_UPDATE) {
// factory.setGlobalUpdatePolicy(ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS);
//}
//factory.setGlobalChecksumPolicy(ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN);
//
//return localRepository;
}
@Override
public void customize(@Nullable MavenWorkspaceMap workspaceMap,
boolean failOnUnresolvedDependency,
@NotNull MavenServerConsole console,
@NotNull MavenServerProgressIndicator indicator,
boolean alwaysUpdateSnapshots,
@Nullable Properties userProperties) throws RemoteException {
try {
customizeComponents();
((CustomMaven3ArtifactFactory)getComponent(ArtifactFactory.class)).customize();
((CustomMaven3ArtifactResolver)getComponent(ArtifactResolver.class)).customize(workspaceMap, failOnUnresolvedDependency);
((CustomMaven3RepositoryMetadataManager)getComponent(RepositoryMetadataManager.class)).customize(workspaceMap);
//((CustomMaven3WagonManager)getComponent(WagonManager.class)).customize(failOnUnresolvedDependency);
myWorkspaceMap = workspaceMap;
myBuildStartTime = new Date();
myAlwaysUpdateSnapshots = myAlwaysUpdateSnapshots || alwaysUpdateSnapshots;
setConsoleAndIndicator(console, new MavenServerProgressIndicatorWrapper(indicator));
myUserProperties = userProperties;
}
catch (Exception e) {
throw rethrowException(e);
}
}
public void customizeComponents() throws RemoteException {
// replace some plexus components
myContainer.addComponent(getComponent(ArtifactFactory.class, "ide"), ArtifactFactory.ROLE);
myContainer.addComponent(getComponent(ArtifactResolver.class, "ide"), ArtifactResolver.ROLE);
myContainer.addComponent(getComponent(RepositoryMetadataManager.class, "ide"), RepositoryMetadataManager.class.getName());
myContainer.addComponent(getComponent(PluginDescriptorCache.class, "ide"), PluginDescriptorCache.class.getName());
ModelInterpolator modelInterpolator = getComponent(ModelInterpolator.class, "ide");
myContainer.addComponent(modelInterpolator, ModelInterpolator.class.getName());
myContainer.addComponent(getComponent(org.apache.maven.project.interpolation.ModelInterpolator.class, "ide"),
org.apache.maven.project.interpolation.ModelInterpolator.ROLE);
ModelValidator modelValidator = getComponent(ModelValidator.class, "ide");
myContainer.addComponent(modelValidator, ModelValidator.class.getName());
DefaultModelBuilder defaultModelBuilder = (DefaultModelBuilder)getComponent(ModelBuilder.class);
defaultModelBuilder.setModelValidator(modelValidator);
defaultModelBuilder.setModelInterpolator(modelInterpolator);
}
private void setConsoleAndIndicator(MavenServerConsole console, MavenServerProgressIndicator indicator) {
myConsoleWrapper.setWrappee(console);
myCurrentIndicator = indicator;
}
@NotNull
@Override
public Collection<MavenServerExecutionResult> resolveProject(@NotNull Collection<File> files,
@NotNull Collection<String> activeProfiles,
@NotNull Collection<String> inactiveProfiles)
throws RemoteException, MavenServerProcessCanceledException {
final DependencyTreeResolutionListener listener = new DependencyTreeResolutionListener(myConsoleWrapper);
Collection<MavenExecutionResult> results =
doResolveProject(files, new ArrayList<String>(activeProfiles), new ArrayList<String>(inactiveProfiles),
Collections.<ResolutionListener>singletonList(listener));
return ContainerUtil.mapNotNull(results, new Function<MavenExecutionResult, MavenServerExecutionResult>() {
@Override
public MavenServerExecutionResult fun(MavenExecutionResult result) {
try {
return createExecutionResult(result.getPomFile(), result, listener.getRootNode());
}
catch (RemoteException e) {
ExceptionUtil.rethrowAllAsUnchecked(e);
}
return null;
}
});
}
@Nullable
@Override
public String evaluateEffectivePom(@NotNull File file, @NotNull List<String> activeProfiles, @NotNull List<String> inactiveProfiles)
throws RemoteException, MavenServerProcessCanceledException {
return MavenEffectivePomDumper.evaluateEffectivePom(this, file, activeProfiles, inactiveProfiles);
}
public void executeWithMavenSession(MavenExecutionRequest request, Runnable runnable) {
DefaultMaven maven = (DefaultMaven)getComponent(Maven.class);
RepositorySystemSession repositorySession = maven.newRepositorySession(request);
request.getProjectBuildingRequest().setRepositorySession(repositorySession);
MavenSession mavenSession = new MavenSession(myContainer, repositorySession, request, new DefaultMavenExecutionResult());
LegacySupport legacySupport = getComponent(LegacySupport.class);
MavenSession oldSession = legacySupport.getSession();
legacySupport.setSession(mavenSession);
/** adapted from {@link DefaultMaven#doExecute(MavenExecutionRequest)} */
try {
for (AbstractMavenLifecycleParticipant listener : getLifecycleParticipants(Collections.<MavenProject>emptyList())) {
listener.afterSessionStart(mavenSession);
}
}
catch (MavenExecutionException e) {
throw new RuntimeException(e);
}
try {
runnable.run();
}
finally {
legacySupport.setSession(oldSession);
}
}
@NotNull
public Collection<MavenExecutionResult> doResolveProject(@NotNull final Collection<File> files,
@NotNull final List<String> activeProfiles,
@NotNull final List<String> inactiveProfiles,
final List<ResolutionListener> listeners) throws RemoteException {
final File file = files.size() == 1 ? files.iterator().next() : null;
final MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles, null);
request.setUpdateSnapshots(myAlwaysUpdateSnapshots);
final Collection<MavenExecutionResult> executionResults = ContainerUtil.newArrayList();
executeWithMavenSession(request, new Runnable() {
@Override
public void run() {
try {
RepositorySystemSession repositorySession = getComponent(LegacySupport.class).getRepositorySession();
if (repositorySession instanceof DefaultRepositorySystemSession) {
DefaultRepositorySystemSession session = (DefaultRepositorySystemSession)repositorySession;
session.setTransferListener(new TransferListenerAdapter(myCurrentIndicator));
if (myWorkspaceMap != null) {
session.setWorkspaceReader(new Maven3WorkspaceReader(myWorkspaceMap));
}
session.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true);
session.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true);
}
List<ProjectBuildingResult> buildingResults = getProjectBuildingResults(request, files);
for (ProjectBuildingResult buildingResult : buildingResults) {
MavenProject project = buildingResult.getProject();
if (project == null) {
List<Exception> exceptions = new ArrayList<Exception>();
for (ModelProblem problem : buildingResult.getProblems()) {
exceptions.add(problem.getException());
}
MavenExecutionResult mavenExecutionResult = new MavenExecutionResult(buildingResult.getPomFile(), exceptions);
executionResults.add(mavenExecutionResult);
continue;
}
List<Exception> exceptions = new ArrayList<Exception>();
loadExtensions(project, exceptions);
//Artifact projectArtifact = project.getArtifact();
//Map managedVersions = project.getManagedVersionMap();
//ArtifactMetadataSource metadataSource = getComponent(ArtifactMetadataSource.class);
project.setDependencyArtifacts(project.createArtifacts(getComponent(ArtifactFactory.class), null, null));
//
if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
addMvn2CompatResults(project, exceptions, listeners, myLocalRepository, executionResults);
}
else {
final DependencyResolutionResult dependencyResolutionResult = resolveDependencies(project, repositorySession);
final List<Dependency> dependencies = dependencyResolutionResult.getDependencies();
final Map<Dependency, Artifact> winnerDependencyMap = new IdentityHashMap<Dependency, Artifact>();
Set<Artifact> artifacts = new LinkedHashSet<Artifact>(dependencies.size());
dependencyResolutionResult.getDependencyGraph().accept(new TreeDependencyVisitor(new DependencyVisitor() {
@Override
public boolean visitEnter(org.eclipse.aether.graph.DependencyNode node) {
final Object winner = node.getData().get(ConflictResolver.NODE_DATA_WINNER);
final Dependency dependency = node.getDependency();
if (dependency != null && winner == null) {
Artifact winnerArtifact = Maven3AetherModelConverter.toArtifact(dependency);
winnerDependencyMap.put(dependency, winnerArtifact);
}
return true;
}
@Override
public boolean visitLeave(org.eclipse.aether.graph.DependencyNode node) {
return true;
}
}));
for (Dependency dependency : dependencies) {
final Artifact artifact = winnerDependencyMap.get(dependency);
if(artifact != null) {
artifacts.add(artifact);
resolveAsModule(artifact);
}
}
project.setArtifacts(artifacts);
executionResults.add(new MavenExecutionResult(project, dependencyResolutionResult, exceptions));
}
}
}
catch (Exception e) {
executionResults.add(handleException(e));
}
}
});
return executionResults;
}
private boolean resolveAsModule(Artifact a) {
MavenWorkspaceMap map = myWorkspaceMap;
if (map == null) return false;
MavenWorkspaceMap.Data resolved = map.findFileAndOriginalId(MavenModelConverter.createMavenId(a));
if (resolved == null) return false;
a.setResolved(true);
a.setFile(resolved.getFile(a.getType()));
a.selectVersion(resolved.originalId.getVersion());
return true;
}
/**
* copied from {@link DefaultProjectBuilder#resolveDependencies(MavenProject, org.sonatype.aether.RepositorySystemSession)}
*/
private DependencyResolutionResult resolveDependencies(MavenProject project, RepositorySystemSession session) {
DependencyResolutionResult resolutionResult;
try {
ProjectDependenciesResolver dependencyResolver = getComponent(ProjectDependenciesResolver.class);
DefaultDependencyResolutionRequest resolution = new DefaultDependencyResolutionRequest(project, session);
resolutionResult = dependencyResolver.resolve(resolution);
}
catch (DependencyResolutionException e) {
resolutionResult = e.getResult();
}
Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
if (resolutionResult.getDependencyGraph() != null) {
RepositoryUtils.toArtifacts(artifacts, resolutionResult.getDependencyGraph().getChildren(),
Collections.singletonList(project.getArtifact().getId()), null);
// Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved or not
LocalRepositoryManager lrm = session.getLocalRepositoryManager();
for (Artifact artifact : artifacts) {
if (!artifact.isResolved()) {
String path = lrm.getPathForLocalArtifact(RepositoryUtils.toArtifact(artifact));
artifact.setFile(new File(lrm.getRepository().getBasedir(), path));
}
}
}
project.setResolvedArtifacts(artifacts);
project.setArtifacts(artifacts);
return resolutionResult;
}
/**
* adapted from {@link DefaultMaven#doExecute(MavenExecutionRequest)}
*/
private void loadExtensions(MavenProject project, List<Exception> exceptions) {
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
Collection<AbstractMavenLifecycleParticipant> lifecycleParticipants = getLifecycleParticipants(Arrays.asList(project));
if (!lifecycleParticipants.isEmpty()) {
LegacySupport legacySupport = getComponent(LegacySupport.class);
MavenSession session = legacySupport.getSession();
session.setCurrentProject(project);
try {
// the method can be removed
session.setAllProjects(Arrays.asList(project));
}
catch (NoSuchMethodError ignore) {
}
session.setProjects(Arrays.asList(project));
for (AbstractMavenLifecycleParticipant listener : lifecycleParticipants) {
Thread.currentThread().setContextClassLoader(listener.getClass().getClassLoader());
try {
listener.afterProjectsRead(session);
}
catch (Exception e) {
exceptions.add(e);
}
finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
}
}
}
/**
* adapted from {@link DefaultMaven#getLifecycleParticipants(Collection)}
*/
private Collection<AbstractMavenLifecycleParticipant> getLifecycleParticipants(Collection<MavenProject> projects) {
Collection<AbstractMavenLifecycleParticipant> lifecycleListeners = new LinkedHashSet<AbstractMavenLifecycleParticipant>();
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
try {
lifecycleListeners.addAll(myContainer.lookupList(AbstractMavenLifecycleParticipant.class));
}
catch (ComponentLookupException e) {
// this is just silly, lookupList should return an empty list!
warn("Failed to lookup lifecycle participants", e);
}
Collection<ClassLoader> scannedRealms = new HashSet<ClassLoader>();
for (MavenProject project : projects) {
ClassLoader projectRealm = project.getClassRealm();
if (projectRealm != null && scannedRealms.add(projectRealm)) {
Thread.currentThread().setContextClassLoader(projectRealm);
try {
lifecycleListeners.addAll(myContainer.lookupList(AbstractMavenLifecycleParticipant.class));
}
catch (ComponentLookupException e) {
// this is just silly, lookupList should return an empty list!
warn("Failed to lookup lifecycle participants", e);
}
}
}
}
finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
return lifecycleListeners;
}
public MavenExecutionRequest createRequest(@Nullable File file,
@Nullable List<String> activeProfiles,
@Nullable List<String> inactiveProfiles,
@Nullable List<String> goals)
throws RemoteException {
//Properties executionProperties = myMavenSettings.getProperties();
//if (executionProperties == null) {
// executionProperties = new Properties();
//}
MavenExecutionRequest result = new DefaultMavenExecutionRequest();
try {
getComponent(MavenExecutionRequestPopulator.class).populateFromSettings(result, myMavenSettings);
result.setGoals(goals == null ? Collections.<String>emptyList() : goals);
result.setPom(file);
getComponent(MavenExecutionRequestPopulator.class).populateDefaults(result);
result.setSystemProperties(mySystemProperties);
result.setUserProperties(myUserProperties);
if (activeProfiles != null) {
result.setActiveProfiles(activeProfiles);
}
if (inactiveProfiles != null) {
result.setInactiveProfiles(inactiveProfiles);
}
result.setCacheNotFound(true);
result.setCacheTransferError(true);
result.setStartTime(myBuildStartTime);
final Method setMultiModuleProjectDirectoryMethod =
ReflectionUtil.findMethod(ReflectionUtil.getClassDeclaredMethods(result.getClass()), "setMultiModuleProjectDirectory", File.class);
if (setMultiModuleProjectDirectoryMethod != null) {
try {
if (file == null) {
file = new File(FileUtil.getTempDirectory());
}
setMultiModuleProjectDirectoryMethod.invoke(result, MavenServerUtil.findMavenBasedir(file));
}
catch (Exception e) {
Maven3ServerGlobals.getLogger().error(e);
}
}
return result;
}
catch (MavenExecutionRequestPopulationException e) {
throw new RuntimeException(e);
}
}
@NotNull
public File getLocalRepositoryFile() {
return new File(myLocalRepository.getBasedir());
}
@NotNull
private MavenServerExecutionResult createExecutionResult(@Nullable File file, MavenExecutionResult result, DependencyNode rootNode)
throws RemoteException {
Collection<MavenProjectProblem> problems = MavenProjectProblem.createProblemsList();
THashSet<MavenId> unresolvedArtifacts = new THashSet<MavenId>();
validate(file, result.getExceptions(), problems, unresolvedArtifacts);
MavenProject mavenProject = result.getMavenProject();
if (mavenProject == null) return new MavenServerExecutionResult(null, problems, unresolvedArtifacts);
MavenModel model = new MavenModel();
try {
if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
//noinspection unchecked
final List<DependencyNode> dependencyNodes = rootNode == null ? Collections.emptyList() : rootNode.getChildren();
model = MavenModelConverter.convertModel(
mavenProject.getModel(), mavenProject.getCompileSourceRoots(), mavenProject.getTestCompileSourceRoots(),
mavenProject.getArtifacts(), dependencyNodes, mavenProject.getExtensionArtifacts(), getLocalRepositoryFile());
}
else {
final DependencyResolutionResult dependencyResolutionResult = result.getDependencyResolutionResult();
final org.eclipse.aether.graph.DependencyNode dependencyGraph =
dependencyResolutionResult != null ? dependencyResolutionResult.getDependencyGraph() : null;
final List<org.eclipse.aether.graph.DependencyNode> dependencyNodes =
dependencyGraph != null ? dependencyGraph.getChildren() : Collections.<org.eclipse.aether.graph.DependencyNode>emptyList();
model = Maven3AetherModelConverter.convertModelWithAetherDependencyTree(
mavenProject.getModel(), mavenProject.getCompileSourceRoots(), mavenProject.getTestCompileSourceRoots(),
mavenProject.getArtifacts(), dependencyNodes, mavenProject.getExtensionArtifacts(), getLocalRepositoryFile());
}
}
catch (Exception e) {
validate(mavenProject.getFile(), Collections.singleton(e), problems, null);
}
RemoteNativeMavenProjectHolder holder = new RemoteNativeMavenProjectHolder(mavenProject);
try {
UnicastRemoteObject.exportObject(holder, 0);
}
catch (RemoteException e) {
throw new RuntimeException(e);
}
Collection<String> activatedProfiles = collectActivatedProfiles(mavenProject);
MavenServerExecutionResult.ProjectData data =
new MavenServerExecutionResult.ProjectData(model, MavenModelConverter.convertToMap(mavenProject.getModel()), holder,
activatedProfiles);
return new MavenServerExecutionResult(data, problems, unresolvedArtifacts);
}
private void validate(@Nullable File file,
@NotNull Collection<Exception> exceptions,
@NotNull Collection<MavenProjectProblem> problems,
@Nullable Collection<MavenId> unresolvedArtifacts) throws RemoteException {
for (Throwable each : exceptions) {
if(each == null) continue;
Maven3ServerGlobals.getLogger().info(each);
if (each instanceof IllegalStateException && each.getCause() != null) {
each = each.getCause();
}
String path = file == null ? "" : file.getPath();
if (path.isEmpty() && each instanceof ProjectBuildingException) {
File pomFile = ((ProjectBuildingException)each).getPomFile();
path = pomFile == null ? "" : pomFile.getPath();
}
if (each instanceof InvalidProjectModelException) {
ModelValidationResult modelValidationResult = ((InvalidProjectModelException)each).getValidationResult();
if (modelValidationResult != null) {
for (Object eachValidationProblem : modelValidationResult.getMessages()) {
problems.add(MavenProjectProblem.createStructureProblem(path, (String)eachValidationProblem));
}
}
else {
problems.add(MavenProjectProblem.createStructureProblem(path, each.getCause().getMessage()));
}
}
else if (each instanceof ProjectBuildingException) {
String causeMessage = each.getCause() != null ? each.getCause().getMessage() : each.getMessage();
problems.add(MavenProjectProblem.createStructureProblem(path, causeMessage));
}
else if (each.getStackTrace().length > 0 && each.getClass().getPackage().getName().equals("groovy.lang")) {
StackTraceElement traceElement = each.getStackTrace()[0];
problems.add(MavenProjectProblem.createStructureProblem(
traceElement.getFileName() + ":" + traceElement.getLineNumber(), each.getMessage()));
}
else {
problems.add(MavenProjectProblem.createStructureProblem(path, each.getMessage()));
}
}
if (unresolvedArtifacts != null) {
unresolvedArtifacts.addAll(retrieveUnresolvedArtifactIds());
}
}
private Set<MavenId> retrieveUnresolvedArtifactIds() {
Set<MavenId> result = new THashSet<MavenId>();
// TODO collect unresolved artifacts
//((CustomMaven3WagonManager)getComponent(WagonManager.class)).getUnresolvedCollector().retrieveUnresolvedIds(result);
//((CustomMaven30ArtifactResolver)getComponent(ArtifactResolver.class)).getUnresolvedCollector().retrieveUnresolvedIds(result);
return result;
}
@NotNull
@Override
public MavenArtifact resolve(@NotNull MavenArtifactInfo info, @NotNull List<MavenRemoteRepository> remoteRepositories)
throws RemoteException, MavenServerProcessCanceledException {
return doResolve(info, remoteRepositories);
}
@NotNull
@Override
public List<MavenArtifact> resolveTransitively(@NotNull List<MavenArtifactInfo> artifacts,
@NotNull List<MavenRemoteRepository> remoteRepositories)
throws RemoteException, MavenServerProcessCanceledException {
try {
Set<Artifact> toResolve = new LinkedHashSet<Artifact>();
for (MavenArtifactInfo each : artifacts) {
toResolve.add(createArtifact(each));
}
Artifact project = getComponent(ArtifactFactory.class).createBuildArtifact("temp", "temp", "666", "pom");
Set<Artifact> res = getComponent(ArtifactResolver.class)
.resolveTransitively(toResolve, project, Collections.EMPTY_MAP, myLocalRepository, convertRepositories(remoteRepositories),
getComponent(ArtifactMetadataSource.class)).getArtifacts();
return MavenModelConverter.convertArtifacts(res, new THashMap<Artifact, MavenArtifact>(), getLocalRepositoryFile());
}
catch (ArtifactResolutionException e) {
Maven3ServerGlobals.getLogger().info(e);
}
catch (ArtifactNotFoundException e) {
Maven3ServerGlobals.getLogger().info(e);
}
catch (Exception e) {
throw rethrowException(e);
}
return Collections.emptyList();
}
@Override
public Collection<MavenArtifact> resolvePlugin(@NotNull final MavenPlugin plugin,
@NotNull final List<MavenRemoteRepository> repositories,
int nativeMavenProjectId,
final boolean transitive) throws RemoteException, MavenServerProcessCanceledException {
try {
Plugin mavenPlugin = new Plugin();
mavenPlugin.setGroupId(plugin.getGroupId());
mavenPlugin.setArtifactId(plugin.getArtifactId());
mavenPlugin.setVersion(plugin.getVersion());
MavenProject project = RemoteNativeMavenProjectHolder.findProjectById(nativeMavenProjectId);
Plugin pluginFromProject = project.getBuild().getPluginsAsMap().get(plugin.getGroupId() + ':' + plugin.getArtifactId());
if (pluginFromProject != null) {
mavenPlugin.setDependencies(pluginFromProject.getDependencies());
}
final MavenExecutionRequest request =
createRequest(null, null, null, null);
DefaultMaven maven = (DefaultMaven)getComponent(Maven.class);
RepositorySystemSession repositorySystemSession = maven.newRepositorySession(request);
PluginDependenciesResolver pluginDependenciesResolver = getComponent(PluginDependenciesResolver.class);
org.eclipse.aether.artifact.Artifact pluginArtifact =
pluginDependenciesResolver.resolve(mavenPlugin, project.getRemotePluginRepositories(), repositorySystemSession);
org.eclipse.aether.graph.DependencyNode node = pluginDependenciesResolver
.resolve(mavenPlugin, pluginArtifact, null, project.getRemotePluginRepositories(), repositorySystemSession);
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept(nlg);
List<MavenArtifact> res = new ArrayList<MavenArtifact>();
for (org.eclipse.aether.artifact.Artifact artifact : nlg.getArtifacts(true)) {
if (!Comparing.equal(artifact.getArtifactId(), plugin.getArtifactId()) ||
!Comparing.equal(artifact.getGroupId(), plugin.getGroupId())) {
res.add(MavenModelConverter.convertArtifact(RepositoryUtils.toArtifact(artifact), getLocalRepositoryFile()));
}
}
return res;
}
catch (Exception e) {
Maven3ServerGlobals.getLogger().info(e);
return Collections.emptyList();
}
}
@Override
@Nullable
public MavenModel readModel(File file) throws RemoteException {
Map<String, Object> inputOptions = new HashMap<String, Object>();
inputOptions.put(ModelProcessor.SOURCE, new FileModelSource(file));
ModelReader reader = null;
if (!StringUtil.endsWithIgnoreCase(file.getName(), "xml")) {
try {
Object polyglotManager = myContainer.lookup("org.sonatype.maven.polyglot.PolyglotModelManager");
if (polyglotManager != null) {
Method getReaderFor = ReflectionUtil.getMethod(polyglotManager.getClass(), "getReaderFor", Map.class);
if (getReaderFor != null) {
reader = (ModelReader)getReaderFor.invoke(polyglotManager, inputOptions);
}
}
}
catch (ComponentLookupException ignore) {
}
catch (Throwable e) {
Maven3ServerGlobals.getLogger().warn(e);
}
}
if (reader == null) {
try {
reader = myContainer.lookup(ModelReader.class);
}
catch (ComponentLookupException ignore) {
}
}
if (reader != null) {
try {
Model model = reader.read(file, inputOptions);
return MavenModelConverter.convertModel(model, null);
}
catch (Exception e) {
Maven3ServerGlobals.getLogger().warn(e);
}
}
return null;
}
private MavenArtifact doResolve(MavenArtifactInfo info, List<MavenRemoteRepository> remoteRepositories) throws RemoteException {
Artifact resolved = doResolve(createArtifact(info), convertRepositories(remoteRepositories));
return MavenModelConverter.convertArtifact(resolved, getLocalRepositoryFile());
}
private Artifact doResolve(Artifact artifact, List<ArtifactRepository> remoteRepositories) throws RemoteException {
try {
return resolve(artifact, remoteRepositories);
}
catch (Exception e) {
Maven3ServerGlobals.getLogger().info(e);
}
return artifact;
}
private Artifact resolve(@NotNull final Artifact artifact, @NotNull final List<ArtifactRepository> repos)
throws
ArtifactResolutionException,
ArtifactNotFoundException,
RemoteException,
org.eclipse.aether.resolution.ArtifactResolutionException {
final String mavenVersion = getMavenVersion();
// org.eclipse.aether.RepositorySystem.newResolutionRepositories() method doesn't exist in aether-api-0.9.0.M2.jar used before maven 3.2.5
// see https://youtrack.jetbrains.com/issue/IDEA-140208 for details
if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING || StringUtil.compareVersionNumbers(mavenVersion, "3.2.5") < 0) {
MavenExecutionRequest request = new DefaultMavenExecutionRequest();
request.setRemoteRepositories(repos);
try {
getComponent(MavenExecutionRequestPopulator.class).populateFromSettings(request, myMavenSettings);
getComponent(MavenExecutionRequestPopulator.class).populateDefaults(request);
}
catch (MavenExecutionRequestPopulationException e) {
throw new RuntimeException(e);
}
getComponent(ArtifactResolver.class).resolve(artifact, request.getRemoteRepositories(), myLocalRepository);
return artifact;
}
else {
final MavenExecutionRequest request =
createRequest(null, null, null, null);
for (ArtifactRepository artifactRepository : repos) {
request.addRemoteRepository(artifactRepository);
}
DefaultMaven maven = (DefaultMaven)getComponent(Maven.class);
RepositorySystemSession repositorySystemSession = maven.newRepositorySession(request);
final org.eclipse.aether.impl.ArtifactResolver artifactResolver = getComponent(org.eclipse.aether.impl.ArtifactResolver.class);
final MyLoggerFactory loggerFactory = new MyLoggerFactory();
if (artifactResolver instanceof DefaultArtifactResolver) {
((DefaultArtifactResolver)artifactResolver).setLoggerFactory(loggerFactory);
}
final org.eclipse.aether.RepositorySystem repositorySystem = getComponent(org.eclipse.aether.RepositorySystem.class);
if (repositorySystem instanceof DefaultRepositorySystem) {
((DefaultRepositorySystem)repositorySystem).setLoggerFactory(loggerFactory);
}
// do not use request.getRemoteRepositories() here,
// it can be broken after DefaultMaven#newRepositorySession => MavenRepositorySystem.injectMirror invocation
List<RemoteRepository> repositories = RepositoryUtils.toRepos(repos);
repositories = repositorySystem.newResolutionRepositories(repositorySystemSession, repositories);
final ArtifactResult artifactResult = repositorySystem.resolveArtifact(
repositorySystemSession, new ArtifactRequest(RepositoryUtils.toArtifact(artifact), repositories, null));
return RepositoryUtils.toArtifact(artifactResult.getArtifact());
}
}
@NotNull
protected List<ArtifactRepository> convertRepositories(List<MavenRemoteRepository> repositories) throws RemoteException {
List<ArtifactRepository> result = new ArrayList<ArtifactRepository>();
for (MavenRemoteRepository each : repositories) {
try {
ArtifactRepositoryFactory factory = getComponent(ArtifactRepositoryFactory.class);
result.add(ProjectUtils.buildArtifactRepository(MavenModelConverter.toNativeRepository(each), factory, myContainer));
}
catch (InvalidRepositoryException e) {
Maven3ServerGlobals.getLogger().warn(e);
}
}
return result;
}
private Artifact createArtifact(MavenArtifactInfo info) {
return getComponent(ArtifactFactory.class)
.createArtifactWithClassifier(info.getGroupId(), info.getArtifactId(), info.getVersion(), info.getPackaging(), info.getClassifier());
}
@NotNull
@Override
public MavenServerExecutionResult execute(@NotNull File file,
@NotNull Collection<String> activeProfiles,
@NotNull Collection<String> inactiveProfiles,
@NotNull List<String> goals,
@NotNull List<String> selectedProjects,
boolean alsoMake,
boolean alsoMakeDependents) throws RemoteException, MavenServerProcessCanceledException {
MavenExecutionResult result =
doExecute(file, new ArrayList<String>(activeProfiles), new ArrayList<String>(inactiveProfiles), goals, selectedProjects, alsoMake,
alsoMakeDependents);
return createExecutionResult(file, result, null);
}
private MavenExecutionResult doExecute(@NotNull final File file,
@NotNull final List<String> activeProfiles,
@NotNull final List<String> inactiveProfiles,
@NotNull final List<String> goals,
@NotNull final List<String> selectedProjects,
boolean alsoMake,
boolean alsoMakeDependents) throws RemoteException {
MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles, goals);
if (!selectedProjects.isEmpty()) {
request.setRecursive(true);
request.setSelectedProjects(selectedProjects);
if (alsoMake && alsoMakeDependents) {
request.setMakeBehavior(ReactorManager.MAKE_BOTH_MODE);
}
else if (alsoMake) {
request.setMakeBehavior(ReactorManager.MAKE_MODE);
}
else if (alsoMakeDependents) {
request.setMakeBehavior(ReactorManager.MAKE_DEPENDENTS_MODE);
}
}
org.apache.maven.execution.MavenExecutionResult executionResult = safeExecute(request, getComponent(Maven.class));
return new MavenExecutionResult(executionResult.getProject(), filterExceptions(executionResult.getExceptions()));
}
private org.apache.maven.execution.MavenExecutionResult safeExecute(MavenExecutionRequest request, Maven maven) throws RemoteException {
MavenLeakDetector detector = new MavenLeakDetector().mark();
org.apache.maven.execution.MavenExecutionResult result = maven.execute(request);
detector.check();
return result;
}
@Override
public void reset() throws RemoteException {
try {
setConsoleAndIndicator(null, null);
final ArtifactFactory artifactFactory = getComponent(ArtifactFactory.class);
if (artifactFactory instanceof CustomMaven3ArtifactFactory) {
((CustomMaven3ArtifactFactory)artifactFactory).reset();
}
final ArtifactResolver artifactResolver = getComponent(ArtifactResolver.class);
if(artifactResolver instanceof CustomMaven3ArtifactResolver) {
((CustomMaven3ArtifactResolver)artifactResolver).reset();
}
final RepositoryMetadataManager repositoryMetadataManager = getComponent(RepositoryMetadataManager.class);
if(repositoryMetadataManager instanceof CustomMaven3RepositoryMetadataManager) {
((CustomMaven3RepositoryMetadataManager)repositoryMetadataManager).reset();
}
//((CustomWagonManager)getComponent(WagonManager.class)).reset();
}
catch (Exception e) {
throw rethrowException(e);
}
}
@Override
public void release() throws RemoteException {
myContainer.dispose();
}
public void clearCaches() throws RemoteException {
// do nothing
}
public void clearCachesFor(final MavenId projectId) throws RemoteException {
// do nothing
}
@Override
protected ArtifactRepository getLocalRepository() {
return myLocalRepository;
}
public interface Computable<T> {
T compute();
}
private class MyLoggerFactory implements LoggerFactory {
@Override
public org.eclipse.aether.spi.log.Logger getLogger(String s) {
return new org.eclipse.aether.spi.log.Logger() {
@Override
public boolean isDebugEnabled() {
return myConsoleWrapper.isDebugEnabled();
}
@Override
public void debug(String s) {
myConsoleWrapper.debug(s);
}
@Override
public void debug(String s, Throwable throwable) {
myConsoleWrapper.debug(s, throwable);
}
@Override
public boolean isWarnEnabled() {
return myConsoleWrapper.isWarnEnabled();
}
@Override
public void warn(String s) {
myConsoleWrapper.warn(s);
}
@Override
public void warn(String s, Throwable throwable) {
myConsoleWrapper.debug(s, throwable);
}
};
}
}
}
| asedunov/intellij-community | plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedderImpl.java | Java | apache-2.0 | 59,004 |
/*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.tests.themes.valo;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.UI;
public class ResponsiveStyles extends UI {
@Override
protected void init(VaadinRequest request) {
ResponsiveStylesDesign design = new ResponsiveStylesDesign();
setContent(design);
boolean collapsed = request.getParameter("collapsed") != null;
design.collapsed.setVisible(collapsed);
design.narrow.setVisible(!collapsed);
design.wide.setVisible(!collapsed);
}
}
| Darsstar/framework | uitest/src/main/java/com/vaadin/tests/themes/valo/ResponsiveStyles.java | Java | apache-2.0 | 1,126 |
/*
* 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.xquery;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XQueryComponentConfigurationTest extends CamelSpringTestSupport {
@Test
public void testConfiguration() throws Exception {
XQueryComponent component = context.getComponent("xquery", XQueryComponent.class);
XQueryEndpoint endpoint = context.getEndpoint("xquery:org/apache/camel/component/xquery/transform.xquery", XQueryEndpoint.class);
assertNotNull(component.getConfiguration());
assertNotNull(component.getConfigurationProperties());
assertEquals(component.getConfiguration(), endpoint.getConfiguration());
assertEquals(component.getConfigurationProperties(), endpoint.getConfigurationProperties());
}
@Override
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/component/xquery/XQueryComponentConfigurationTest.xml");
}
} | davidkarlsen/camel | components/camel-saxon/src/test/java/org/apache/camel/component/xquery/XQueryComponentConfigurationTest.java | Java | apache-2.0 | 1,906 |
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.notification.mgt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.wso2.carbon.identity.notification.mgt.bean.ModuleConfiguration;
import org.wso2.carbon.identity.notification.mgt.bean.Subscription;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.securevault.SecretResolver;
import org.wso2.securevault.SecretResolverFactory;
import java.io.*;
import java.net.URL;
import java.util.*;
/**
* Configuration builder class for Message Management component. Responsible for reading msg-mgt
* .properties file and extract properties and distribute them to relevant message sending
* components.
*/
@SuppressWarnings("unused")
public class NotificationMgtConfigBuilder {
private static final Log log = LogFactory.getLog(NotificationMgtConfigBuilder.class);
/**
* All properties configured in msg-mgt.properties file
*/
private Properties notificationMgtConfigProperties;
/**
* Map of configurations which are specific to notification sending modules
*/
private Map<String, ModuleConfiguration> moduleConfiguration;
/**
* Thread pool size for message sending task
*/
private String threadPoolSize;
/**
* Load properties file and set Module properties
*
* @param bundleContext Bundle context
* @throws NotificationManagementException
*/
public NotificationMgtConfigBuilder(BundleContext bundleContext) throws NotificationManagementException {
notificationMgtConfigProperties = loadProperties(bundleContext);
setThreadPoolSize();
resolveSecrets();
moduleConfiguration = new HashMap<String, ModuleConfiguration>();
build();
}
/**
* Sets the thread pool size read from configurations
*/
private void setThreadPoolSize() {
threadPoolSize = (String) notificationMgtConfigProperties.remove(NotificationMgtConstants.Configs.
THREAD_POOL_SIZE);
}
/**
* Load properties which are defined in msg-mgt.properties file
*
* @param bundleContext Bundle context
* @return Set of properties which are defined in msg-mgt.properties file
* @throws NotificationManagementException
*/
private Properties loadProperties(BundleContext bundleContext) throws NotificationManagementException {
Properties properties = new Properties();
InputStream inStream = null;
// Open the default configuration file in carbon conf directory path .
File MessageMgtPropertyFile = new File(CarbonUtils.getCarbonConfigDirPath(),
NotificationMgtConstants.MODULE_CONFIG_FILE);
try {
// If the configuration exists in the carbon conf directory, read properties from there
if (MessageMgtPropertyFile.exists()) {
inStream = new FileInputStream(MessageMgtPropertyFile);
// Else read properties form either bundle context path or class path
} else {
URL url;
if (bundleContext != null) {
if ((url = bundleContext.getBundle().getResource(NotificationMgtConstants.MODULE_CONFIG_FILE))
!= null) {
inStream = url.openStream();
} else {
log.warn("Bundle context could not find resource " + NotificationMgtConstants
.MODULE_CONFIG_FILE);
}
// If bundle context is not found, read properties file from class path
} else {
if ((url = this.getClass().getClassLoader().getResource(NotificationMgtConstants.
MODULE_CONFIG_FILE)) != null) {
inStream = url.openStream();
} else {
log.warn("Class resource loader could not find resource " + NotificationMgtConstants.
MODULE_CONFIG_FILE);
}
}
}
if (inStream != null) {
properties.load(inStream);
}
//Even if the configurations are not found, individual modules can behave themselves without configuration
} catch (FileNotFoundException e) {
log.warn("Could not find configuration file for Message Sending module", e);
} catch (IOException e) {
log.warn("Error while opening input stream for property file", e);
// Finally close input stream
} finally {
try {
if (inStream != null) {
inStream.close();
}
} catch (IOException e) {
log.error("Error while closing input stream ", e);
}
}
return properties;
}
/**
* Build and store per module configuration objects
*/
private void build() {
Properties moduleNames = NotificationManagementUtils.getSubProperties(NotificationMgtConstants.Configs.
MODULE_NAME, notificationMgtConfigProperties);
Enumeration propertyNames = moduleNames.propertyNames();
// Iterate through events and build event objects
while (propertyNames.hasMoreElements()) {
String key = (String) propertyNames.nextElement();
String moduleName = (String) moduleNames.remove(key);
moduleConfiguration.put(moduleName, buildModuleConfigurations(moduleName));
}
}
/**
* Building per module configuration objects
*
* @param moduleName Name of the module
* @return ModuleConfiguration object which has configurations for the given module name
*/
private ModuleConfiguration buildModuleConfigurations(String moduleName) {
Properties moduleProperties = getModuleProperties(moduleName);
List<Subscription> subscriptionList = buildSubscriptionList(moduleName, moduleProperties);
return new ModuleConfiguration(getModuleProperties(moduleName), subscriptionList);
}
/**
* Build a list of subscription by a particular module
*
* @param moduleName Name of the module
* @param moduleProperties Set of properties which
* @return A list of subscriptions by the module
*/
private List<Subscription> buildSubscriptionList(String moduleName, Properties moduleProperties) {
// Get subscribed events
Properties subscriptions = NotificationManagementUtils.getSubProperties(moduleName + "." +
NotificationMgtConstants.Configs.SUBSCRIPTION, moduleProperties);
List<Subscription> subscriptionList = new ArrayList<Subscription>();
Enumeration propertyNames = subscriptions.propertyNames();
// Iterate through events and build event objects
while (propertyNames.hasMoreElements()) {
String key = (String) propertyNames.nextElement();
String subscriptionName = (String) subscriptions.remove(key);
// Read all the event properties starting from the event prefix
Properties subscriptionProperties = NotificationManagementUtils.getPropertiesWithPrefix
(moduleName + "." + NotificationMgtConstants.Configs.SUBSCRIPTION + "." + subscriptionName,
moduleProperties);
Subscription subscription = new Subscription(subscriptionName, subscriptionProperties);
subscriptionList.add(subscription);
}
return subscriptionList;
}
/**
* Retrieve all properties defined for a particular module
*
* @param moduleName Name of the module
* @return A set of properties which are defined for a particular module
*/
private Properties getModuleProperties(String moduleName) {
return NotificationManagementUtils.getPropertiesWithPrefix(moduleName, notificationMgtConfigProperties);
}
/**
* Returns a module configuration object for the passed mdoule name
*
* @param moduleName Name of the module
* @return Module configuration object which is relevant to the given name.
*/
public ModuleConfiguration getModuleConfigurations(String moduleName) {
return this.moduleConfiguration.get(moduleName);
}
public String getThreadPoolSize() {
return threadPoolSize;
}
/**
* There can be sensitive information like passwords in configuration file. If they are encrypted using secure
* vault, this method will resolve them and replace with original values.
*/
private void resolveSecrets() {
SecretResolver secretResolver = SecretResolverFactory.create(notificationMgtConfigProperties);
Enumeration propertyNames = notificationMgtConfigProperties.propertyNames();
if (secretResolver != null && secretResolver.isInitialized()) {
// Iterate through whole config file and find encrypted properties and resolve them
while (propertyNames.hasMoreElements()) {
String key = (String) propertyNames.nextElement();
if (secretResolver.isTokenProtected(key)) {
if (log.isDebugEnabled()) {
log.debug("Resolving and replacing secret for " + key);
}
// Resolving the secret password.
String value = secretResolver.resolve(key);
// Replaces the original encrypted property with resolved property
notificationMgtConfigProperties.put(key, value);
} else {
if (log.isDebugEnabled()) {
log.debug("No encryption done for value with key :" + key);
}
}
}
} else {
log.warn("Secret Resolver is not present. Will not resolve encryptions in config file");
}
}
}
| rswijesena/carbon-identity | components/notification-mgt/org.wso2.carbon.identity.notification.mgt/src/main/java/org/wso2/carbon/identity/notification/mgt/NotificationMgtConfigBuilder.java | Java | apache-2.0 | 10,717 |
/*
* 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.hive.hbase;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.io.BytesWritable;
public class HBaseScanRange implements Serializable {
private byte[] startRow;
private byte[] stopRow;
private List<FilterDesc> filterDescs = new ArrayList<FilterDesc>();
public byte[] getStartRow() {
return startRow;
}
public void setStartRow(byte[] startRow) {
this.startRow = startRow;
}
public byte[] getStopRow() {
return stopRow;
}
public void setStopRow(byte[] stopRow) {
this.stopRow = stopRow;
}
public void addFilter(Filter filter) throws Exception {
Class<? extends Filter> clazz = filter.getClass();
clazz.getMethod("parseFrom", byte[].class); // valiade
filterDescs.add(new FilterDesc(clazz.getName(), filter.toByteArray()));
}
public void setup(Scan scan, Configuration conf) throws Exception {
setup(scan, conf, false);
}
public void setup(Scan scan, Configuration conf, boolean filterOnly) throws Exception {
if (!filterOnly) {
// Set the start and stop rows only if asked to
if (startRow != null) {
scan.setStartRow(startRow);
}
if (stopRow != null) {
scan.setStopRow(stopRow);
}
}
if (filterDescs.isEmpty()) {
return;
}
if (filterDescs.size() == 1) {
scan.setFilter(filterDescs.get(0).toFilter(conf));
return;
}
List<Filter> filters = new ArrayList<Filter>();
for (FilterDesc filter : filterDescs) {
filters.add(filter.toFilter(conf));
}
scan.setFilter(new FilterList(filters));
}
@Override
public String toString() {
return (startRow == null ? "" : new BytesWritable(startRow).toString()) + " ~ " +
(stopRow == null ? "" : new BytesWritable(stopRow).toString());
}
private static class FilterDesc implements Serializable {
private String className;
private byte[] binary;
public FilterDesc(String className, byte[] binary) {
this.className = className;
this.binary = binary;
}
public Filter toFilter(Configuration conf) throws Exception {
return (Filter) getFactoryMethod(className, conf).invoke(null, binary);
}
private Method getFactoryMethod(String className, Configuration conf) throws Exception {
Class<?> clazz = conf.getClassByName(className);
return clazz.getMethod("parseFrom", byte[].class);
}
}
}
| sankarh/hive | hbase-handler/src/java/org/apache/hadoop/hive/hbase/HBaseScanRange.java | Java | apache-2.0 | 3,494 |
/**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kew.service;
import org.apache.log4j.Logger;
import org.kuali.rice.core.api.config.module.RunMode;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
import org.kuali.rice.edl.framework.extract.ExtractService;
import org.kuali.rice.kew.actionlist.service.ActionListService;
import org.kuali.rice.kew.actionrequest.service.ActionRequestService;
import org.kuali.rice.kew.actions.ActionRegistry;
import org.kuali.rice.kew.actiontaken.service.ActionTakenService;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.batch.ExternalActnListNotificationService;
import org.kuali.rice.kew.batch.XmlPollerService;
import org.kuali.rice.kew.docsearch.DocumentSearchCustomizationMediator;
import org.kuali.rice.kew.docsearch.service.DocumentSearchService;
import org.kuali.rice.kew.doctype.service.DocumentSecurityService;
import org.kuali.rice.kew.doctype.service.DocumentTypePermissionService;
import org.kuali.rice.kew.doctype.service.DocumentTypeService;
import org.kuali.rice.kew.documentlink.service.DocumentLinkService;
import org.kuali.rice.kew.engine.WorkflowEngineFactory;
import org.kuali.rice.kew.engine.node.service.BranchService;
import org.kuali.rice.kew.engine.node.service.RouteNodeService;
import org.kuali.rice.kew.engine.simulation.SimulationWorkflowEngine;
import org.kuali.rice.kew.exception.WorkflowDocumentExceptionRoutingService;
import org.kuali.rice.kew.identity.service.IdentityHelperService;
import org.kuali.rice.kew.impl.document.WorkflowDocumentPrototype;
import org.kuali.rice.kew.mail.service.ActionListEmailService;
import org.kuali.rice.kew.mail.service.EmailContentService;
import org.kuali.rice.kew.notes.service.NoteService;
import org.kuali.rice.kew.notification.service.NotificationService;
import org.kuali.rice.kew.responsibility.service.ResponsibilityIdService;
import org.kuali.rice.kew.role.service.RoleService;
import org.kuali.rice.kew.routeheader.service.RouteHeaderService;
import org.kuali.rice.kew.routeheader.service.WorkflowDocumentService;
import org.kuali.rice.kew.routemodule.service.RouteModuleService;
import org.kuali.rice.kew.routemodule.service.RoutingReportService;
import org.kuali.rice.kew.rule.WorkflowRuleAttributeMediator;
import org.kuali.rice.kew.rule.service.RuleAttributeService;
import org.kuali.rice.kew.rule.service.RuleDelegationService;
import org.kuali.rice.kew.rule.service.RuleServiceInternal;
import org.kuali.rice.kew.rule.service.RuleTemplateService;
import org.kuali.rice.kew.useroptions.UserOptionsService;
import org.kuali.rice.kew.validation.RuleValidationAttributeResolver;
import org.springframework.cache.CacheManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import javax.xml.namespace.QName;
/**
* Convenience class that holds service names and provide methods to acquire services. Defaults to
* GLR for actual service acquisition. Used to be responsible for loading and holding spring
* application context (when it was SpringServiceLocator) but those responsibilities have been
* moved to the SpringLoader.
*
* @author Kuali Rice Team ([email protected])
*
*/
public final class KEWServiceLocator {
private static final Logger LOG = Logger.getLogger(KEWServiceLocator.class);
public static final String KEW_RUN_MODE_PROPERTY = "kew.mode";
public static final String DATASOURCE = "kewDataSource";
public static final String QUICK_LINKS_SERVICE = "enQuickLinksService";
public static final String DOCUMENT_SEARCH_SERVICE = "enDocumentSearchService";
public static final String ACTION_TAKEN_SRV = "enActionTakenService";
public static final String ACTION_REQUEST_SRV = "enActionRequestService";
public static final String ACTION_LIST_SRV = "enActionListService";
public static final String DOC_ROUTE_HEADER_SRV = "enDocumentRouteHeaderService";
public static final String DOCUMENT_TYPE_GROUP_SERVICE = "enDocumentTypeGroupService";
public static final String DOCUMENT_TYPE_SERVICE = "enDocumentTypeService";
public static final String DOCUMENT_TYPE_PERMISSION_SERVICE = "enDocumentTypePermissionService";
public static final String DOCUMENT_SECURITY_SERVICE = "enDocumentSecurityService";
public static final String USER_OPTIONS_SRV = "enUserOptionsService";
public static final String DOCUMENT_CHANGE_HISTORY_SRV = "enDocumentChangeHistoryService";
public static final String DOCUMENT_VALUE_INDEX_SRV = "enDocumentValueIndexService";
public static final String ROUTE_LEVEL_SERVICE = "enRouteLevelService";
public static final String CONSTANTS_SERVICE = "enApplicationConstantsService";
public static final String ROUTE_LOG_SERVICE = "enRouteLogService";
public static final String RULE_TEMPLATE_SERVICE = "enRuleTemplateService";
public static final String RULE_SERVICE = "enRuleServiceInternal";
public static final String RULE_ATTRIBUTE_SERVICE = "enRuleAttributeService";
public static final String RULE_TEMPLATE_ATTRIBUTE_SERVICE = "enRuleTemplateAttributeService";
public static final String ROLE_SERVICE = "enRoleService";
public static final String RESPONSIBILITY_ID_SERVICE = "enResponsibilityIdService";
public static final String STATS_SERVICE = "enStatsService";
public static final String ROUTE_MANAGER_QUEUE_SERVICE = "enRouteManagerQueueService";
public static final String ROUTE_MANAGER_CONTROLLER = "enRouteManagerController";
public static final String RULE_DELEGATION_SERVICE = "enRuleDelegationService";
public static final String ROUTE_MANAGER_DRIVER = "enRouteManagerDriver";
public static final String OPTIMISTIC_LOCK_FAILURE_SERVICE = "enOptimisticLockFailureService";
public static final String NOTE_SERVICE = "enNoteService";
public static final String ROUTING_REPORT_SERVICE = "enRoutingReportService";
public static final String ROUTE_MODULE_SERVICE = "enRouteModuleService";
public static final String EXCEPTION_ROUTING_SERVICE = "enExceptionRoutingService";
public static final String ACTION_REGISTRY = "enActionRegistry";
public static final String BRANCH_SERVICE = "enBranchService";
public static final String WORKFLOW_MBEAN = "workflowMBean";
public static final String JTA_TRANSACTION_MANAGER = "jtaTransactionManager";
public static final String USER_TRANSACTION = "userTransaction";
public static final String SCHEDULER = "enScheduler";
public static final String DOCUMENT_LINK_SERVICE = "enDocumentLinkService";
/**
* Polls for xml files on disk
*/
public static final String XML_POLLER_SERVICE = "enXmlPollerService";
public static final String EXTERNAL_ACTN_LIST_NOTIFICATION_SERVICE = "rice.kew.externalActnListNotificationService";
public static final String DB_TABLES_LOADER = "enDbTablesLoader";
public static final String ROUTE_NODE_SERVICE = "enRouteNodeService";
public static final String SIMULATION_ENGINE = "simulationEngine";
public static final String WORKFLOW_ENGINE_FACTORY = "workflowEngineFactory";
public static final String ACTION_LIST_EMAIL_SERVICE = "enActionListEmailService";
public static final String EMAIL_CONTENT_SERVICE = "enEmailContentService";
public static final String NOTIFICATION_SERVICE = "enNotificationService";
public static final String TRANSACTION_MANAGER = "transactionManager";
public static final String TRANSACTION_TEMPLATE = "transactionTemplate";
public static final String WORKFLOW_DOCUMENT_SERVICE = "enWorkflowDocumentService";
public static final String EXTENSION_SERVICE = "enExtensionService";
public static final String TRANSFORMATION_SERVICE = "enTransformationService";
public static final String REMOVE_REPLACE_DOCUMENT_SERVICE = "enRemoveReplaceDocumentService";
public static final String EXTRACT_SERVICE = "enExtractService";
public static final String IDENTITY_HELPER_SERVICE = "kewIdentityHelperService";
public static final String ENTITY_MANAGER_FACTORY = "kewEntityManagerFactory";
public static final String MAILER = "mailer";
public static final String WORKFLOW_DOCUMENT_PROTOTYPE = "rice.kew.workflowDocumentPrototype";
public static final String DOCUMENT_SEARCH_CUSTOMIZATION_MEDIATOR = "rice.kew.documentSearchCustomizationMediator";
public static final String RULE_VALIDATION_ATTRIBUTE_RESOLVER = "rice.kew.ruleValidationAttributeResolver";
public static final String WORKFLOW_RULE_ATTRIBUTE_MEDIATOR = "rice.kew.workflowRuleAttributeMediator";
public static final String LOCAL_CACHE_MANAGER = "kewLocalCacheManager";
public static EntityManagerFactory getEntityManagerFactory() {
return (EntityManagerFactory) getService(ENTITY_MANAGER_FACTORY);
}
/**
* @param serviceName
* the name of the service bean
* @return the service
*/
public static <T> T getService(String serviceName) {
return KEWServiceLocator.<T>getBean(serviceName);
}
public static <T> T getBean(String serviceName) {
if ( LOG.isDebugEnabled() ) {
LOG.debug("Fetching service " + serviceName);
}
QName name = new QName(serviceName);
RunMode kewRunMode = RunMode.valueOf(ConfigContext.getCurrentContextConfig().getProperty(KEW_RUN_MODE_PROPERTY));
if (kewRunMode == RunMode.REMOTE || kewRunMode == RunMode.THIN) {
if (!serviceName.equals(WORKFLOW_DOCUMENT_PROTOTYPE)) {
name = new QName(KewApiConstants.Namespaces.KEW_NAMESPACE_2_0, serviceName);
} else {
name = new QName(serviceName);
}
}
return GlobalResourceLoader.getResourceLoader().<T>getService(name);
}
public static DocumentTypeService getDocumentTypeService() {
return (DocumentTypeService) getBean(DOCUMENT_TYPE_SERVICE);
}
public static DocumentTypePermissionService getDocumentTypePermissionService() {
return (DocumentTypePermissionService) getBean(DOCUMENT_TYPE_PERMISSION_SERVICE);
}
public static DocumentSecurityService getDocumentSecurityService() {
return (DocumentSecurityService) getBean(DOCUMENT_SECURITY_SERVICE);
}
public static ActionRequestService getActionRequestService() {
return (ActionRequestService) getBean(ACTION_REQUEST_SRV);
}
public static ActionTakenService getActionTakenService() {
return (ActionTakenService) getBean(ACTION_TAKEN_SRV);
}
public static ResponsibilityIdService getResponsibilityIdService() {
return (ResponsibilityIdService) getBean(RESPONSIBILITY_ID_SERVICE);
}
public static RouteHeaderService getRouteHeaderService() {
return (RouteHeaderService) getBean(DOC_ROUTE_HEADER_SRV);
}
public static RuleTemplateService getRuleTemplateService() {
return (RuleTemplateService) getBean(RULE_TEMPLATE_SERVICE);
}
public static RuleAttributeService getRuleAttributeService() {
return (RuleAttributeService) getBean(RULE_ATTRIBUTE_SERVICE);
}
public static WorkflowDocumentService getWorkflowDocumentService() {
return (WorkflowDocumentService) getBean(WORKFLOW_DOCUMENT_SERVICE);
}
public static RouteModuleService getRouteModuleService() {
return (RouteModuleService) getBean(ROUTE_MODULE_SERVICE);
}
public static RoleService getRoleService() {
return (RoleService) getBean(ROLE_SERVICE);
}
public static RuleServiceInternal getRuleService() {
return (RuleServiceInternal) getBean(RULE_SERVICE);
}
public static RuleDelegationService getRuleDelegationService() {
return (RuleDelegationService) getBean(RULE_DELEGATION_SERVICE);
}
public static RoutingReportService getRoutingReportService() {
return (RoutingReportService) getBean(ROUTING_REPORT_SERVICE);
}
public static XmlPollerService getXmlPollerService() {
return (XmlPollerService) getBean(XML_POLLER_SERVICE);
}
public static ExternalActnListNotificationService getExternalActnListNotificationService() {
return (ExternalActnListNotificationService) getBean(EXTERNAL_ACTN_LIST_NOTIFICATION_SERVICE);
}
public static UserOptionsService getUserOptionsService() {
return (UserOptionsService) getBean(USER_OPTIONS_SRV);
}
public static ActionListService getActionListService() {
return (ActionListService) getBean(ACTION_LIST_SRV);
}
public static RouteNodeService getRouteNodeService() {
return (RouteNodeService) getBean(ROUTE_NODE_SERVICE);
}
public static SimulationWorkflowEngine getSimulationEngine() {
return (SimulationWorkflowEngine) getBean(SIMULATION_ENGINE);
}
public static WorkflowEngineFactory getWorkflowEngineFactory() {
return (WorkflowEngineFactory) getBean(WORKFLOW_ENGINE_FACTORY);
}
public static WorkflowDocumentExceptionRoutingService getExceptionRoutingService() {
return (WorkflowDocumentExceptionRoutingService) getBean(EXCEPTION_ROUTING_SERVICE);
}
public static ActionListEmailService getActionListEmailService() {
return (ActionListEmailService) getBean(KEWServiceLocator.ACTION_LIST_EMAIL_SERVICE);
}
public static EmailContentService getEmailContentService() {
return (EmailContentService) getBean(KEWServiceLocator.EMAIL_CONTENT_SERVICE);
}
public static NotificationService getNotificationService() {
return (NotificationService) getBean(KEWServiceLocator.NOTIFICATION_SERVICE);
}
public static TransactionManager getTransactionManager() {
return (TransactionManager) getBean(JTA_TRANSACTION_MANAGER);
}
public static UserTransaction getUserTransaction() {
return (UserTransaction) getBean(USER_TRANSACTION);
}
public static NoteService getNoteService() {
return (NoteService) getBean(NOTE_SERVICE);
}
public static ActionRegistry getActionRegistry() {
return (ActionRegistry) getBean(ACTION_REGISTRY);
}
public static BranchService getBranchService() {
return (BranchService) getBean(BRANCH_SERVICE);
}
public static DocumentSearchService getDocumentSearchService() {
return (DocumentSearchService) getBean(DOCUMENT_SEARCH_SERVICE);
}
public static ExtractService getExtractService() {
return (ExtractService) getBean(EXTRACT_SERVICE);
}
public static IdentityHelperService getIdentityHelperService() {
return (IdentityHelperService) getBean(IDENTITY_HELPER_SERVICE);
}
public static DocumentLinkService getDocumentLinkService(){
return (DocumentLinkService) getBean(DOCUMENT_LINK_SERVICE);
}
/**
* For the following methods, we go directly to the SpringLoader because we do NOT want them to
* be wrapped in any sort of proxy.
*/
public static DataSource getDataSource() {
return (DataSource) getBean(DATASOURCE);
}
public static PlatformTransactionManager getPlatformTransactionManager() {
return (PlatformTransactionManager) getBean(TRANSACTION_MANAGER);
}
public static WorkflowDocumentPrototype getWorkflowDocumentPrototype() {
return getBean(WORKFLOW_DOCUMENT_PROTOTYPE);
}
public static DocumentSearchCustomizationMediator getDocumentSearchCustomizationMediator() {
return getBean(DOCUMENT_SEARCH_CUSTOMIZATION_MEDIATOR);
}
public static WorkflowRuleAttributeMediator getWorkflowRuleAttributeMediator() {
return getBean(WORKFLOW_RULE_ATTRIBUTE_MEDIATOR);
}
public static RuleValidationAttributeResolver getRuleValidationAttributeResolver() {
return getBean(RULE_VALIDATION_ATTRIBUTE_RESOLVER);
}
public static CacheManager getLocalCacheManager() {
return (CacheManager) getService(LOCAL_CACHE_MANAGER);
}
}
| bhutchinson/rice | rice-middleware/impl/src/main/java/org/kuali/rice/kew/service/KEWServiceLocator.java | Java | apache-2.0 | 16,222 |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.msf4j.internal.router;
import org.wso2.carbon.messaging.CarbonMessage;
import org.wso2.msf4j.util.HttpUtil;
import javax.ws.rs.core.Response;
/**
* Creating Http Response for Exception messages.
*/
public class HandlerException extends Exception {
private final Response.Status failureStatus;
private final String message;
public HandlerException(Response.Status failureStatus, String message) {
super(message);
this.failureStatus = failureStatus;
this.message = message;
}
public HandlerException(Response.Status failureStatus, String message, Throwable cause) {
super(message, cause);
this.failureStatus = failureStatus;
this.message = message;
}
public CarbonMessage getFailureResponse() {
return HttpUtil.createTextResponse(failureStatus.getStatusCode(), message);
}
public Response.Status getFailureStatus() {
return failureStatus;
}
}
| callkalpa/product-mss | core/src/main/java/org/wso2/msf4j/internal/router/HandlerException.java | Java | apache-2.0 | 1,610 |
/*
* 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.model.language;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.camel.spi.Metadata;
/**
* Evaluate a JsonPath expression against a JSON message body.
*/
@Metadata(firstVersion = "2.13.0", label = "language,json", title = "JsonPath")
@XmlRootElement(name = "jsonpath")
@XmlAccessorType(XmlAccessType.FIELD)
public class JsonPathExpression extends ExpressionDefinition {
@XmlAttribute(name = "resultType")
private String resultTypeName;
@XmlTransient
private Class<?> resultType;
@XmlAttribute
@Metadata(defaultValue = "false", javaType = "java.lang.Boolean")
private String suppressExceptions;
@XmlAttribute
@Metadata(defaultValue = "true", javaType = "java.lang.Boolean")
private String allowSimple;
@XmlAttribute
@Metadata(defaultValue = "true", javaType = "java.lang.Boolean")
private String allowEasyPredicate;
@XmlAttribute
@Metadata(defaultValue = "false", javaType = "java.lang.Boolean")
private String writeAsString;
@XmlAttribute
private String headerName;
@XmlAttribute
@Metadata(enums = "DEFAULT_PATH_LEAF_TO_NULL,ALWAYS_RETURN_LIST,AS_PATH_LIST,SUPPRESS_EXCEPTIONS,REQUIRE_PROPERTIES")
private String option;
public JsonPathExpression() {
}
public JsonPathExpression(String expression) {
super(expression);
}
public String getResultTypeName() {
return resultTypeName;
}
/**
* Sets the class name of the result type (type from output)
*/
public void setResultTypeName(String resultTypeName) {
this.resultTypeName = resultTypeName;
}
public Class<?> getResultType() {
return resultType;
}
/**
* Sets the class of the result type (type from output)
*/
public void setResultType(Class<?> resultType) {
this.resultType = resultType;
}
public String getSuppressExceptions() {
return suppressExceptions;
}
public String getAllowSimple() {
return allowSimple;
}
/**
* Whether to allow in inlined simple exceptions in the JsonPath expression
*/
public void setAllowSimple(String allowSimple) {
this.allowSimple = allowSimple;
}
public String getAllowEasyPredicate() {
return allowEasyPredicate;
}
/**
* Whether to allow using the easy predicate parser to pre-parse predicates.
*/
public void setAllowEasyPredicate(String allowEasyPredicate) {
this.allowEasyPredicate = allowEasyPredicate;
}
/**
* Whether to suppress exceptions such as PathNotFoundException.
*/
public void setSuppressExceptions(String suppressExceptions) {
this.suppressExceptions = suppressExceptions;
}
public String getWriteAsString() {
return writeAsString;
}
/**
* Whether to write the output of each row/element as a JSON String value instead of a Map/POJO value.
*/
public void setWriteAsString(String writeAsString) {
this.writeAsString = writeAsString;
}
public String getHeaderName() {
return headerName;
}
/**
* Name of header to use as input, instead of the message body
*/
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
public String getOption() {
return option;
}
/**
* To configure additional options on json path. Multiple values can be separated by comma.
*/
public void setOption(String option) {
this.option = option;
}
@Override
public String getLanguage() {
return "jsonpath";
}
}
| nikhilvibhav/camel | core/camel-core-model/src/main/java/org/apache/camel/model/language/JsonPathExpression.java | Java | apache-2.0 | 4,665 |
/*=========================================================================
* Copyright (c) 2010-2014 Pivotal Software, Inc. All Rights Reserved.
* This product is protected by U.S. and international copyright
* and intellectual property laws. Pivotal products are covered by
* one or more patents listed at http://www.pivotal.io/patents.
*=========================================================================
*/
package com.gemstone.gemfire.internal.cache;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import com.gemstone.gemfire.internal.cache.lru.EnableLRU;
import com.gemstone.gemfire.internal.cache.lru.LRUClockNode;
import com.gemstone.gemfire.internal.cache.lru.NewLRUClockHand;
import com.gemstone.gemfire.internal.offheap.OffHeapRegionEntryHelper;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.offheap.annotations.Retained;
import com.gemstone.gemfire.internal.offheap.annotations.Unretained;
import com.gemstone.gemfire.internal.util.concurrent.CustomEntryConcurrentHashMap.HashEntry;
// macros whose definition changes this class:
// disk: DISK
// lru: LRU
// stats: STATS
// versioned: VERSIONED
// offheap: OFFHEAP
// One of the following key macros must be defined:
// key object: KEY_OBJECT
// key int: KEY_INT
// key long: KEY_LONG
// key uuid: KEY_UUID
// key string1: KEY_STRING1
// key string2: KEY_STRING2
/**
* Do not modify this class. It was generated.
* Instead modify LeafRegionEntry.cpp and then run
* bin/generateRegionEntryClasses.sh from the directory
* that contains your build.xml.
*/
public class VMThinLRURegionEntryOffHeapStringKey1 extends VMThinLRURegionEntryOffHeap {
public VMThinLRURegionEntryOffHeapStringKey1 (RegionEntryContext context, String key,
@Retained
Object value
, boolean byteEncode
) {
super(context,
value
);
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// caller has already confirmed that key.length <= MAX_INLINE_STRING_KEY
long tmpBits1 = 0L;
if (byteEncode) {
for (int i=key.length()-1; i >= 0; i--) {
// Note: we know each byte is <= 0x7f so the "& 0xff" is not needed. But I added it in to keep findbugs happy.
tmpBits1 |= (byte)key.charAt(i) & 0xff;
tmpBits1 <<= 8;
}
tmpBits1 |= 1<<6;
} else {
for (int i=key.length()-1; i >= 0; i--) {
tmpBits1 |= key.charAt(i);
tmpBits1 <<= 16;
}
}
tmpBits1 |= key.length();
this.bits1 = tmpBits1;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// common code
protected int hash;
private HashEntry<Object, Object> next;
@SuppressWarnings("unused")
private volatile long lastModified;
private static final AtomicLongFieldUpdater<VMThinLRURegionEntryOffHeapStringKey1> lastModifiedUpdater
= AtomicLongFieldUpdater.newUpdater(VMThinLRURegionEntryOffHeapStringKey1.class, "lastModified");
/**
* All access done using ohAddrUpdater so it is used even though the compiler can not tell it is.
*/
@SuppressWarnings("unused")
@Retained @Released private volatile long ohAddress;
/**
* I needed to add this because I wanted clear to call setValue which normally can only be called while the re is synced.
* But if I sync in that code it causes a lock ordering deadlock with the disk regions because they also get a rw lock in clear.
* Some hardware platforms do not support CAS on a long. If gemfire is run on one of those the AtomicLongFieldUpdater does a sync
* on the re and we will once again be deadlocked.
* I don't know if we support any of the hardware platforms that do not have a 64bit CAS. If we do then we can expect deadlocks
* on disk regions.
*/
private final static AtomicLongFieldUpdater<VMThinLRURegionEntryOffHeapStringKey1> ohAddrUpdater = AtomicLongFieldUpdater.newUpdater(VMThinLRURegionEntryOffHeapStringKey1.class, "ohAddress");
@Override
public Token getValueAsToken() {
return OffHeapRegionEntryHelper.getValueAsToken(this);
}
@Override
protected Object getValueField() {
return OffHeapRegionEntryHelper._getValue(this);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
@Override
@Unretained
protected void setValueField(@Unretained Object v) {
OffHeapRegionEntryHelper.setValue(this, v);
}
@Override
@Retained
public Object _getValueRetain(RegionEntryContext context, boolean decompress) {
return OffHeapRegionEntryHelper._getValueRetain(this, decompress, context);
}
@Override
public long getAddress() {
return ohAddrUpdater.get(this);
}
@Override
public boolean setAddress(long expectedAddr, long newAddr) {
return ohAddrUpdater.compareAndSet(this, expectedAddr, newAddr);
}
@Override
@Released
public void release() {
OffHeapRegionEntryHelper.releaseEntry(this);
}
@Override
public void returnToPool() {
// Deadcoded for now; never was working
// if (this instanceof VMThinRegionEntryLongKey) {
// factory.returnToPool((VMThinRegionEntryLongKey)this);
// }
}
protected long getlastModifiedField() {
return lastModifiedUpdater.get(this);
}
protected boolean compareAndSetLastModifiedField(long expectedValue, long newValue) {
return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
}
/**
* @see HashEntry#getEntryHash()
*/
public final int getEntryHash() {
return this.hash;
}
protected void setEntryHash(int v) {
this.hash = v;
}
/**
* @see HashEntry#getNextEntry()
*/
public final HashEntry<Object, Object> getNextEntry() {
return this.next;
}
/**
* @see HashEntry#setNextEntry
*/
public final void setNextEntry(final HashEntry<Object, Object> n) {
this.next = n;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// lru code
@Override
public void setDelayedDiskId(LocalRegion r) {
// nothing needed for LRUs with no disk
}
public final synchronized int updateEntrySize(EnableLRU capacityController) {
return updateEntrySize(capacityController, _getValue()); // OFHEAP: _getValue ok w/o incing refcount because we are synced and only getting the size
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
public final synchronized int updateEntrySize(EnableLRU capacityController,
Object value) {
int oldSize = getEntrySize();
int newSize = capacityController.entrySize( getKeyForSizing(), value);
setEntrySize(newSize);
int delta = newSize - oldSize;
// if ( debug ) log( "updateEntrySize key=" + getKey()
// + (_getValue() == Token.INVALID ? " invalid" :
// (_getValue() == Token.LOCAL_INVALID ? "local_invalid" :
// (_getValue()==null ? " evicted" : " valid")))
// + " oldSize=" + oldSize
// + " newSize=" + this.size );
return delta;
}
public final boolean testRecentlyUsed() {
return areAnyBitsSet(RECENTLY_USED);
}
@Override
public final void setRecentlyUsed() {
setBits(RECENTLY_USED);
}
public final void unsetRecentlyUsed() {
clearBits(~RECENTLY_USED);
}
public final boolean testEvicted() {
return areAnyBitsSet(EVICTED);
}
public final void setEvicted() {
setBits(EVICTED);
}
public final void unsetEvicted() {
clearBits(~EVICTED);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
private LRUClockNode nextLRU;
private LRUClockNode prevLRU;
private int size;
public final void setNextLRUNode( LRUClockNode next ) {
this.nextLRU = next;
}
public final LRUClockNode nextLRUNode() {
return this.nextLRU;
}
public final void setPrevLRUNode( LRUClockNode prev ) {
this.prevLRU = prev;
}
public final LRUClockNode prevLRUNode() {
return this.prevLRU;
}
public final int getEntrySize() {
return this.size;
}
protected final void setEntrySize(int size) {
this.size = size;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
//@Override
//public StringBuilder appendFieldsToString(final StringBuilder sb) {
// StringBuilder result = super.appendFieldsToString(sb);
// result.append("; prev=").append(this.prevLRU==null?"null":"not null");
// result.append("; next=").append(this.nextLRU==null?"null":"not null");
// return result;
//}
@Override
public Object getKeyForSizing() {
// inline keys always report null for sizing since the size comes from the entry size
return null;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// key code
private final long bits1;
private int getKeyLength() {
return (int) (this.bits1 & 0x003fL);
}
private int getEncoding() {
// 0 means encoded as char
// 1 means encoded as bytes that are all <= 0x7f;
return (int) (this.bits1 >> 6) & 0x03;
}
@Override
public final Object getKey() {
int keylen = getKeyLength();
char[] chars = new char[keylen];
long tmpBits1 = this.bits1;
if (getEncoding() == 1) {
for (int i=0; i < keylen; i++) {
tmpBits1 >>= 8;
chars[i] = (char) (tmpBits1 & 0x00ff);
}
} else {
for (int i=0; i < keylen; i++) {
tmpBits1 >>= 16;
chars[i] = (char) (tmpBits1 & 0x00FFff);
}
}
return new String(chars);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
@Override
public boolean isKeyEqual(Object k) {
if (k instanceof String) {
String str = (String)k;
int keylen = getKeyLength();
if (str.length() == keylen) {
long tmpBits1 = this.bits1;
if (getEncoding() == 1) {
for (int i=0; i < keylen; i++) {
tmpBits1 >>= 8;
char c = (char) (tmpBits1 & 0x00ff);
if (str.charAt(i) != c) {
return false;
}
}
} else {
for (int i=0; i < keylen; i++) {
tmpBits1 >>= 16;
char c = (char) (tmpBits1 & 0x00FFff);
if (str.charAt(i) != c) {
return false;
}
}
}
return true;
}
}
return false;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
}
| ysung-pivotal/incubator-geode | gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/VMThinLRURegionEntryOffHeapStringKey1.java | Java | apache-2.0 | 10,554 |
/**
* Copyright 2007-2016, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.gateway.transport.wsn.logging;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.kaazing.test.util.ITUtil.timeoutRule;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.kaazing.gateway.server.test.GatewayRule;
import org.kaazing.gateway.server.test.config.GatewayConfiguration;
import org.kaazing.gateway.server.test.config.builder.GatewayConfigurationBuilder;
import org.kaazing.k3po.junit.annotation.Specification;
import org.kaazing.k3po.junit.rules.K3poRule;
import org.kaazing.test.util.LoggingRule;
import org.kaazing.test.util.MethodExecutionTrace;
/**
* RFC-6455, section 5.2 "Base Framing Protocol"
*/
public class WsnAcceptorInfoLoggingIT {
private static final String FILTER_PATTERN = ".*\\[.*#.*].*";
private final K3poRule k3po = new K3poRule().setScriptRoot("org/kaazing/specification");
private LoggingRule checkLogMessageRule = new LoggingRule().filterPattern(FILTER_PATTERN);
private GatewayRule gateway = new GatewayRule() {
{
// @formatter:off
GatewayConfiguration configuration =
new GatewayConfigurationBuilder()
.service()
.accept("ws://localhost:8080/echo")
.type("echo")
.crossOrigin()
.allowOrigin("http://localhost:8001")
.done()
.done()
.done();
// @formatter:on
init(configuration);
}
};
Properties log4j;
{ log4j = new Properties();
log4j.setProperty("log4j.rootLogger", "INFO, A1");
log4j.setProperty("log4j.appender.A1", "org.kaazing.test.util.MemoryAppender");
log4j.setProperty("log4j.appender.A1.layout", "org.apache.log4j.PatternLayout");
log4j.setProperty("log4j.appender.A1.layout.ConversionPattern", "%-4r %c [%t] %-5p %c{1} %x - %m%n");
}
private TestRule trace = new MethodExecutionTrace(log4j); // info level logging
@Rule
// Special ordering: gateway around k3po allows gateway to detect k3po closing any still open connections
// to make sure we get the log messages for the abrupt close
public final TestRule chain = RuleChain.outerRule(trace).around(gateway).around(checkLogMessageRule)
.around(k3po).around(timeoutRule(5, SECONDS));
@Test
@Specification({
"ws/extensibility/client.send.text.frame.with.rsv.1/handshake.request.and.frame"
})
public void shouldLogProtocolException() throws Exception {
checkLogMessageRule.expectPatterns(Arrays.asList(
"tcp#.*OPENED",
"tcp#.*CLOSED",
"http#.*OPENED",
"http#.*CLOSED",
"wsn#.*OPENED",
"tcp#.*EXCEPTION.*Protocol.*Exception",
"wsn#.*EXCEPTION.*IOException.*caused by.*Protocol.*Exception",
"wsn#.*CLOSED"
));
k3po.finish();
}
@Test
@Specification({
"ws/framing/echo.binary.payload.length.125/handshake.request.and.frame"
})
public void shouldLogOpenWriteReceivedAndAbruptClose() throws Exception {
checkLogMessageRule.expectPatterns(Arrays.asList(
"tcp#.* [^/]*:\\d*] OPENED", // example: [tcp#34 192.168.4.126:49966] OPENED: (...
"tcp#.* [^/]*:\\d*] CLOSED",
"http#.* [^/]*:\\d*] OPENED",
"http#.* [^/]*:\\d*] CLOSED",
"wsn#.* [^/]*:\\d*] OPENED",
"wsn#.* [^/]*:\\d*] EXCEPTION.*IOException",
"wsn#.* [^/]*:\\d*] CLOSED"
));
k3po.finish();
}
@Test
@Specification({
"ws/closing/client.send.empty.close.frame/handshake.request.and.frame"
})
public void shouldLogOpenAndCleanClose() throws Exception {
k3po.finish();
checkLogMessageRule.expectPatterns(Arrays.asList(
"tcp#.* [^/]*:\\d*] OPENED",
"tcp#.* [^/]*:\\d*] CLOSED",
"http#.* [^/]*:\\d*] OPENED",
"http#.* [^/]*:\\d*] CLOSED",
"wsn#.* [^/]*:\\d*] OPENED",
"wsn#.* [^/]*:\\d*] CLOSED"
));
checkLogMessageRule.forbidPatterns(Collections.singletonList("#.*EXCEPTION"));
}
} | a-zuckut/gateway | transport/wsn/src/test/java/org/kaazing/gateway/transport/wsn/logging/WsnAcceptorInfoLoggingIT.java | Java | apache-2.0 | 5,171 |
/*
* IzPack - Copyright 2001-2012 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2012 Tim Anderson
*
* 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.izforge.izpack.installer.console;
import com.izforge.izpack.api.config.Config;
import com.izforge.izpack.api.config.Options;
import com.izforge.izpack.api.data.Info;
import com.izforge.izpack.api.data.InstallData;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.logging.Logger;
/**
* Action to generate properties for each panel.
*
* @author Tim Anderson
*/
class GeneratePropertiesAction extends ConsoleAction
{
private static final Logger logger = Logger.getLogger(GeneratePropertiesAction.class.getName());
/**
* The options files to write properties to.
*/
private final Options options;
private final String path;
/**
* Constructs a <tt>GeneratePropertiesAction</tt>.
*
* @param installData the installation data
* @param path the path to write properties to
* @throws FileNotFoundException if the file exists but is a directory rather than a regular file, does not exist
* but cannot be created, or cannot be opened for any other reason
*/
public GeneratePropertiesAction(InstallData installData, String path) throws FileNotFoundException
{
super(installData);
Info info = installData.getInfo();
this.options = new Options();
Config config = this.options.getConfig();
config.setEmptyLines(true);
config.setHeaderComment(true);
config.setFileEncoding(Charset.forName("ISO-8859-1"));
this.options.setHeaderComment(Arrays.asList(info.getAppName() + " " + info.getAppVersion()));
this.path = path;
}
/**
* Determines if this is an installation action.
*
* @return <tt>false</tt>
*/
@Override
public boolean isInstall()
{
return false;
}
/**
* Runs the action for the panel.
*
* @param panel the panel
* @return {@code true} if the action was successful, otherwise {@code false}
*/
@Override
public boolean run(ConsolePanelView panel)
{
return panel.getView().generateOptions(getInstallData(), options);
}
/**
* Invoked after the action has been successfully run for each panel.
*
* @return {@code true} if the operation succeeds; {@code false} if it fails
*/
@Override
public boolean complete()
{
try
{
options.store(new File(path));
}
catch (IOException e)
{
logger.severe("Error saving the option file.");
return false;
}
return true;
}
}
| akuhtz/izpack | izpack-installer/src/main/java/com/izforge/izpack/installer/console/GeneratePropertiesAction.java | Java | apache-2.0 | 3,426 |
/*
* 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.smpp;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.jsmpp.bean.CancelSm;
import org.jsmpp.bean.NumberingPlanIndicator;
import org.jsmpp.bean.TypeOfNumber;
import org.jsmpp.session.SMPPSession;
public class SmppCancelSmCommand extends AbstractSmppCommand {
public SmppCancelSmCommand(SMPPSession session, SmppConfiguration config) {
super(session, config);
}
@Override
public void execute(Exchange exchange) throws SmppException {
CancelSm cancelSm = createCancelSm(exchange);
if (log.isDebugEnabled()) {
log.debug("Canceling a short message for exchange id '{}' and message id '{}'",
exchange.getExchangeId(), cancelSm.getMessageId());
}
try {
session.cancelShortMessage(
cancelSm.getServiceType(),
cancelSm.getMessageId(),
TypeOfNumber.valueOf(cancelSm.getSourceAddrTon()),
NumberingPlanIndicator.valueOf(cancelSm.getSourceAddrNpi()),
cancelSm.getSourceAddr(),
TypeOfNumber.valueOf(cancelSm.getDestAddrTon()),
NumberingPlanIndicator.valueOf(cancelSm.getDestAddrNpi()),
cancelSm.getDestinationAddress());
} catch (Exception e) {
throw new SmppException(e);
}
if (log.isDebugEnabled()) {
log.debug("Cancel a short message for exchange id '{}' and message id '{}'",
exchange.getExchangeId(), cancelSm.getMessageId());
}
Message message = getResponseMessage(exchange);
message.setHeader(SmppConstants.ID, cancelSm.getMessageId());
}
protected CancelSm createCancelSm(Exchange exchange) {
Message in = exchange.getIn();
CancelSm cancelSm = new CancelSm();
if (in.getHeaders().containsKey(SmppConstants.ID)) {
cancelSm.setMessageId(in.getHeader(SmppConstants.ID, String.class));
}
if (in.getHeaders().containsKey(SmppConstants.SOURCE_ADDR)) {
cancelSm.setSourceAddr(in.getHeader(SmppConstants.SOURCE_ADDR, String.class));
} else {
cancelSm.setSourceAddr(config.getSourceAddr());
}
if (in.getHeaders().containsKey(SmppConstants.SOURCE_ADDR_TON)) {
cancelSm.setSourceAddrTon(in.getHeader(SmppConstants.SOURCE_ADDR_TON, Byte.class));
} else {
cancelSm.setSourceAddrTon(config.getSourceAddrTon());
}
if (in.getHeaders().containsKey(SmppConstants.SOURCE_ADDR_NPI)) {
cancelSm.setSourceAddrNpi(in.getHeader(SmppConstants.SOURCE_ADDR_NPI, Byte.class));
} else {
cancelSm.setSourceAddrNpi(config.getSourceAddrNpi());
}
if (in.getHeaders().containsKey(SmppConstants.DEST_ADDR)) {
cancelSm.setDestinationAddress(in.getHeader(SmppConstants.DEST_ADDR, String.class));
} else {
cancelSm.setDestinationAddress(config.getDestAddr());
}
if (in.getHeaders().containsKey(SmppConstants.DEST_ADDR_TON)) {
cancelSm.setDestAddrTon(in.getHeader(SmppConstants.DEST_ADDR_TON, Byte.class));
} else {
cancelSm.setDestAddrTon(config.getDestAddrTon());
}
if (in.getHeaders().containsKey(SmppConstants.DEST_ADDR_NPI)) {
cancelSm.setDestAddrNpi(in.getHeader(SmppConstants.DEST_ADDR_NPI, Byte.class));
} else {
cancelSm.setDestAddrNpi(config.getDestAddrNpi());
}
if (in.getHeaders().containsKey(SmppConstants.SERVICE_TYPE)) {
cancelSm.setServiceType(in.getHeader(SmppConstants.SERVICE_TYPE, String.class));
} else {
cancelSm.setServiceType(config.getServiceType());
}
return cancelSm;
}
} | davidkarlsen/camel | components/camel-smpp/src/main/java/org/apache/camel/component/smpp/SmppCancelSmCommand.java | Java | apache-2.0 | 4,691 |
package org.mifos.customers.business.service;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mifos.customers.persistence.CustomerPersistence;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.exceptions.ServiceException;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class CustomerBusinessServiceTest {
private CustomerPersistence customerPersistence = mock(CustomerPersistence.class);
private CustomerBusinessService service = new CustomerBusinessService(customerPersistence);
@Test
public void testInvalidConnectionGetCustomer() throws PersistenceException {
Integer customerId = new Integer(1);
try {
when(customerPersistence.getCustomer(customerId)).thenThrow(new PersistenceException("some exception"));
service.getCustomer(customerId);
junit.framework.Assert.fail("should fail because of invalid session");
} catch (ServiceException e) {
}
}
@Test
public void testInvalidConnectionFindBySystemId() throws PersistenceException {
try {
String globalNum = "globalNum";
when(customerPersistence.findBySystemId(globalNum)).thenThrow(new PersistenceException("some exception"));
service.findBySystemId(globalNum);
junit.framework.Assert.fail("should fail because of invalid session");
} catch (ServiceException e) {
}
}
}
| vorburger/mifos-head | application/src/test/java/org/mifos/customers/business/service/CustomerBusinessServiceTest.java | Java | apache-2.0 | 1,580 |
/*
* 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.
*/
/* $Id$ */
package org.apache.fop.fonts.substitute;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Encapsulates a range of font weight values
*/
public class FontWeightRange {
/** logging instance */
protected static final Log log = LogFactory.getLog("org.apache.fop.render.fonts");
/**
* Returns an <code>FontWeightRange</code> object holding the
* range values of the specified <code>String</code>.
*
* @param weightRangeString the value range string
* @return an <code>FontWeightRange</code> object holding the value ranges
*/
public static FontWeightRange valueOf(String weightRangeString) {
StringTokenizer rangeToken = new StringTokenizer(weightRangeString, "..");
FontWeightRange weightRange = null;
if (rangeToken.countTokens() == 2) {
String weightString = rangeToken.nextToken().trim();
try {
int start = Integer.parseInt(weightString);
if (start % 100 != 0) {
log.error("font-weight start range is not a multiple of 100");
}
int end = Integer.parseInt(rangeToken.nextToken());
if (end % 100 != 0) {
log.error("font-weight end range is not a multiple of 100");
}
if (start <= end) {
weightRange = new FontWeightRange(start, end);
} else {
log.error("font-weight start range is greater than end range");
}
} catch (NumberFormatException e) {
log.error("invalid font-weight value " + weightString);
}
}
return weightRange;
}
/** the start range */
private int start;
/** the end range */
private int end;
/**
* Main constructor
* @param start the start value range
* @param end the end value range
*/
public FontWeightRange(int start, int end) {
this.start = start;
this.end = end;
}
/**
* Returns true if the given integer value is within this integer range
* @param value the integer value
* @return true if the given integer value is within this integer range
*/
public boolean isWithinRange(int value) {
return (value >= start && value <= end);
}
/**
* {@inheritDoc}
*/
public String toString() {
return start + ".." + end;
}
/**
* @return an integer array containing the weight ranges
*/
public int[] toArray() {
int cnt = 0;
for (int i = start; i <= end; i += 100) {
cnt++;
}
int[] range = new int[cnt];
for (int i = 0; i < cnt; i++) {
range[i] = start + (i * 100);
}
return range;
}
}
| Distrotech/fop | src/java/org/apache/fop/fonts/substitute/FontWeightRange.java | Java | apache-2.0 | 3,710 |
/**
* Copyright (C) 2006-2009 Dustin Sallings
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
* IN THE SOFTWARE.
*/
package net.spy.memcached.protocol.ascii;
import java.nio.ByteBuffer;
import net.spy.memcached.ops.FlushOperation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationState;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.StatusCode;
/**
* Memcached flush_all operation.
*/
final class FlushOperationImpl extends OperationImpl implements FlushOperation {
private static final byte[] FLUSH = "flush_all\r\n".getBytes();
private static final OperationStatus OK = new OperationStatus(true, "OK",
StatusCode.SUCCESS);
private final int delay;
public FlushOperationImpl(int d, OperationCallback cb) {
super(cb);
delay = d;
}
@Override
public void handleLine(String line) {
getLogger().debug("Flush completed successfully");
getCallback().receivedStatus(matchStatus(line, OK));
transitionState(OperationState.COMPLETE);
}
@Override
public void initialize() {
ByteBuffer b = null;
if (delay == -1) {
b = ByteBuffer.wrap(FLUSH);
} else {
b = ByteBuffer.allocate(32);
b.put(("flush_all " + delay + "\r\n").getBytes());
b.flip();
}
setBuffer(b);
}
@Override
public String toString() {
return "Cmd: flush_all Delay: " + delay;
}
}
| douxiaozhao/java-memcached-client | src/main/java/net/spy/memcached/protocol/ascii/FlushOperationImpl.java | Java | mit | 2,419 |
/**
* $Id$
*
* Author:: Francis Cianfrocca (gmail: blackhedd)
* Homepage:: http://rubyeventmachine.com
* Date:: 15 Jul 2007
*
* See EventMachine and EventMachine::Connection for documentation and
* usage examples.
*
*
*----------------------------------------------------------------------------
*
* Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
* Gmail: blackhedd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of either: 1) the GNU General Public License
* as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version; or 2) Ruby's License.
*
* See the file COPYING for complete licensing information.
*
*---------------------------------------------------------------------------
*
*
*/
package com.rubyeventmachine.tests;
import com.rubyeventmachine.*;
import com.rubyeventmachine.application.*;
import java.net.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Assert;
public class TestServers {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testBadServerAddress() {
final Application a = new Application();
a.run (new Runnable() {
public void run() {
try {
a.startServer(new InetSocketAddress ("100.100.100.100", 100), new DefaultConnectionFactory());
Assert.fail ("was supposed to throw a reactor exception");
} catch (EmReactorException e) {}
a.stop();
}
});
}
}
| mattgraham/play-graham | vendor/gems/ruby/1.8/gems/eventmachine-0.12.10/java/src/com/rubyeventmachine/tests/TestServers.java | Java | mit | 1,809 |
package convert;
import java.util.Currency;
import org.eclipse.core.databinding.conversion.IConverter;
/**
* @author lobas_av
*
*/
public class ConverterCurrencyToSymbolString implements IConverter {
////////////////////////////////////////////////////////////////////////////
//
// IConverter
//
////////////////////////////////////////////////////////////////////////////
public Object getFromType() {
return Currency.class;
}
public Object getToType() {
return String.class;
}
public Object convert(Object fromObject) {
if (fromObject == null) {
return "???";
}
Currency currency = (Currency) fromObject;
return currency.getSymbol();
}
} | NounVannakGitHub/Java-Tutorial-Vollegen | de.vogella.databinding.windowbuilder.example/src/convert/ConverterCurrencyToSymbolString.java | Java | epl-1.0 | 701 |
/**
* Copyright (c) 2014,2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.binding.astro.internal.model;
/**
* Holds the sign of the zodiac.
*
* @author Gerhard Riegler - Initial contribution
*/
public class Zodiac {
private ZodiacSign sign;
public Zodiac(ZodiacSign sign) {
this.sign = sign;
}
/**
* Returns the sign of the zodiac.
*/
public ZodiacSign getSign() {
return sign;
}
}
| Snickermicker/smarthome | extensions/binding/org.eclipse.smarthome.binding.astro/src/main/java/org/eclipse/smarthome/binding/astro/internal/model/Zodiac.java | Java | epl-1.0 | 810 |
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
*
* @summary converted from VM Testbase vm/mlvm/indy/func/jvmti/mergeCP_indy2none_b.
* VM Testbase keywords: [feature_mlvm, nonconcurrent, jvmti, redefine, noJFR]
* VM Testbase readme:
* DESCRIPTION
* Test calls a boostrap and a target methods via InvokeDynamic call, monitoring that
* a method in the debuggee class (Dummy0.redefineNow()) is called (monitoring is done
* via MethodEntry event). At this moment, Dummy0 class is redefined using RedefineClasses
* function to another Dummy0 class and PopFrame function is called to reenter the method.
* To verify logic of merging constant pools with regard to JSR 292, the original class has
* a invokedynamic call and the new Dummy0 does not have invokedynamic at all.
* The test verifies that when class is redefined in a target method (at that moment,
* the call site is linked) and frame is popped, the new target method is executed and
* the site is relinked.
*
* @library /vmTestbase
* /test/lib
*
* @comment build dummy class
* @build vm.mlvm.indy.func.jvmti.mergeCP_indy2none_b.INDIFY_Dummy0
*
* @comment compile newclass to bin/newclass
* @run driver nsk.share.ExtraClassesBuilder newclass
* @run driver vm.mlvm.share.IndifiedClassesBuilder bin/newclass
*
* @run driver jdk.test.lib.FileInstaller . .
*
* @comment build test class and indify classes
* @build vm.mlvm.indy.func.jvmti.share.IndyRedefineTest
* @run driver vm.mlvm.share.IndifiedClassesBuilder
*
* @run main/othervm/native
* -agentlib:IndyRedefineClass=verbose=~pathToNewByteCode=./bin/newclass
* vm.mlvm.indy.func.jvmti.share.IndyRedefineTest
* -dummyClassName=vm.mlvm.indy.func.jvmti.mergeCP_indy2none_b.INDIFY_Dummy0
*/
| md-5/jdk10 | test/hotspot/jtreg/vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2none_b/TestDescription.java | Java | gpl-2.0 | 2,806 |
/*
* Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.media.sound;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Objects;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.spi.AudioFileWriter;
/**
* Floating-point encoded (format 3) WAVE file writer.
*
* @author Karl Helgason
*/
public final class WaveFloatFileWriter extends AudioFileWriter {
@Override
public Type[] getAudioFileTypes() {
return new Type[]{Type.WAVE};
}
@Override
public Type[] getAudioFileTypes(AudioInputStream stream) {
if (!stream.getFormat().getEncoding().equals(Encoding.PCM_FLOAT))
return new Type[0];
return new Type[] { Type.WAVE };
}
private void checkFormat(AudioFileFormat.Type type, AudioInputStream stream) {
if (!Type.WAVE.equals(type))
throw new IllegalArgumentException("File type " + type
+ " not supported.");
if (!stream.getFormat().getEncoding().equals(Encoding.PCM_FLOAT))
throw new IllegalArgumentException("File format "
+ stream.getFormat() + " not supported.");
}
public void write(AudioInputStream stream, RIFFWriter writer)
throws IOException {
try (final RIFFWriter fmt_chunk = writer.writeChunk("fmt ")) {
AudioFormat format = stream.getFormat();
fmt_chunk.writeUnsignedShort(3); // WAVE_FORMAT_IEEE_FLOAT
fmt_chunk.writeUnsignedShort(format.getChannels());
fmt_chunk.writeUnsignedInt((int) format.getSampleRate());
fmt_chunk.writeUnsignedInt(((int) format.getFrameRate())
* format.getFrameSize());
fmt_chunk.writeUnsignedShort(format.getFrameSize());
fmt_chunk.writeUnsignedShort(format.getSampleSizeInBits());
}
try (RIFFWriter data_chunk = writer.writeChunk("data")) {
byte[] buff = new byte[1024];
int len;
while ((len = stream.read(buff, 0, buff.length)) != -1) {
data_chunk.write(buff, 0, len);
}
}
}
private static final class NoCloseOutputStream extends OutputStream {
final OutputStream out;
NoCloseOutputStream(OutputStream out) {
this.out = out;
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
out.write(b);
}
}
private AudioInputStream toLittleEndian(AudioInputStream ais) {
AudioFormat format = ais.getFormat();
AudioFormat targetFormat = new AudioFormat(format.getEncoding(), format
.getSampleRate(), format.getSampleSizeInBits(), format
.getChannels(), format.getFrameSize(), format.getFrameRate(),
false);
return AudioSystem.getAudioInputStream(targetFormat, ais);
}
@Override
public int write(AudioInputStream stream, Type fileType, OutputStream out)
throws IOException {
Objects.requireNonNull(stream);
Objects.requireNonNull(fileType);
Objects.requireNonNull(out);
checkFormat(fileType, stream);
if (stream.getFormat().isBigEndian())
stream = toLittleEndian(stream);
try (final RIFFWriter writer = new RIFFWriter(
new NoCloseOutputStream(out), "WAVE")) {
write(stream, writer);
return (int) writer.getFilePointer();
}
}
@Override
public int write(AudioInputStream stream, Type fileType, File out)
throws IOException {
Objects.requireNonNull(stream);
Objects.requireNonNull(fileType);
Objects.requireNonNull(out);
checkFormat(fileType, stream);
if (stream.getFormat().isBigEndian())
stream = toLittleEndian(stream);
try (final RIFFWriter writer = new RIFFWriter(out, "WAVE")) {
write(stream, writer);
return (int) writer.getFilePointer();
}
}
}
| md-5/jdk10 | src/java.desktop/share/classes/com/sun/media/sound/WaveFloatFileWriter.java | Java | gpl-2.0 | 5,819 |
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.processor.model.java;
import com.sun.tools.internal.ws.processor.model.Parameter;
/**
*
* @author WS Development Team
*/
public class JavaParameter {
public JavaParameter() {}
public JavaParameter(String name, JavaType type, Parameter parameter) {
this(name, type, parameter, false);
}
public JavaParameter(String name, JavaType type, Parameter parameter,
boolean holder) {
this.name = name;
this.type = type;
this.parameter = parameter;
this.holder = holder;
}
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public JavaType getType() {
return type;
}
public void setType(JavaType t) {
type = t;
}
public Parameter getParameter() {
return parameter;
}
public void setParameter(Parameter p) {
parameter = p;
}
public boolean isHolder() {
return holder;
}
public void setHolder(boolean b) {
holder = b;
}
public String getHolderName() {
return holderName;
}
public void setHolderName(String holderName) {
this.holderName = holderName;
}
private String name;
private JavaType type;
private Parameter parameter;
private boolean holder;
private String holderName;
}
| axDev-JDK/jaxws | src/share/jaxws_classes/com/sun/tools/internal/ws/processor/model/java/JavaParameter.java | Java | gpl-2.0 | 2,615 |
/*
* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.scenario.effect.compiler.parser;
import com.sun.scenario.effect.compiler.JSLParser;
import com.sun.scenario.effect.compiler.model.BinaryOpType;
import com.sun.scenario.effect.compiler.model.Type;
import com.sun.scenario.effect.compiler.tree.BinaryExpr;
import org.antlr.runtime.RecognitionException;
import org.junit.Test;
import static org.junit.Assert.*;
public class EqualityExprTest extends ParserBase {
@Test
public void oneEq() throws Exception {
BinaryExpr tree = parseTreeFor("foo == 3");
assertEquals(tree.getOp(), BinaryOpType.EQEQ);
}
@Test
public void oneNotEq() throws Exception {
BinaryExpr tree = parseTreeFor("foo != 3");
assertEquals(tree.getOp(), BinaryOpType.NEQ);
}
@Test(expected = RecognitionException.class)
public void notAnEqualityExpression() throws Exception {
parseTreeFor("foo @ 3");
}
private BinaryExpr parseTreeFor(String text) throws RecognitionException {
JSLParser parser = parserOver(text);
parser.getSymbolTable().declareVariable("foo", Type.INT, null);
return (BinaryExpr)parser.equality_expression();
}
}
| teamfx/openjfx-10-dev-rt | modules/javafx.graphics/src/test/jslc/com/sun/scenario/effect/compiler/parser/EqualityExprTest.java | Java | gpl-2.0 | 2,389 |
/*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.bind.v2.model.annotation;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlValue;
final class XmlValueQuick
extends Quick
implements XmlValue
{
private final XmlValue core;
public XmlValueQuick(Locatable upstream, XmlValue core) {
super(upstream);
this.core = core;
}
protected Annotation getAnnotation() {
return core;
}
protected Quick newInstance(Locatable upstream, Annotation core) {
return new XmlValueQuick(upstream, ((XmlValue) core));
}
public Class<XmlValue> annotationType() {
return XmlValue.class;
}
}
| axDev-JDK/jaxws | src/share/jaxws_classes/com/sun/xml/internal/bind/v2/model/annotation/XmlValueQuick.java | Java | gpl-2.0 | 1,877 |
/**
* Aptana Studio
* Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.js.core.index;
import java.io.InputStream;
import java.net.URI;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import com.aptana.core.logging.IdeLog;
import com.aptana.core.util.CollectionsUtil;
import com.aptana.index.core.AbstractFileIndexingParticipant;
import com.aptana.index.core.Index;
import com.aptana.index.core.build.BuildContext;
import com.aptana.js.core.JSCorePlugin;
import com.aptana.js.core.JSTypeConstants;
import com.aptana.js.core.inferencing.JSTypeUtil;
import com.aptana.js.core.model.AliasElement;
import com.aptana.js.core.model.FunctionElement;
import com.aptana.js.core.model.PropertyElement;
import com.aptana.js.core.model.TypeElement;
import com.aptana.js.internal.core.index.JSIndexReader;
import com.aptana.js.internal.core.index.JSIndexWriter;
import com.aptana.js.internal.core.index.JSMetadataReader;
public class SDocMLFileIndexingParticipant extends AbstractFileIndexingParticipant
{
public void index(BuildContext context, Index index, IProgressMonitor monitor) throws CoreException
{
if (context == null || index == null)
{
return;
}
SubMonitor sub = SubMonitor.convert(monitor, 100);
try
{
sub.subTask(getIndexingMessage(index, context.getURI()));
try
{
JSMetadataReader reader = new JSMetadataReader();
InputStream stream = context.openInputStream(sub.newChild(5));
// parse
reader.loadXML(stream, context.getURI().toString());
sub.worked(45);
// create new Global type for this file
JSIndexReader jsir = new JSIndexReader();
List<TypeElement> globalTypes = jsir.getType(index, JSTypeConstants.GLOBAL_TYPE, true);
TypeElement globalTypeElement;
if (!CollectionsUtil.isEmpty(globalTypes))
{
globalTypeElement = globalTypes.get(globalTypes.size() - 1);
}
else
{
globalTypeElement = JSTypeUtil.createGlobalType(JSTypeConstants.GLOBAL_TYPE);
}
// process results
JSIndexWriter indexer = new JSIndexWriter();
TypeElement[] types = reader.getTypes();
AliasElement[] aliases = reader.getAliases();
URI location = context.getURI();
// write types and add properties to Window
for (TypeElement type : types)
{
// apply user agents to type
type.setHasAllUserAgents();
// apply user agents to all properties
for (PropertyElement property : type.getProperties())
{
property.setHasAllUserAgents();
}
String typeName = type.getName();
if (!typeName.contains(".") && !typeName.startsWith(JSTypeConstants.GENERIC_CLASS_OPEN)) //$NON-NLS-1$
{
List<FunctionElement> constructors = type.getConstructors();
if (!constructors.isEmpty())
{
for (FunctionElement constructor : constructors)
{
// remove the constructor and make it a global function
type.removeProperty(constructor);
globalTypeElement.addProperty(constructor);
}
// wrap the type name in Function<> and update the property owningType references to
// that name
String newName = JSTypeUtil.toFunctionType(typeName);
type.setName(newName);
for (PropertyElement property : type.getProperties())
{
property.setOwningType(newName);
}
}
else
{
PropertyElement property = globalTypeElement.getProperty(typeName);
if (property == null)
{
property = new PropertyElement();
property.setName(typeName);
property.addType(typeName);
property.setHasAllUserAgents();
globalTypeElement.addProperty(property);
}
}
}
// NOTE: we write the type after processing top-level types in case the type name changes
indexer.writeType(index, type, location);
}
for (AliasElement alias : aliases)
{
String typeName = alias.getType();
// NOTE: we currently assume we can only alias types that were encountered in this sdocml file
PropertyElement property = globalTypeElement.getProperty(typeName);
if (property != null)
{
// we found a property, now clone it
if (property instanceof FunctionElement)
{
property = new FunctionElement((FunctionElement) property);
}
else
{
property = new PropertyElement(property);
}
// and change the name to match our alias
property.setName(alias.getName());
}
else
{
// didn't find anything, so create a new property
property = new PropertyElement();
property.setName(alias.getName());
property.addType(typeName);
}
globalTypeElement.addProperty(property);
}
// write global type info
indexer.writeType(index, globalTypeElement, location);
}
catch (Throwable e)
{
IdeLog.logError(JSCorePlugin.getDefault(), e);
}
}
finally
{
sub.done();
}
}
}
| shakaran/studio3 | plugins/com.aptana.js.core/src/com/aptana/js/core/index/SDocMLFileIndexingParticipant.java | Java | gpl-3.0 | 5,317 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero;
import com.shatteredpixel.shatteredpixeldungeon.items.Generator;
import com.shatteredpixel.shatteredpixeldungeon.items.Gold;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.Artifact;
import com.shatteredpixel.shatteredpixeldungeon.items.weapon.missiles.MissileWeapon;
import com.shatteredpixel.shatteredpixeldungeon.ui.QuickSlotButton;
import com.watabou.noosa.Game;
import com.watabou.utils.Bundle;
import com.watabou.utils.Random;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
public class Bones {
private static final String BONES_FILE = "bones.dat";
private static final String LEVEL = "level";
private static final String ITEM = "item";
private static int depth = -1;
private static Item item;
public static void leave() {
depth = Dungeon.depth;
//heroes which have won the game, who die far above their farthest depth, or who are challenged drop no bones.
if (Statistics.amuletObtained || (Statistics.deepestFloor - 5) >= depth || Dungeon.challenges > 0) {
depth = -1;
return;
}
item = pickItem(Dungeon.hero);
Bundle bundle = new Bundle();
bundle.put( LEVEL, depth );
bundle.put( ITEM, item );
try {
OutputStream output = Game.instance.openFileOutput( BONES_FILE, Game.MODE_PRIVATE );
Bundle.write( bundle, output );
output.close();
} catch (IOException e) {
}
}
private static Item pickItem(Hero hero){
Item item = null;
if (Random.Int(2) == 0) {
switch (Random.Int(5)) {
case 0:
item = hero.belongings.weapon;
break;
case 1:
item = hero.belongings.armor;
break;
case 2:
item = hero.belongings.misc1;
break;
case 3:
item = hero.belongings.misc2;
break;
case 4:
item = Dungeon.quickslot.randomNonePlaceholder();
break;
}
if (item != null && !item.bones)
return pickItem(hero);
} else {
Iterator<Item> iterator = hero.belongings.backpack.iterator();
Item curItem;
ArrayList<Item> items = new ArrayList<Item>();
while (iterator.hasNext()){
curItem = iterator.next();
if (curItem.bones)
items.add(curItem);
}
if (Random.Int(3) < items.size()) {
item = Random.element(items);
if (item.stackable){
if (item instanceof MissileWeapon){
item.quantity(Random.NormalIntRange(1, item.quantity()));
} else {
item.quantity(Random.NormalIntRange(1, (item.quantity() + 1) / 2));
}
}
}
}
if (item == null) {
if (Dungeon.gold > 50) {
item = new Gold( Random.NormalIntRange( 50, Dungeon.gold ) );
} else {
item = new Gold( 50 );
}
}
return item;
}
public static Item get() {
if (depth == -1) {
try {
InputStream input = Game.instance.openFileInput( BONES_FILE ) ;
Bundle bundle = Bundle.read( input );
input.close();
depth = bundle.getInt( LEVEL );
item = (Item)bundle.get( ITEM );
return get();
} catch (Exception e) {
return null;
}
} else {
//heroes who are challenged cannot find bones
if (depth == Dungeon.depth && Dungeon.challenges == 0) {
Game.instance.deleteFile( BONES_FILE );
depth = 0;
if (item instanceof Artifact){
if (Generator.removeArtifact((Artifact)item)) {
try {
Artifact artifact = (Artifact)item.getClass().newInstance();
artifact.cursed = true;
artifact.cursedKnown = true;
//caps displayed artifact level
artifact.transferUpgrade(Math.min(
item.visiblyUpgraded(),
1 + ((Dungeon.depth * 3) / 10)));
return item;
} catch (Exception e) {
return new Gold(item.price());
}
} else {
return new Gold(item.price());
}
}
if (item.isUpgradable()) {
item.cursed = true;
item.cursedKnown = true;
if (item.isUpgradable()) {
//gain 1 level every 3.333 floors down plus one additional level.
int lvl = 1 + ((Dungeon.depth * 3) / 10);
if (lvl < item.level) {
item.degrade( item.level - lvl );
}
item.levelKnown = false;
}
}
item.syncVisuals();
return item;
} else {
return null;
}
}
}
}
| ultiferrago/shattered-pixel-dungeon | src/com/shatteredpixel/shatteredpixeldungeon/Bones.java | Java | gpl-3.0 | 6,092 |
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library 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; version 3 of
* the License.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package functionalTests.component.collectiveitf.multicast.classbased;
import java.util.List;
import functionalTests.component.collectiveitf.multicast.WrappedInteger;
public interface BroadcastServerItf {
public WrappedInteger dispatch(List<WrappedInteger> l);
}
| moliva/proactive | src/Tests/functionalTests/component/collectiveitf/multicast/classbased/BroadcastServerItf.java | Java | agpl-3.0 | 1,706 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.ld.util;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.gl.businessobject.CorrectionChangeGroup;
import org.kuali.kfs.gl.businessobject.CorrectionCriteria;
import org.kuali.kfs.gl.businessobject.OriginEntryFull;
import org.kuali.kfs.module.ld.businessobject.LaborOriginEntry;
import org.kuali.kfs.module.ld.businessobject.options.LaborOriginEntryFieldFinder;
import org.kuali.rice.core.api.util.type.KualiDecimal;
/**
* This class provides utility methods for the Labor correction document
*/
public class CorrectionDocumentUtils {
/**
* Returns whether an origin entry matches the passed in criteria. If both the criteria and actual value are both String types
* and are empty, null, or whitespace only, then they will match.
*
* @param cc correction criteria to test against origin entry
* @param oe origin entry to test
* @return true if origin entry matches the passed in criteria
*/
public static boolean laborEntryMatchesCriteria(CorrectionCriteria cc, OriginEntryFull oe) {
LaborOriginEntryFieldFinder loeff = new LaborOriginEntryFieldFinder();
LaborOriginEntry loe = (LaborOriginEntry) oe;
Object fieldActualValue = loe.getFieldValue(cc.getCorrectionFieldName());
String fieldTestValue = StringUtils.isBlank(cc.getCorrectionFieldValue()) ? "" : cc.getCorrectionFieldValue();
String fieldType = loeff.getFieldType(cc.getCorrectionFieldName());
String fieldActualValueString = org.kuali.kfs.gl.document.CorrectionDocumentUtils.convertToString(fieldActualValue, fieldType);
if ("String".equals(fieldType) || "sw".equals(cc.getCorrectionOperatorCode()) || "ew".equals(cc.getCorrectionOperatorCode()) || "ct".equals(cc.getCorrectionOperatorCode())) {
return org.kuali.kfs.gl.document.CorrectionDocumentUtils.compareStringData(cc, fieldTestValue, fieldActualValueString);
}
int compareTo = 0;
try {
if (fieldActualValue == null) {
return false;
}
if ("Integer".equals(fieldType)) {
compareTo = ((Integer) fieldActualValue).compareTo(Integer.parseInt(fieldTestValue));
}
if ("KualiDecimal".equals(fieldType)) {
compareTo = ((KualiDecimal) fieldActualValue).compareTo(new KualiDecimal(Double.parseDouble(fieldTestValue)));
}
if ("BigDecimal".equals(fieldType)) {
compareTo = ((BigDecimal) fieldActualValue).compareTo(new BigDecimal(Double.parseDouble(fieldTestValue)));
}
if ("Date".equals(fieldType)) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
compareTo = ((Date) fieldActualValue).compareTo(df.parse(fieldTestValue));
}
}
catch (Exception e) {
// any exception while parsing data return false
return false;
}
return org.kuali.kfs.gl.document.CorrectionDocumentUtils.compareTo(compareTo, cc.getCorrectionOperatorCode());
}
/**
* Returns whether the labor entry matches any of the criteria groups
*
* @param entry labor origin entry
* @param groups collection of correction change group
* @return true if labor origin entry matches any of the criteria groups
*/
public static boolean doesLaborEntryMatchAnyCriteriaGroups(OriginEntryFull entry, Collection<CorrectionChangeGroup> groups) {
boolean anyGroupMatch = false;
for (CorrectionChangeGroup ccg : groups) {
int matches = 0;
for (CorrectionCriteria cc : ccg.getCorrectionCriteria()) {
if (CorrectionDocumentUtils.laborEntryMatchesCriteria(cc, entry)) {
matches++;
}
}
// If they all match, change it
if (matches == ccg.getCorrectionCriteria().size()) {
anyGroupMatch = true;
break;
}
}
return anyGroupMatch;
}
}
| bhutchinson/kfs | kfs-ld/src/main/java/org/kuali/kfs/module/ld/util/CorrectionDocumentUtils.java | Java | agpl-3.0 | 5,023 |
/*
* Copyright (c) JForum Team. All rights reserved.
*
* The software in this package is published under the terms of the LGPL
* license a copy of which has been included with this distribution in the
* license.txt file.
*
* The JForum Project
* http://www.jforum.net
*/
package net.jforum.security;
import javax.servlet.http.HttpServletRequest;
import net.jforum.core.SessionManager;
import net.jforum.core.exceptions.AccessRuleException;
import net.jforum.entities.Forum;
import net.jforum.entities.Post;
import net.jforum.entities.Topic;
import net.jforum.entities.UserSession;
import net.jforum.repository.ForumRepository;
import net.jforum.repository.PostRepository;
import net.jforum.repository.TopicRepository;
import br.com.caelum.vraptor.ioc.Component;
/**
* Check if the user can reply to an existing topic.
* This is intended to be used with {@link SecurityConstraint}, and will check
* if the current user can reply to an existing topic.
* @author Rafael Steil
*/
@Component
public class ReplyTopicRule implements AccessRule {
private TopicRepository topicRepository;
private PostRepository postRepository;
private ForumRepository forumRepository;
private SessionManager sessionManager;
public ReplyTopicRule(TopicRepository topicRepository, PostRepository postRepository,
ForumRepository forumRepository, SessionManager sessionManager) {
this.topicRepository = topicRepository;
this.postRepository = postRepository;
this.forumRepository = forumRepository;
this.sessionManager = sessionManager;
}
/**
* Applies the following rules:
* <ul>
* <li> User must have access to the forum
* <li> Forum should not be read-only
* <li> User must be logged or anonymous posts allowed in the forum.
* </ul>
* It is expected that the parameter <i>topicId</i>, <i>topic.forum.id</i>
* or <i>postId</i> exists in the request
*/
@Override
public boolean shouldProceed(UserSession userSession, HttpServletRequest request) {
RoleManager roleManager = userSession.getRoleManager();
int forumId = this.findForumId(request);
Forum forum = this.forumRepository.get(forumId);
return roleManager.isForumAllowed(forumId)
&& (userSession.isLogged() || forum.isAllowAnonymousPosts())
&& !roleManager.isForumReadOnly(forumId)
&& (!roleManager.getPostOnlyWithModeratorOnline() || (roleManager.getPostOnlyWithModeratorOnline() && this.sessionManager.isModeratorOnline()));
}
private int findForumId(HttpServletRequest request) {
int forumId = 0;
if (request.getParameterMap().containsKey("topic.forum.id")) {
forumId = Integer.parseInt(request.getParameter("topic.forum.id"));
}
else if (request.getParameterMap().containsKey("topicId")) {
forumId = this.getForumIdFromTopic(Integer.parseInt(request.getParameter("topicId")));
}
else if (request.getParameterMap().containsKey("postId")) {
forumId = this.getForumIdFromPost(Integer.parseInt(request.getParameter("postId")));
}
else {
throw new AccessRuleException("Could not find topicId, topic.forum.id or postId in the current request");
}
return forumId;
}
private int getForumIdFromPost(int postId) {
Post post = this.postRepository.get(postId);
return post.getForum().getId();
}
private int getForumIdFromTopic(int topicId) {
Topic topic = this.topicRepository.get(topicId);
return topic.getForum().getId();
}
}
| ippxie/jforum3 | src/main/java/net/jforum/security/ReplyTopicRule.java | Java | lgpl-2.1 | 3,376 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.controller;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.BLOCKING_TIMEOUT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.descriptions.NonResolvingResourceDescriptionResolver;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.operations.global.GlobalOperationHandlers;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Tests of ability to time out operations. WFLY-2741.
*
* @author Brian Stansberry (c) 2014 Red Hat Inc.
*/
public class OperationTimeoutUnitTestCase {
private static final Executor executor = Executors.newCachedThreadPool();
private static CountDownLatch blockObject;
private static CountDownLatch latch;
private ServiceContainer container;
private ModelControllerService controllerService;
private ModelControllerClient client;
@Before
public void setupController() throws InterruptedException {
// restore default
blockObject = new CountDownLatch(1);
latch = new CountDownLatch(1);
System.out.println("========= New Test \n");
container = ServiceContainer.Factory.create("test");
ServiceTarget target = container.subTarget();
controllerService = new ModelControllerService();
target.addService(ServiceName.of("ModelController")).setInstance(controllerService).install();
controllerService.awaitStartup(30, TimeUnit.SECONDS);
ModelController controller = controllerService.getValue();
client = controller.createClient(executor);
System.setProperty(BlockingTimeout.SYSTEM_PROPERTY, "1");
}
@After
public void shutdownServiceContainer() {
System.clearProperty(BlockingTimeout.SYSTEM_PROPERTY);
releaseBlockingThreads();
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (container != null) {
container.shutdown();
try {
container.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
container = null;
}
}
}
@Test
public void testOperationHeaderConfig() throws InterruptedException, ExecutionException, TimeoutException {
blockInVerifyTest(new ModelNode(1));
}
@Test
public void testBlockInVerify() throws InterruptedException, ExecutionException, TimeoutException {
blockInVerifyTest(null);
}
private void blockInVerifyTest(ModelNode header) throws InterruptedException, ExecutionException, TimeoutException {
ModelNode op = Util.createEmptyOperation("block", null);
op.get("start").set(true);
if (header != null) {
op.get(OPERATION_HEADERS, BLOCKING_TIMEOUT).set(header);
System.setProperty(BlockingTimeout.SYSTEM_PROPERTY, "300");
}
Future<ModelNode> future = client.executeAsync(op, null);
ModelNode response = future.get(20, TimeUnit.SECONDS);
assertEquals(response.toString(), FAILED, response.get(OUTCOME).asString());
assertTrue(response.toString(), response.get(FAILURE_DESCRIPTION).asString().contains(ControllerLogger.MGMT_OP_LOGGER.timeoutExecutingOperation()));
assertEquals(ControlledProcessState.State.RESTART_REQUIRED, controllerService.getCurrentProcessState());
}
@Test
public void testBlockInRollback() throws InterruptedException, ExecutionException, TimeoutException {
ModelNode op = Util.createEmptyOperation("block", null);
op.get("fail").set(true);
op.get("stop").set(true);
Future<ModelNode> future = client.executeAsync(op, null);
ModelNode response = future.get(20, TimeUnit.SECONDS);
assertEquals(response.toString(), FAILED, response.get(OUTCOME).asString());
assertTrue(response.toString(), response.get(FAILURE_DESCRIPTION).asString().contains("failfailfail"));
assertEquals(ControlledProcessState.State.RESTART_REQUIRED, controllerService.getCurrentProcessState());
}
@Test
public void testBlockInBoth() throws InterruptedException, ExecutionException, TimeoutException {
ModelNode op = Util.createEmptyOperation("block", null);
op.get("start").set(true);
op.get("stop").set(true);
Future<ModelNode> future = client.executeAsync(op, null);
ModelNode response = future.get(20, TimeUnit.SECONDS);
assertEquals(response.toString(), FAILED, response.get(OUTCOME).asString());
assertTrue(response.toString(), response.get(FAILURE_DESCRIPTION).asString().contains(ControllerLogger.MGMT_OP_LOGGER.timeoutExecutingOperation()));
assertEquals(ControlledProcessState.State.RESTART_REQUIRED, controllerService.getCurrentProcessState());
}
@Test
public void testBlockAwaitingRuntimeLock() throws InterruptedException, ExecutionException, TimeoutException {
// Get the service container fubar
blockInVerifyTest(null);
ModelNode op = Util.createEmptyOperation("block", null);
op.get("start").set(false);
op.get("stop").set(false);
Future<ModelNode> future = client.executeAsync(op, null);
ModelNode response = future.get(20, TimeUnit.SECONDS);
assertEquals(response.toString(), FAILED, response.get(OUTCOME).asString());
assertTrue(response.toString(), response.get(FAILURE_DESCRIPTION).asString().contains(ControllerLogger.MGMT_OP_LOGGER.timeoutAwaitingInitialStability()));
assertEquals(ControlledProcessState.State.RESTART_REQUIRED, controllerService.getCurrentProcessState());
}
@Test
public void testRepairInRollback() throws InterruptedException, ExecutionException, TimeoutException {
ModelNode op = Util.createEmptyOperation("block", null);
op.get("fail").set(true);
op.get("start").set(true);
op.get("repair").set(true);
Future<ModelNode> future = client.executeAsync(op, null);
ModelNode response = future.get(20, TimeUnit.SECONDS);
assertEquals(response.toString(), FAILED, response.get(OUTCOME).asString());
assertTrue(response.toString(), response.get(FAILURE_DESCRIPTION).asString().contains("failfailfail"));
// We should be in RUNNING state because stability could be obtained before the op completed
assertEquals(ControlledProcessState.State.RUNNING, controllerService.getCurrentProcessState());
}
private static void releaseBlockingThreads() {
if (blockObject != null) {
blockObject.countDown();
}
}
private static void block() {
latch.countDown();
try {
blockObject.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static class ModelControllerService extends TestModelControllerService {
@Override
protected void initModel(ManagementModel managementModel, Resource modelControllerResource) {
ManagementResourceRegistration rootRegistration = managementModel.getRootResourceRegistration();
rootRegistration.registerOperationHandler(BlockingServiceHandler.DEFINITION, new BlockingServiceHandler());
GlobalOperationHandlers.registerGlobalOperations(rootRegistration, processType);
}
}
public static class BlockingServiceHandler implements OperationStepHandler {
static final SimpleOperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder("block", new NonResolvingResourceDescriptionResolver())
// this isn't really runtime-only but we lie and say it is to let
// testBlockAwaitingRuntimeLock() work. That test relies on first
// messing up MSC in order to how the next op that blocks waiting
// for MSC stability reacts, but messing up MSC also puts the process
// in restart-required. If this op isn't "runtime-only" the controller
// won't let it run then.
.setRuntimeOnly()
.build();
@Override
public void execute(OperationContext context, ModelNode operation) {
context.readResourceForUpdate(PathAddress.EMPTY_ADDRESS);
context.addStep(new OperationStepHandler() {
@Override
public void execute(final OperationContext context, ModelNode operation) {
boolean start = operation.get("start").asBoolean(false);
boolean stop = operation.get("stop").asBoolean(false);
boolean fail = operation.get("fail").asBoolean(false);
final boolean repair = fail && operation.get("repair").asBoolean(false);
BlockingService bad = start ? (stop ? BlockingService.BOTH : BlockingService.START)
: (stop ? BlockingService.STOP : BlockingService.NEITHER);
final ServiceName svcName = ServiceName.JBOSS.append("bad-service");
context.getServiceTarget().addService(svcName).setInstance(bad).install();
try {
bad.startLatch.await(20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
if (fail) {
context.setRollbackOnly();
context.getFailureDescription().set("failfailfail");
}
context.completeStep(new OperationContext.ResultHandler() {
@Override
public void handleResult(OperationContext.ResultAction resultAction, OperationContext context, ModelNode operation) {
if (repair) {
releaseBlockingThreads();
}
context.removeService(svcName);
}
});
}
}, OperationContext.Stage.RUNTIME);
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
}
private static class BlockingService implements Service<Void> {
private static final BlockingService START = new BlockingService(true, false);
private static final BlockingService STOP = new BlockingService(false, true);
private static final BlockingService BOTH = new BlockingService(true, true);
private static final BlockingService NEITHER = new BlockingService(false, false);
private final boolean start;
private final boolean stop;
private final CountDownLatch startLatch = new CountDownLatch(1);
private BlockingService(boolean start, boolean stop) {
this.start = start;
this.stop = stop;
}
@Override
public Void getValue() throws IllegalStateException, IllegalArgumentException {
return null;
}
@Override
public void start(StartContext context) throws StartException {
startLatch.countDown();
if (start) {
block();
}
}
@Override
public void stop(StopContext context) {
if (stop) {
block();
}
}
}
}
| darranl/wildfly-core | controller/src/test/java/org/jboss/as/controller/OperationTimeoutUnitTestCase.java | Java | lgpl-2.1 | 14,070 |
/**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic 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.
*
* FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain.phd.candidacy;
import java.util.Collections;
import java.util.Set;
import org.fenixedu.academic.domain.ExecutionYear;
import org.fenixedu.academic.domain.Person;
import org.fenixedu.academic.domain.accounting.Entry;
import org.fenixedu.academic.domain.accounting.EntryType;
import org.fenixedu.academic.domain.accounting.EventType;
import org.fenixedu.academic.domain.accounting.PaymentCodeType;
import org.fenixedu.academic.domain.accounting.paymentCodes.AccountingEventPaymentCode;
import org.fenixedu.academic.domain.accounting.paymentCodes.IndividualCandidacyPaymentCode;
import org.fenixedu.academic.domain.administrativeOffice.AdministrativeOffice;
import org.fenixedu.academic.domain.exceptions.DomainException;
import org.fenixedu.academic.domain.phd.PhdIndividualProgramProcess;
import org.fenixedu.academic.domain.phd.PhdProgram;
import org.fenixedu.academic.domain.phd.alert.AlertService;
import org.fenixedu.academic.dto.accounting.EntryDTO;
import org.fenixedu.academic.dto.accounting.SibsTransactionDetailDTO;
import org.fenixedu.academic.util.Bundle;
import org.fenixedu.academic.util.LabelFormatter;
import org.fenixedu.academic.util.Money;
import org.fenixedu.bennu.core.domain.User;
import org.joda.time.YearMonthDay;
public class PhdProgramCandidacyEvent extends PhdProgramCandidacyEvent_Base {
protected PhdProgramCandidacyEvent() {
super();
}
public PhdProgramCandidacyEvent(AdministrativeOffice administrativeOffice, Person person,
PhdProgramCandidacyProcess candidacyProcess) {
this();
init(administrativeOffice, person, candidacyProcess);
}
public PhdProgramCandidacyEvent(final Person person, final PhdProgramCandidacyProcess process) {
this(process.getIndividualProgramProcess().getAdministrativeOffice(), person, process);
if (process.isPublicCandidacy()) {
attachAvailablePaymentCode();
}
}
protected void attachAvailablePaymentCode() {
YearMonthDay candidacyDate = getCandidacyProcess().getCandidacyDate().toDateMidnight().toYearMonthDay();
IndividualCandidacyPaymentCode paymentCode =
IndividualCandidacyPaymentCode.getAvailablePaymentCodeAndUse(PaymentCodeType.PHD_PROGRAM_CANDIDACY_PROCESS,
candidacyDate, this, getPerson());
if (paymentCode == null) {
throw new DomainException("error.IndividualCandidacyEvent.invalid.payment.code");
}
}
private void init(AdministrativeOffice administrativeOffice, Person person, PhdProgramCandidacyProcess candidacyProcess) {
super.init(administrativeOffice, EventType.CANDIDACY_ENROLMENT, person);
String[] args = {};
if (candidacyProcess == null) {
throw new DomainException("error.phd.candidacy.PhdProgramCandidacyEvent.candidacyProcess.cannot.be.null", args);
}
super.setCandidacyProcess(candidacyProcess);
}
@Override
public void setCandidacyProcess(PhdProgramCandidacyProcess candidacyProcess) {
throw new DomainException("error.phd.candidacy.PhdProgramCandidacyEvent.cannot.modify.candidacyProcess");
}
@Override
public LabelFormatter getDescriptionForEntryType(EntryType entryType) {
final LabelFormatter labelFormatter = new LabelFormatter();
labelFormatter.appendLabel(entryType.name(), Bundle.ENUMERATION).appendLabel(" (")
.appendLabel(getPhdProgram().getPresentationName()).appendLabel(" - ").appendLabel(getExecutionYear().getYear())
.appendLabel(")");
return labelFormatter;
}
@Override
public LabelFormatter getDescription() {
return new LabelFormatter().appendLabel(AlertService.getMessageFromResource("label.phd.candidacy")).appendLabel(": ")
.appendLabel(getPhdProgram().getPresentationName()).appendLabel(" - ").appendLabel(getExecutionYear().getYear());
}
private ExecutionYear getExecutionYear() {
return getCandidacyProcess().getIndividualProgramProcess().getExecutionYear();
}
@Override
protected PhdProgram getPhdProgram() {
return getCandidacyProcess().getIndividualProgramProcess().getPhdProgram();
}
@Override
protected void disconnect() {
setCandidacyProcess(null);
super.disconnect();
}
public IndividualCandidacyPaymentCode getAssociatedPaymentCode() {
if (super.getAllPaymentCodes().isEmpty()) {
return null;
}
return (IndividualCandidacyPaymentCode) super.getAllPaymentCodes().iterator().next();
}
@Override
public PhdIndividualProgramProcess getPhdIndividualProgramProcess() {
return getCandidacyProcess().getIndividualProgramProcess();
}
@Override
protected Set<Entry> internalProcess(User responsibleUser, AccountingEventPaymentCode paymentCode, Money amountToPay,
SibsTransactionDetailDTO transactionDetail) {
return internalProcess(responsibleUser, Collections.singletonList(new EntryDTO(getEntryType(), this, amountToPay)),
transactionDetail);
}
protected EntryType getEntryType() {
return EntryType.CANDIDACY_ENROLMENT_FEE;
}
}
| andre-nunes/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/phd/candidacy/PhdProgramCandidacyEvent.java | Java | lgpl-3.0 | 6,049 |
/*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.intellij.plugin.actions;
import com.facebook.buck.intellij.plugin.build.BuckBuildCommandHandler;
import com.facebook.buck.intellij.plugin.build.BuckBuildManager;
import com.facebook.buck.intellij.plugin.build.BuckCommand;
import com.facebook.buck.intellij.plugin.config.BuckModule;
import com.facebook.buck.intellij.plugin.ui.BuckEventsConsumer;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
/**
* Run buck build command.
*/
public class BuckBuildAction extends BuckBaseAction {
public static final String ACTION_TITLE = "Run buck build";
public static final String ACTION_DESCRIPTION = "Run buck build command";
public BuckBuildAction() {
super(ACTION_TITLE, ACTION_DESCRIPTION, AllIcons.Actions.Download);
}
@Override
public void update(AnActionEvent e) {
if (preUpdateCheck(e)) {
Project project = e.getProject();
e.getPresentation().setEnabled(!BuckBuildManager.getInstance(project).isBuilding());
}
}
@Override
public void actionPerformed(AnActionEvent e) {
BuckBuildManager buildManager = BuckBuildManager.getInstance(e.getProject());
String target = buildManager.getCurrentSavedTarget(e.getProject());
if (target == null) {
buildManager.showNoTargetMessage(e.getProject());
return;
}
// Initiate a buck build
BuckEventsConsumer bu = new BuckEventsConsumer(e.getProject());
BuckModule mod = e.getProject().getComponent(BuckModule.class);
mod.attach(bu, target);
// this needs to change
BuckBuildCommandHandler handler = new BuckBuildCommandHandler(
e.getProject(),
e.getProject().getBaseDir(),
BuckCommand.BUILD);
handler.command().addParameter(target);
buildManager.runBuckCommand(handler, ACTION_TITLE);
// until here
}
}
| tgummerer/buck | src/com/facebook/buck/intellij/plugin/src/com/facebook/buck/intellij/plugin/actions/BuckBuildAction.java | Java | apache-2.0 | 2,497 |
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package benchmarks.regression;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
/**
* Measure throughput of various parsers.
*
* <p>This benchmark requires that ParseBenchmarkData.zip is on the classpath.
* That file contains Twitter feed data, which is representative of what
* applications will be parsing.
*/
public final class ParseBenchmark extends SimpleBenchmark {
@Param Document document;
@Param Api api;
private enum Document {
TWEETS,
READER_SHORT,
READER_LONG
}
private enum Api {
ANDROID_STREAM("json") {
@Override Parser newParser() {
return new AndroidStreamParser();
}
},
ORG_JSON("json") {
@Override Parser newParser() {
return new OrgJsonParser();
}
},
XML_PULL("xml") {
@Override Parser newParser() {
return new GeneralXmlPullParser();
}
},
XML_DOM("xml") {
@Override Parser newParser() {
return new XmlDomParser();
}
},
XML_SAX("xml") {
@Override Parser newParser() {
return new XmlSaxParser();
}
};
final String extension;
private Api(String extension) {
this.extension = extension;
}
abstract Parser newParser();
}
private String text;
private Parser parser;
@Override protected void setUp() throws Exception {
text = resourceToString("/" + document.name() + "." + api.extension);
parser = api.newParser();
}
public void timeParse(int reps) throws Exception {
for (int i = 0; i < reps; i++) {
parser.parse(text);
}
}
public static void main(String... args) throws Exception {
Runner.main(ParseBenchmark.class, args);
}
private static String resourceToString(String path) throws Exception {
InputStream in = ParseBenchmark.class.getResourceAsStream(path);
if (in == null) {
throw new IllegalArgumentException("No such file: " + path);
}
Reader reader = new InputStreamReader(in, "UTF-8");
char[] buffer = new char[8192];
StringWriter writer = new StringWriter();
int count;
while ((count = reader.read(buffer)) != -1) {
writer.write(buffer, 0, count);
}
reader.close();
return writer.toString();
}
interface Parser {
void parse(String data) throws Exception;
}
private static class AndroidStreamParser implements Parser {
@Override public void parse(String data) throws Exception {
android.util.JsonReader jsonReader
= new android.util.JsonReader(new StringReader(data));
readToken(jsonReader);
jsonReader.close();
}
public void readObject(android.util.JsonReader reader) throws IOException {
reader.beginObject();
while (reader.hasNext()) {
reader.nextName();
readToken(reader);
}
reader.endObject();
}
public void readArray(android.util.JsonReader reader) throws IOException {
reader.beginArray();
while (reader.hasNext()) {
readToken(reader);
}
reader.endArray();
}
private void readToken(android.util.JsonReader reader) throws IOException {
switch (reader.peek()) {
case BEGIN_ARRAY:
readArray(reader);
break;
case BEGIN_OBJECT:
readObject(reader);
break;
case BOOLEAN:
reader.nextBoolean();
break;
case NULL:
reader.nextNull();
break;
case NUMBER:
reader.nextLong();
break;
case STRING:
reader.nextString();
break;
default:
throw new IllegalArgumentException("Unexpected token" + reader.peek());
}
}
}
private static class OrgJsonParser implements Parser {
@Override public void parse(String data) throws Exception {
if (data.startsWith("[")) {
new JSONArray(data);
} else if (data.startsWith("{")) {
new JSONObject(data);
} else {
throw new IllegalArgumentException();
}
}
}
private static class GeneralXmlPullParser implements Parser {
@Override public void parse(String data) throws Exception {
XmlPullParser xmlParser = android.util.Xml.newPullParser();
xmlParser.setInput(new StringReader(data));
xmlParser.nextTag();
while (xmlParser.next() != XmlPullParser.END_DOCUMENT) {
xmlParser.getName();
xmlParser.getText();
}
}
}
private static class XmlDomParser implements Parser {
@Override public void parse(String data) throws Exception {
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(data)));
}
}
private static class XmlSaxParser implements Parser {
@Override public void parse(String data) throws Exception {
SAXParserFactory.newInstance().newSAXParser().parse(
new InputSource(new StringReader(data)), new DefaultHandler());
}
}
}
| JuudeDemos/android-sdk-20 | src/benchmarks/regression/ParseBenchmark.java | Java | apache-2.0 | 6,760 |
/*
* Encog(tm) Core v3.3 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2014 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.util.normalize;
import org.encog.EncogError;
/**
* Used for normalization errors.
*
* @author jheaton
*
*/
public class NormalizationError extends EncogError {
/**
* The serial id.
*/
private static final long serialVersionUID = 1454192534753095149L;
/**
* Construct a message exception.
*
* @param msg
* The exception message.
*/
public NormalizationError(final String msg) {
super(msg);
}
/**
* Construct an exception that holds another exception.
*
* @param t
* The other exception.
*/
public NormalizationError(final Throwable t) {
super(t);
}
}
| krzysztof-magosa/encog-java-core | src/main/java/org/encog/util/normalize/NormalizationError.java | Java | apache-2.0 | 1,514 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.viewer.restfulobjects.applib.client;
import java.io.IOException;
import java.util.List;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation;
import org.apache.isis.viewer.restfulobjects.applib.LinkRepresentation;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.collect.Lists;
public class RepresentationWalker {
static class Step {
private final String key;
private final LinkRepresentation link;
private final JsonRepresentation body;
private final RestfulResponse<? extends JsonRepresentation> response;
private String error;
private final Exception exception;
public Step(final String key, final LinkRepresentation link, final JsonRepresentation body, final RestfulResponse<? extends JsonRepresentation> response, final String error, final Exception exception) {
this.key = key;
this.link = link;
this.body = body;
this.response = response;
this.error = error;
this.exception = exception;
}
@Override
public String toString() {
return "Step [key=" + key + ", link=" + (link != null ? link.getHref() : "(null)") + ", error=" + error + "]";
}
}
private final RestfulClient restfulClient;
private final List<Step> steps = Lists.newLinkedList();
public RepresentationWalker(final RestfulClient restfulClient, final Response response) {
this.restfulClient = restfulClient;
final RestfulResponse<JsonRepresentation> jsonResp = RestfulResponse.of(response);
addStep(null, null, null, jsonResp, null, null);
}
private Step addStep(final String key, final LinkRepresentation link, final JsonRepresentation body, final RestfulResponse<JsonRepresentation> jsonResp, final String error, final Exception ex) {
final Step step = new Step(key, link, body, jsonResp, error, ex);
steps.add(0, step);
if (error != null) {
if (jsonResp.getStatus().getFamily() != Family.SUCCESSFUL) {
step.error = "response status code: " + jsonResp.getStatus();
}
}
return step;
}
public void walk(final String path) {
walk(path, null);
}
public void walk(final String path, final JsonRepresentation invokeBody) {
final Step previousStep = currentStep();
if (previousStep.error != null) {
return;
}
final RestfulResponse<? extends JsonRepresentation> jsonResponse = previousStep.response;
JsonRepresentation entity;
try {
entity = jsonResponse.getEntity();
} catch (final Exception e) {
addStep(path, null, null, null, "exception: " + e.getMessage(), e);
return;
}
LinkRepresentation link;
try {
link = entity.getLink(path);
} catch (final Exception e) {
addStep(path, null, null, null, "exception: " + e.getMessage(), e);
return;
}
if (link == null) {
addStep(path, null, null, null, "no such link '" + path + "'", null);
return;
}
final RestfulResponse<JsonRepresentation> response;
try {
if (invokeBody != null) {
response = restfulClient.follow(link, invokeBody);
} else {
response = restfulClient.follow(link);
}
} catch (final Exception e) {
addStep(path, link, null, null, "failed to follow link: " + e.getMessage(), e);
return;
}
addStep(path, link, null, response, null, null);
}
/**
* The entity returned from the previous walk.
*
* <p>
* Will return null if the previous walk returned an error.
*/
public JsonRepresentation getEntity() throws JsonParseException, JsonMappingException, IOException {
final Step currentStep = currentStep();
if (currentStep.response == null || currentStep.error != null) {
return null;
}
return currentStep.response.getEntity();
}
/**
* The response returned from the previous walk.
*
* <p>
* Once a walk/performed has been attempted, is guaranteed to return a
* non-null value. (Conversely, will return <tt>null</tt> immediately after
* instantiation and prior to a walk being attempted/performed).
*/
public RestfulResponse<?> getResponse() {
final Step currentStep = currentStep();
return currentStep != null ? currentStep.response : null;
}
/**
* The error (if any) that occurred from the previous walk.
*/
public String getError() {
final Step currentStep = currentStep();
return currentStep != null ? currentStep.error : null;
}
/**
* The exception (if any) that occurred from the previous walk.
*
* <p>
* Will only ever be populated if {@link #getError()} is non-null.
*/
public Exception getException() {
final Step currentStep = currentStep();
return currentStep != null ? currentStep.exception : null;
}
/**
* The step that has just been walked.
*/
private Step currentStep() {
return steps.get(0);
}
}
| howepeng/isis | core/viewer-restfulobjects-applib/src/main/java/org/apache/isis/viewer/restfulobjects/applib/client/RepresentationWalker.java | Java | apache-2.0 | 6,342 |
/*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.querydsl.jpa.impl;
import javax.annotation.Nullable;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.EntityPath;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.JPQLQueryFactory;
import com.querydsl.jpa.JPQLTemplates;
/**
* Factory class for query and DML clause creation
*
* @author tiwe
*
*/
public class JPAQueryFactory implements JPQLQueryFactory {
@Nullable
private final JPQLTemplates templates;
private final Provider<EntityManager> entityManager;
public JPAQueryFactory(final EntityManager entityManager) {
this.entityManager = new Provider<EntityManager>() {
@Override
public EntityManager get() {
return entityManager;
}
};
this.templates = null;
}
public JPAQueryFactory(JPQLTemplates templates, final EntityManager entityManager) {
this.entityManager = new Provider<EntityManager>() {
@Override
public EntityManager get() {
return entityManager;
}
};
this.templates = templates;
}
public JPAQueryFactory(Provider<EntityManager> entityManager) {
this.entityManager = entityManager;
this.templates = null;
}
public JPAQueryFactory(JPQLTemplates templates, Provider<EntityManager> entityManager) {
this.entityManager = entityManager;
this.templates = templates;
}
@Override
public JPADeleteClause delete(EntityPath<?> path) {
if (templates != null) {
return new JPADeleteClause(entityManager.get(), path, templates);
} else {
return new JPADeleteClause(entityManager.get(), path);
}
}
@Override
public <T> JPAQuery<T> select(Expression<T> expr) {
return query().select(expr);
}
@Override
public JPAQuery<Tuple> select(Expression<?>... exprs) {
return query().select(exprs);
}
@Override
public <T> JPAQuery<T> selectDistinct(Expression<T> expr) {
return select(expr).distinct();
}
@Override
public JPAQuery<Tuple> selectDistinct(Expression<?>... exprs) {
return select(exprs).distinct();
}
@Override
public JPAQuery<Integer> selectOne() {
return select(Expressions.ONE);
}
@Override
public JPAQuery<Integer> selectZero() {
return select(Expressions.ZERO);
}
@Override
public <T> JPAQuery<T> selectFrom(EntityPath<T> from) {
return select(from).from(from);
}
@Override
public JPAQuery<?> from(EntityPath<?> from) {
return query().from(from);
}
@Override
public JPAQuery<?> from(EntityPath<?>... from) {
return query().from(from);
}
@Override
public JPAUpdateClause update(EntityPath<?> path) {
if (templates != null) {
return new JPAUpdateClause(entityManager.get(), path, templates);
} else {
return new JPAUpdateClause(entityManager.get(), path);
}
}
@Override
public JPAQuery<?> query() {
if (templates != null) {
return new JPAQuery<Void>(entityManager.get(), templates);
} else {
return new JPAQuery<Void>(entityManager.get());
}
}
}
| balazs-zsoldos/querydsl | querydsl-jpa/src/main/java/com/querydsl/jpa/impl/JPAQueryFactory.java | Java | apache-2.0 | 4,049 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.datastructures;
import org.apache.ignite.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.processors.datastructures.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.testframework.*;
import org.apache.ignite.transactions.*;
import org.jetbrains.annotations.*;
import java.util.*;
import java.util.concurrent.*;
import static org.apache.ignite.cache.CacheMode.*;
import static org.apache.ignite.transactions.TransactionConcurrency.*;
import static org.apache.ignite.transactions.TransactionIsolation.*;
/**
* Cache sequence basic tests.
*/
public abstract class GridCacheSequenceApiSelfAbstractTest extends IgniteAtomicsAbstractTest {
/** */
protected static final int BATCH_SIZE = 3;
/** Number of sequences. */
protected static final int SEQ_NUM = 3;
/** */
private static final String TRANSACTIONAL_CACHE_NAME = "tx_cache";
/** Number of loops in method execution. */
protected static final int MAX_LOOPS_NUM = 1000;
/** Number of threads for multi-threaded test. */
protected static final int THREAD_NUM = 10;
/** Random number generator. */
protected static final Random RND = new Random();
/** Names of mandatory sequences. */
private static String[] seqNames = new String[SEQ_NUM];
/** Mandatory sequences. */
private static IgniteAtomicSequence[] seqArr = new IgniteAtomicSequence[SEQ_NUM];
/** {@inheritDoc} */
@Override protected int gridCount() {
return 1;
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(gridName);
CacheConfiguration ccfg = new CacheConfiguration();
ccfg.setName(TRANSACTIONAL_CACHE_NAME);
ccfg.setCacheMode(PARTITIONED);
cfg.setCacheConfiguration(ccfg);
return cfg;
}
/** {@inheritDoc} */
protected AtomicConfiguration atomicConfiguration() {
AtomicConfiguration atomicCfg = super.atomicConfiguration();
atomicCfg.setAtomicSequenceReserveSize(BATCH_SIZE);
return atomicCfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
//Prepare names of mandatory sequences.
for (int i = 0; i < SEQ_NUM; i++)
seqNames[i] = UUID.randomUUID().toString();
// Prepare mandatory sequences.
seqArr[0] = grid().atomicSequence(seqNames[0], 0, true);
seqArr[1] = grid().atomicSequence(seqNames[1], RND.nextLong(), true);
seqArr[2] = grid().atomicSequence(seqNames[2], -1 * RND.nextLong(), true);
// Check and change batch size.
for (IgniteAtomicSequence seq : seqArr) {
assert seq != null;
// Compare with default batch size.
assertEquals(BATCH_SIZE, seq.batchSize());
}
assertEquals(1, G.allGrids().size());
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
try {
// Remove mandatory sequences from cache.
for (String seqName : seqNames) {
IgniteAtomicSequence seq = grid().atomicSequence(seqName, 0, false);
assertNotNull(seq);
seq.close();
assertNull(grid().atomicSequence(seqName, 0, false));
}
}
finally {
super.afterTestsStopped();
}
}
/** {@inheritDoc} */
protected IgniteEx grid() {
return grid(0);
}
/**
* @throws Exception If failed.
*/
public void testPrepareSequence() throws Exception {
// Random sequence names.
String locSeqName1 = UUID.randomUUID().toString();
String locSeqName2 = UUID.randomUUID().toString();
IgniteAtomicSequence locSeq1 = grid().atomicSequence(locSeqName1, 0, true);
IgniteAtomicSequence locSeq2 = grid().atomicSequence(locSeqName2, 0, true);
IgniteAtomicSequence locSeq3 = grid().atomicSequence(locSeqName1, 0, true);
assertNotNull(locSeq1);
assertNotNull(locSeq2);
assertNotNull(locSeq3);
assert locSeq1.equals(locSeq3);
assert locSeq3.equals(locSeq1);
assert !locSeq3.equals(locSeq2);
removeSequence(locSeqName1);
removeSequence(locSeqName2);
}
/**
* @throws Exception If failed.
*/
public void testAddWrongValue() throws Exception {
for (IgniteAtomicSequence seq : seqArr) {
try {
seq.getAndAdd(-15);
fail("Exception expected.");
}
catch (IllegalArgumentException e) {
info("Caught expected exception: " + e);
}
try {
seq.addAndGet(-15);
fail("Exception expected.");
}
catch (IllegalArgumentException e) {
info("Caught expected exception: " + e);
}
}
}
/**
* @throws Exception If failed.
*/
public void testGetAndIncrement() throws Exception {
for (int i = 0; i < MAX_LOOPS_NUM; i++) {
for (IgniteAtomicSequence seq : seqArr)
getAndIncrement(seq);
if (i % 100 == 0)
info("Finished iteration: " + i);
}
}
/**
* @throws Exception If failed.
*/
public void testIncrementAndGet() throws Exception {
for (int i = 0; i < MAX_LOOPS_NUM; i++) {
for (IgniteAtomicSequence seq : seqArr)
incrementAndGet(seq);
if (i % 100 == 0)
info("Finished iteration: " + i);
}
}
/**
* @throws Exception If failed.
*/
public void testAddAndGet() throws Exception {
for (int i = 1; i < MAX_LOOPS_NUM; i++) {
for (IgniteAtomicSequence seq : seqArr)
addAndGet(seq, i);
if (i % 100 == 0)
info("Finished iteration: " + i);
}
}
/**
* @throws Exception If failed.
*/
public void testGetAndAdd() throws Exception {
for (int i = 1; i < MAX_LOOPS_NUM; i++) {
for (IgniteAtomicSequence seq : seqArr)
getAndAdd(seq, i);
if (i % 100 == 0)
info("Finished iteration: " + i);
}
}
/**
* @throws Exception If failed.
*/
public void testGetAndAddInTx() throws Exception {
try (Transaction tx = grid().transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
for (int i = 1; i < MAX_LOOPS_NUM; i++) {
for (IgniteAtomicSequence seq : seqArr)
getAndAdd(seq, i);
if (i % 100 == 0)
info("Finished iteration: " + i);
}
}
}
/**
* @throws Exception If failed.
*/
public void testSequenceIntegrity0() throws Exception {
// Random sequence names.
String locSeqName1 = UUID.randomUUID().toString();
String locSeqName2 = UUID.randomUUID().toString();
// Sequence.
IgniteAtomicSequence locSeq1 = grid().atomicSequence(locSeqName1, 0, true);
locSeq1.batchSize(1);
// Sequence.
long initVal = -1500;
IgniteAtomicSequence locSeq2 = grid().atomicSequence(locSeqName2, initVal, true);
locSeq2.batchSize(7);
// Compute sequence value manually and compare with sequence value.
for (int i = 0; i < MAX_LOOPS_NUM; i++) {
integrity(locSeq1, i * 4);
integrity(locSeq2, (i * 4) + initVal);
if (i % 100 == 0)
info("Finished iteration: " + i);
}
removeSequence(locSeqName1);
removeSequence(locSeqName2);
}
/**
* @throws Exception If failed.
*/
public void testSequenceIntegrity1() throws Exception {
sequenceIntegrity(1, 0);
sequenceIntegrity(7, -1500);
sequenceIntegrity(3, 345);
}
/**
* @throws Exception If failed.
*/
public void testMultiThreadedSequenceIntegrity() throws Exception {
multiThreadedSequenceIntegrity(1, 0);
multiThreadedSequenceIntegrity(7, -1500);
multiThreadedSequenceIntegrity(3, 345);
}
/**
* @throws Exception If failed.
*/
public void testEviction() throws Exception {
String locSeqName = UUID.randomUUID().toString();
IgniteAtomicSequence locSeq = grid().atomicSequence(locSeqName, 0, true);
locSeq.addAndGet(153);
GridCacheAdapter cache = ((IgniteKernal)grid()).internalCache(GridCacheUtils.ATOMICS_CACHE_NAME);
assertNotNull(cache);
cache.evictAll(cache.keySet());
assert null != cache.get(new GridCacheInternalKeyImpl(locSeqName));
}
/**
* @throws Exception If failed.
*/
public void testRemove() throws Exception {
String locSeqName = UUID.randomUUID().toString();
IgniteAtomicSequence seq = grid().atomicSequence(locSeqName, 0, true);
seq.addAndGet(153);
seq.close();
try {
seq.addAndGet(153);
fail("Exception expected.");
}
catch (IllegalStateException e) {
info("Caught expected exception: " + e);
}
}
/**
* @throws Exception If failed.
*/
public void testCacheSets() throws Exception {
// Make new atomic sequence in cache.
IgniteAtomicSequence seq = grid().atomicSequence(UUID.randomUUID().toString(), 0, true);
seq.incrementAndGet();
GridCacheAdapter cache = ((IgniteKernal)grid()).internalCache(GridCacheUtils.ATOMICS_CACHE_NAME);
assertNotNull(cache);
GridTestUtils.assertThrows(log, new Callable<Void>() {
@Override public Void call() throws Exception {
grid().cache(GridCacheUtils.ATOMICS_CACHE_NAME);
return null;
}
}, IllegalStateException.class, null);
for (Object o : cache.keySet())
assert !(o instanceof GridCacheInternal) : "Wrong keys [key=" + o + ']';
for (Object o : cache.values())
assert !(o instanceof GridCacheInternal) : "Wrong values [value=" + o + ']';
for (Object o : cache.entrySet())
assert !(o instanceof GridCacheInternal) : "Wrong entries [entry=" + o + ']';
assert cache.keySet().isEmpty();
assert cache.values().isEmpty();
assert cache.entrySet().isEmpty();
assert cache.size() == 0;
for (String seqName : seqNames)
assert null != cache.get(new GridCacheInternalKeyImpl(seqName));
}
/**
* Sequence get and increment.
*
* @param seq Sequence for test.
* @throws Exception If failed.
* @return Result of operation.
*/
private long getAndIncrement(IgniteAtomicSequence seq) throws Exception {
long locSeqVal = seq.get();
assertEquals(locSeqVal, seq.getAndIncrement());
assertEquals(locSeqVal + 1, seq.get());
return seq.get();
}
/**
* Sequence add and increment
*
* @param seq Sequence for test.
* @throws Exception If failed.
* @return Result of operation.
*/
private long incrementAndGet(IgniteAtomicSequence seq) throws Exception {
long locSeqVal = seq.get();
assertEquals(locSeqVal + 1, seq.incrementAndGet());
assertEquals(locSeqVal + 1, seq.get());
return seq.get();
}
/**
* Sequence add and get.
*
* @param seq Sequence for test.
* @param l Number of added elements.
* @throws Exception If failed.
* @return Result of operation.
*/
private long addAndGet(IgniteAtomicSequence seq, long l) throws Exception {
long locSeqVal = seq.get();
assertEquals(locSeqVal + l, seq.addAndGet(l));
assertEquals(locSeqVal + l, seq.get());
return seq.get();
}
/**
* Sequence add and get.
*
* @param seq Sequence for test.
* @param l Number of added elements.
* @throws Exception If failed.
* @return Result of operation.
*/
private long getAndAdd(IgniteAtomicSequence seq, long l) throws Exception {
long locSeqVal = seq.get();
assertEquals(locSeqVal, seq.getAndAdd(l));
assertEquals(locSeqVal + l, seq.get());
return seq.get();
}
/**
* Sequence integrity.
*
* @param batchSize Sequence batch size.
* @param initVal Sequence initial value.
* @throws Exception If test fail.
*/
private void sequenceIntegrity(int batchSize, long initVal) throws Exception {
// Random sequence names.
String locSeqName = UUID.randomUUID().toString();
// Sequence.
IgniteAtomicSequence locSeq = grid().atomicSequence(locSeqName, initVal, true);
locSeq.batchSize(batchSize);
// Result set.
Collection<Long> resSet = new HashSet<>();
// Get sequence value and try to put it result set.
for (int i = 0; i < MAX_LOOPS_NUM; i++) {
Long val = locSeq.getAndIncrement();
assert resSet.add(val) : "Element already in set : " + val;
}
assert resSet.size() == MAX_LOOPS_NUM;
for (long i = initVal; i < MAX_LOOPS_NUM + initVal; i++)
assert resSet.contains(i) : "Element is absent in set : " + i;
removeSequence(locSeqName);
}
/**
* Multi-threaded integrity.
*
* @param batchSize Sequence batch size.
* @param initVal Sequence initial value.
* @throws Exception If test fail.
*/
private void multiThreadedSequenceIntegrity(int batchSize, long initVal) throws Exception {
// Random sequence names.
String locSeqName = UUID.randomUUID().toString();
// Sequence.
final IgniteAtomicSequence locSeq = grid().atomicSequence(locSeqName, initVal,
true);
locSeq.batchSize(batchSize);
// Result set.
final Set<Long> resSet = Collections.synchronizedSet(new HashSet<Long>());
// Get sequence value and try to put it result set.
for (int i = 0; i < MAX_LOOPS_NUM; i++) {
Long val = locSeq.getAndIncrement();
assert !resSet.contains(val) : "Element already in set : " + val;
resSet.add(val);
if (i % 100 == 0)
info("Finished iteration 1: " + i);
}
// Work with sequences in many threads.
multithreaded(
new Callable() {
@Nullable @Override public Object call() throws Exception {
// Get sequence value and try to put it result set.
for (int i = 0; i < MAX_LOOPS_NUM; i++) {
Long val = locSeq.getAndIncrement();
assert !resSet.contains(val) : "Element already in set : " + val;
resSet.add(val);
}
return null;
}
}, THREAD_NUM);
// Get sequence value and try to put it result set.
for (int i = 0; i < MAX_LOOPS_NUM; i++) {
Long val = locSeq.getAndIncrement();
assert !resSet.contains(val) : "Element already in set : " + val;
resSet.add(val);
if (i % 100 == 0)
info("Finished iteration 2: " + i);
}
assert resSet.size() == MAX_LOOPS_NUM * (THREAD_NUM + 2);
for (long i = initVal; i < MAX_LOOPS_NUM * (THREAD_NUM + 2) + initVal; i++) {
assert resSet.contains(i) : "Element is absent in set : " + i;
if (i % 100 == 0)
info("Finished iteration 3: " + i);
}
removeSequence(locSeqName);
}
/**
* Test sequence integrity.
*
* @param seq Sequence for test.
* @param calcVal Manually calculated value.
* @throws Exception If failed.
*/
private void integrity(IgniteAtomicSequence seq, long calcVal) throws Exception {
assert calcVal == seq.get();
getAndAdd(seq, 1);
assert calcVal + 1 == seq.get();
addAndGet(seq, 1);
assert calcVal + 2 == seq.get();
getAndIncrement(seq);
assert calcVal + BATCH_SIZE == seq.get();
incrementAndGet(seq);
assert calcVal + 4 == seq.get();
}
/**
* @param name Sequence name.
* @throws Exception If failed.
*/
private void removeSequence(String name) throws Exception {
IgniteAtomicSequence seq = grid().atomicSequence(name, 0, false);
assertNotNull(seq);
seq.close();
assertNull(grid().atomicSequence(name, 0, false));
}
}
| akuznetsov-gridgain/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/datastructures/GridCacheSequenceApiSelfAbstractTest.java | Java | apache-2.0 | 17,859 |
/*
* 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.synapse.securevault.definition;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.securevault.CipherOperationMode;
import org.apache.synapse.securevault.EncodingType;
/**
* Encapsulates the cipher related information
*/
public class CipherInformation {
/**
* Default cipher algorithm
*/
public static final String DEFAULT_ALGORITHM = "RSA";
private static final Log log = LogFactory.getLog(CipherInformation.class);
/* Cipher algorithm */
private String algorithm = DEFAULT_ALGORITHM;
/* Cipher operation mode - ENCRYPT or DECRYPT */
private CipherOperationMode cipherOperationMode;
/* Mode of operation - ECB,CCB,etc*/
private String mode;
/* Type of the input to the cipher */
private EncodingType inType;
/* Type of the output from the cipher*/
private EncodingType outType;
/* Ciphering type - asymmetric , symmetric*/
private String type;
private String provider;
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
if (algorithm == null || "".equals(algorithm)) {
log.info("Given algorithm is null, using a default one : RSA");
}
this.algorithm = algorithm;
}
public CipherOperationMode getCipherOperationMode() {
return cipherOperationMode;
}
public void setCipherOperationMode(CipherOperationMode operationMode) {
this.cipherOperationMode = operationMode;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public EncodingType getInType() {
return inType;
}
public void setInType(EncodingType inType) {
this.inType = inType;
}
public EncodingType getOutType() {
return outType;
}
public void setOutType(EncodingType outType) {
this.outType = outType;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
}
| maheshika/wso2-synapse | modules/securevault/src/main/java/org/apache/synapse/securevault/definition/CipherInformation.java | Java | apache-2.0 | 3,110 |
// 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.support.events;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public interface WebDriverEventListener {
/**
* Called before {@link org.openqa.selenium.WebDriver#get get(String url)} respectively
* {@link org.openqa.selenium.WebDriver.Navigation#to navigate().to(String url)}.
*
* @param url URL
* @param driver WebDriver
*/
void beforeNavigateTo(String url, WebDriver driver);
/**
* Called after {@link org.openqa.selenium.WebDriver#get get(String url)} respectively
* {@link org.openqa.selenium.WebDriver.Navigation#to navigate().to(String url)}. Not called, if an
* exception is thrown.
*
* @param url URL
* @param driver WebDriver
*/
void afterNavigateTo(String url, WebDriver driver);
/**
* Called before {@link org.openqa.selenium.WebDriver.Navigation#back navigate().back()}.
*
* @param driver WebDriver
*/
void beforeNavigateBack(WebDriver driver);
/**
* Called after {@link org.openqa.selenium.WebDriver.Navigation navigate().back()}. Not called, if an
* exception is thrown.
*
* @param driver WebDriver
*/
void afterNavigateBack(WebDriver driver);
/**
* Called before {@link org.openqa.selenium.WebDriver.Navigation#forward navigate().forward()}.
*
* @param driver WebDriver
*/
void beforeNavigateForward(WebDriver driver);
/**
* Called after {@link org.openqa.selenium.WebDriver.Navigation#forward navigate().forward()}. Not called,
* if an exception is thrown.
*
* @param driver WebDriver
*/
void afterNavigateForward(WebDriver driver);
/**
* Called before {@link org.openqa.selenium.WebDriver.Navigation#refresh navigate().refresh()}.
*
* @param driver WebDriver
*/
void beforeNavigateRefresh(WebDriver driver);
/**
* Called after {@link org.openqa.selenium.WebDriver.Navigation#refresh navigate().refresh()}. Not called,
* if an exception is thrown.
*
* @param driver WebDriver
*/
void afterNavigateRefresh(WebDriver driver);
/**
* Called before {@link WebDriver#findElement WebDriver.findElement(...)}, or
* {@link WebDriver#findElements WebDriver.findElements(...)}, or {@link WebElement#findElement
* WebElement.findElement(...)}, or {@link WebElement#findElement WebElement.findElements(...)}.
*
* @param element will be <code>null</code>, if a find method of <code>WebDriver</code> is called.
* @param by locator being used
* @param driver WebDriver
*/
void beforeFindBy(By by, WebElement element, WebDriver driver);
/**
* Called after {@link WebDriver#findElement WebDriver.findElement(...)}, or
* {@link WebDriver#findElements WebDriver.findElements(...)}, or {@link WebElement#findElement
* WebElement.findElement(...)}, or {@link WebElement#findElement WebElement.findElements(...)}.
*
* @param element will be <code>null</code>, if a find method of <code>WebDriver</code> is called.
* @param by locator being used
* @param driver WebDriver
*/
void afterFindBy(By by, WebElement element, WebDriver driver);
/**
* Called before {@link WebElement#click WebElement.click()}.
*
* @param driver WebDriver
* @param element the WebElement being used for the action
*/
void beforeClickOn(WebElement element, WebDriver driver);
/**
* Called after {@link WebElement#click WebElement.click()}. Not called, if an exception is
* thrown.
*
* @param driver WebDriver
* @param element the WebElement being used for the action
*/
void afterClickOn(WebElement element, WebDriver driver);
/**
* Called before {@link WebElement#clear WebElement.clear()}, {@link WebElement#sendKeys
* WebElement.sendKeys(...)}.
*
* @param driver WebDriver
* @param element the WebElement being used for the action
*/
void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend);
/**
* Called after {@link WebElement#clear WebElement.clear()}, {@link WebElement#sendKeys
* WebElement.sendKeys(...)}}. Not called, if an exception is thrown.
*
* @param driver WebDriver
* @param element the WebElement being used for the action
*/
void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend);
/**
* Called before {@link org.openqa.selenium.remote.RemoteWebDriver#executeScript(java.lang.String, java.lang.Object[]) }
*
* @param driver WebDriver
* @param script the script to be executed
*/
// Previously: Called before {@link WebDriver#executeScript(String)}
// See the same issue below.
void beforeScript(String script, WebDriver driver);
/**
* Called after {@link org.openqa.selenium.remote.RemoteWebDriver#executeScript(java.lang.String, java.lang.Object[]) }.
* Not called if an exception is thrown
*
* @param driver WebDriver
* @param script the script that was executed
*/
// Previously: Called after {@link WebDriver#executeScript(String)}. Not called if an exception is thrown
// So someone should check if this is right. There is no executeScript method
// in WebDriver, but there is in several other places, like this one
void afterScript(String script, WebDriver driver);
/**
* Called whenever an exception would be thrown.
*
* @param driver WebDriver
* @param throwable the exception that will be thrown
*/
void onException(Throwable throwable, WebDriver driver);
}
| alb-i986/selenium | java/client/src/org/openqa/selenium/support/events/WebDriverEventListener.java | Java | apache-2.0 | 6,294 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.