repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
zuoyebushiwo/openfire-my-study | src/java/org/jivesoftware/openfire/muc/spi/package-info.java | 99 | /**
* Implementation of Multi-User Chat (XEP-0045).
*/
package org.jivesoftware.openfire.muc.spi; | apache-2.0 |
deciament/presto | presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java | 15098 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.gen;
import com.facebook.presto.byteCode.ByteCodeBlock;
import com.facebook.presto.byteCode.ByteCodeNode;
import com.facebook.presto.byteCode.ClassDefinition;
import com.facebook.presto.byteCode.MethodDefinition;
import com.facebook.presto.byteCode.Parameter;
import com.facebook.presto.byteCode.ParameterizedType;
import com.facebook.presto.byteCode.Scope;
import com.facebook.presto.byteCode.Variable;
import com.facebook.presto.byteCode.control.ForLoop;
import com.facebook.presto.byteCode.control.IfStatement;
import com.facebook.presto.byteCode.instruction.LabelNode;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.operator.PageProcessor;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.ConstantExpression;
import com.facebook.presto.sql.relational.Expressions;
import com.facebook.presto.sql.relational.InputReferenceExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.facebook.presto.sql.relational.RowExpressionVisitor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import io.airlift.slice.Slice;
import java.util.List;
import java.util.TreeSet;
import static com.facebook.presto.byteCode.Access.PUBLIC;
import static com.facebook.presto.byteCode.Access.a;
import static com.facebook.presto.byteCode.OpCode.NOP;
import static com.facebook.presto.byteCode.Parameter.arg;
import static com.facebook.presto.byteCode.ParameterizedType.type;
import static com.facebook.presto.sql.gen.ByteCodeUtils.generateWrite;
import static com.facebook.presto.sql.gen.ByteCodeUtils.loadConstant;
import static java.lang.String.format;
import static java.util.Collections.nCopies;
public class PageProcessorCompiler
implements BodyCompiler<PageProcessor>
{
private final Metadata metadata;
public PageProcessorCompiler(Metadata metadata)
{
this.metadata = metadata;
}
@Override
public void generateMethods(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter, List<RowExpression> projections)
{
generateProcessMethod(classDefinition, filter, projections);
generateFilterMethod(classDefinition, callSiteBinder, filter);
for (int i = 0; i < projections.size(); i++) {
generateProjectMethod(classDefinition, callSiteBinder, "project_" + i, projections.get(i));
}
}
private void generateProcessMethod(ClassDefinition classDefinition, RowExpression filter, List<RowExpression> projections)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter start = arg("start", int.class);
Parameter end = arg("end", int.class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "process", type(int.class), session, page, start, end, pageBuilder);
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
Variable position = scope.declareVariable(int.class, "position");
method.getBody()
.comment("int position = start;")
.getVariable(start)
.putVariable(position);
List<Integer> allInputChannels = getInputChannels(Iterables.concat(projections, ImmutableList.of(filter)));
for (int channel : allInputChannels) {
Variable blockVariable = scope.declareVariable(Block.class, "block_" + channel);
method.getBody()
.comment("Block %s = page.getBlock(%s);", blockVariable.getName(), channel)
.getVariable(page)
.push(channel)
.invokeVirtual(Page.class, "getBlock", Block.class, int.class)
.putVariable(blockVariable);
}
//
// for loop loop body
//
LabelNode done = new LabelNode("done");
ByteCodeBlock loopBody = new ByteCodeBlock();
ForLoop loop = new ForLoop()
.initialize(NOP)
.condition(new ByteCodeBlock()
.comment("position < end")
.getVariable(position)
.getVariable(end)
.invokeStatic(CompilerOperations.class, "lessThan", boolean.class, int.class, int.class)
)
.update(new ByteCodeBlock()
.comment("position++")
.incrementVariable(position, (byte) 1))
.body(loopBody);
loopBody.comment("if (pageBuilder.isFull()) break;")
.getVariable(pageBuilder)
.invokeVirtual(PageBuilder.class, "isFull", boolean.class)
.ifTrueGoto(done);
// if (filter(cursor))
IfStatement filterBlock = new IfStatement();
filterBlock.condition()
.append(thisVariable)
.getVariable(session)
.append(pushBlockVariables(scope, getInputChannels(filter)))
.getVariable(position)
.invokeVirtual(classDefinition.getType(),
"filter",
type(boolean.class),
ImmutableList.<ParameterizedType>builder()
.add(type(ConnectorSession.class))
.addAll(nCopies(getInputChannels(filter).size(), type(Block.class)))
.add(type(int.class))
.build());
filterBlock.ifTrue()
.append(pageBuilder)
.invokeVirtual(PageBuilder.class, "declarePosition", void.class);
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
List<Integer> inputChannels = getInputChannels(projections.get(projectionIndex));
filterBlock.ifTrue()
.append(thisVariable)
.append(session)
.append(pushBlockVariables(scope, inputChannels))
.getVariable(position);
filterBlock.ifTrue()
.comment("pageBuilder.getBlockBuilder(%d)", projectionIndex)
.append(pageBuilder)
.push(projectionIndex)
.invokeVirtual(PageBuilder.class, "getBlockBuilder", BlockBuilder.class, int.class);
filterBlock.ifTrue()
.comment("project_%d(session, block_%s, position, blockBuilder)", projectionIndex, inputChannels)
.invokeVirtual(classDefinition.getType(),
"project_" + projectionIndex,
type(void.class),
ImmutableList.<ParameterizedType>builder()
.add(type(ConnectorSession.class))
.addAll(nCopies(inputChannels.size(), type(Block.class)))
.add(type(int.class))
.add(type(BlockBuilder.class))
.build());
}
loopBody.append(filterBlock);
method.getBody()
.append(loop)
.visitLabel(done)
.comment("return position;")
.getVariable(position)
.retInt();
}
private void generateFilterMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> blocks = toBlockParameters(getInputChannels(filter));
Parameter position = arg("position", int.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(boolean.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(blocks)
.add(position)
.build());
method.comment("Filter: %s", filter.toString());
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable(type(boolean.class), "wasNull");
ByteCodeExpressionVisitor visitor = new ByteCodeExpressionVisitor(
callSiteBinder,
fieldReferenceCompiler(callSiteBinder, position, wasNullVariable),
metadata.getFunctionRegistry());
ByteCodeNode body = filter.accept(visitor, scope);
LabelNode end = new LabelNode("end");
method
.getBody()
.comment("boolean wasNull = false;")
.putVariable(wasNullVariable, false)
.append(body)
.getVariable(wasNullVariable)
.ifFalseGoto(end)
.pop(boolean.class)
.push(false)
.visitLabel(end)
.retBoolean();
}
private void generateProjectMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, String methodName, RowExpression projection)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> inputs = toBlockParameters(getInputChannels(projection));
Parameter position = arg("position", int.class);
Parameter output = arg("output", BlockBuilder.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
methodName,
type(void.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(inputs)
.add(position)
.add(output)
.build());
method.comment("Projection: %s", projection.toString());
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable(type(boolean.class), "wasNull");
ByteCodeBlock body = method.getBody()
.comment("boolean wasNull = false;")
.putVariable(wasNullVariable, false);
ByteCodeExpressionVisitor visitor = new ByteCodeExpressionVisitor(callSiteBinder, fieldReferenceCompiler(callSiteBinder, position, wasNullVariable), metadata.getFunctionRegistry());
body.getVariable(output)
.comment("evaluate projection: " + projection.toString())
.append(projection.accept(visitor, scope))
.append(generateWrite(callSiteBinder, scope, wasNullVariable, projection.getType()))
.ret();
}
private static List<Integer> getInputChannels(Iterable<RowExpression> expressions)
{
TreeSet<Integer> channels = new TreeSet<>();
for (RowExpression expression : Expressions.subExpressions(expressions)) {
if (expression instanceof InputReferenceExpression) {
channels.add(((InputReferenceExpression) expression).getField());
}
}
return ImmutableList.copyOf(channels);
}
private static List<Integer> getInputChannels(RowExpression expression)
{
return getInputChannels(ImmutableList.of(expression));
}
private static List<Parameter> toBlockParameters(List<Integer> inputChannels)
{
ImmutableList.Builder<Parameter> parameters = ImmutableList.builder();
for (int channel : inputChannels) {
parameters.add(arg("block_" + channel, Block.class));
}
return parameters.build();
}
private static ByteCodeNode pushBlockVariables(Scope scope, List<Integer> inputs)
{
ByteCodeBlock block = new ByteCodeBlock();
for (int channel : inputs) {
block.append(scope.getVariable("block_" + channel));
}
return block;
}
private RowExpressionVisitor<Scope, ByteCodeNode> fieldReferenceCompiler(final CallSiteBinder callSiteBinder, final Variable positionVariable, final Variable wasNullVariable)
{
return new RowExpressionVisitor<Scope, ByteCodeNode>()
{
@Override
public ByteCodeNode visitInputReference(InputReferenceExpression node, Scope scope)
{
int field = node.getField();
Type type = node.getType();
Variable block = scope.getVariable("block_" + field);
Class<?> javaType = type.getJavaType();
if (!javaType.isPrimitive() && javaType != Slice.class) {
javaType = Object.class;
}
IfStatement ifStatement = new IfStatement();
ifStatement.condition()
.setDescription(format("block_%d.get%s()", field, type))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Block.class, "isNull", boolean.class, int.class);
ifStatement.ifTrue()
.putVariable(wasNullVariable, true)
.pushJavaDefault(javaType);
String methodName = "get" + Primitives.wrap(javaType).getSimpleName();
ifStatement.ifFalse()
.append(loadConstant(callSiteBinder.bind(type, Type.class)))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Type.class, methodName, javaType, Block.class, int.class);
return ifStatement;
}
@Override
public ByteCodeNode visitCall(CallExpression call, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
@Override
public ByteCodeNode visitConstant(ConstantExpression literal, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
};
}
}
| apache-2.0 |
jk1/intellij-community | python/src/com/jetbrains/python/inspections/quickfix/AddIgnoredIdentifierQuickFix.java | 2763 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.inspections.quickfix;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ex.InspectionProfileModifiableModelKt;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.inspections.unresolvedReference.PyUnresolvedReferencesInspection;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class AddIgnoredIdentifierQuickFix implements LocalQuickFix, LowPriorityAction {
public static final String END_WILDCARD = ".*";
@NotNull private final QualifiedName myIdentifier;
private final boolean myIgnoreAllAttributes;
public AddIgnoredIdentifierQuickFix(@NotNull QualifiedName identifier, boolean ignoreAllAttributes) {
myIdentifier = identifier;
myIgnoreAllAttributes = ignoreAllAttributes;
}
@NotNull
@Override
public String getName() {
if (myIgnoreAllAttributes) {
return "Mark all unresolved attributes of '" + myIdentifier + "' as ignored";
}
else {
return "Ignore unresolved reference '" + myIdentifier + "'";
}
}
@NotNull
@Override
public String getFamilyName() {
return "Ignore unresolved reference";
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final PsiElement context = descriptor.getPsiElement();
InspectionProfileModifiableModelKt.modifyAndCommitProjectProfile(project, model -> {
PyUnresolvedReferencesInspection inspection =
(PyUnresolvedReferencesInspection)model.getUnwrappedTool(PyUnresolvedReferencesInspection.class.getSimpleName(), context);
String name = myIdentifier.toString();
if (myIgnoreAllAttributes) {
name += END_WILDCARD;
}
assert inspection != null;
if (!inspection.ignoredIdentifiers.contains(name)) {
inspection.ignoredIdentifiers.add(name);
}
});
}
}
| apache-2.0 |
smmribeiro/intellij-community | java/java-analysis-api/src/com/intellij/lang/jvm/actions/CreateConstructorRequest.java | 259 | // 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.intellij.lang.jvm.actions;
public interface CreateConstructorRequest extends CreateExecutableRequest {
}
| apache-2.0 |
markyao/disconf | disconf-web/src/main/java/com/baidu/disconf/web/service/user/vo/VisitorVo.java | 1901 | package com.baidu.disconf.web.service.user.vo;
public class VisitorVo {
private Long id;
private String name;
private String role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "VisitorVo [id=" + id + ", name=" + name + ", role=" + role + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((role == null) ? 0 : role.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
VisitorVo other = (VisitorVo) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (role == null) {
if (other.role != null) {
return false;
}
} else if (!role.equals(other.role)) {
return false;
}
return true;
}
}
| apache-2.0 |
apavlenko/opencv | samples/android/15-puzzle/src/org/opencv/samples/puzzle15/Puzzle15Processor.java | 6624 | package org.opencv.samples.puzzle15;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.core.Point;
import org.opencv.imgproc.Imgproc;
import android.util.Log;
/**
* This class is a controller for puzzle game.
* It converts the image from Camera into the shuffled image
*/
public class Puzzle15Processor {
private static final int GRID_SIZE = 4;
private static final int GRID_AREA = GRID_SIZE * GRID_SIZE;
private static final int GRID_EMPTY_INDEX = GRID_AREA - 1;
private static final String TAG = "Puzzle15Processor";
private static final Scalar GRID_EMPTY_COLOR = new Scalar(0x33, 0x33, 0x33, 0xFF);
private int[] mIndexes;
private int[] mTextWidths;
private int[] mTextHeights;
private Mat mRgba15;
private Mat[] mCells15;
private boolean mShowTileNumbers = true;
public Puzzle15Processor() {
mTextWidths = new int[GRID_AREA];
mTextHeights = new int[GRID_AREA];
mIndexes = new int [GRID_AREA];
for (int i = 0; i < GRID_AREA; i++)
mIndexes[i] = i;
}
/* this method is intended to make processor prepared for a new game */
public synchronized void prepareNewGame() {
do {
shuffle(mIndexes);
} while (!isPuzzleSolvable());
}
/* This method is to make the processor know the size of the frames that
* will be delivered via puzzleFrame.
* If the frames will be different size - then the result is unpredictable
*/
public synchronized void prepareGameSize(int width, int height) {
mRgba15 = new Mat(height, width, CvType.CV_8UC4);
mCells15 = new Mat[GRID_AREA];
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
int k = i * GRID_SIZE + j;
mCells15[k] = mRgba15.submat(i * height / GRID_SIZE, (i + 1) * height / GRID_SIZE, j * width / GRID_SIZE, (j + 1) * width / GRID_SIZE);
}
}
for (int i = 0; i < GRID_AREA; i++) {
Size s = Imgproc.getTextSize(Integer.toString(i + 1), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, 2, null);
mTextHeights[i] = (int) s.height;
mTextWidths[i] = (int) s.width;
}
}
/* this method to be called from the outside. it processes the frame and shuffles
* the tiles as specified by mIndexes array
*/
public synchronized Mat puzzleFrame(Mat inputPicture) {
Mat[] cells = new Mat[GRID_AREA];
int rows = inputPicture.rows();
int cols = inputPicture.cols();
rows = rows - rows%4;
cols = cols - cols%4;
for (int i = 0; i < GRID_SIZE; i++) {
for (int j = 0; j < GRID_SIZE; j++) {
int k = i * GRID_SIZE + j;
cells[k] = inputPicture.submat(i * inputPicture.rows() / GRID_SIZE, (i + 1) * inputPicture.rows() / GRID_SIZE, j * inputPicture.cols()/ GRID_SIZE, (j + 1) * inputPicture.cols() / GRID_SIZE);
}
}
rows = rows - rows%4;
cols = cols - cols%4;
// copy shuffled tiles
for (int i = 0; i < GRID_AREA; i++) {
int idx = mIndexes[i];
if (idx == GRID_EMPTY_INDEX)
mCells15[i].setTo(GRID_EMPTY_COLOR);
else {
cells[idx].copyTo(mCells15[i]);
if (mShowTileNumbers) {
Imgproc.putText(mCells15[i], Integer.toString(1 + idx), new Point((cols / GRID_SIZE - mTextWidths[idx]) / 2,
(rows / GRID_SIZE + mTextHeights[idx]) / 2), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, new Scalar(255, 0, 0, 255), 2);
}
}
}
for (int i = 0; i < GRID_AREA; i++)
cells[i].release();
drawGrid(cols, rows, mRgba15);
return mRgba15;
}
public void toggleTileNumbers() {
mShowTileNumbers = !mShowTileNumbers;
}
public void deliverTouchEvent(int x, int y) {
int rows = mRgba15.rows();
int cols = mRgba15.cols();
int row = (int) Math.floor(y * GRID_SIZE / rows);
int col = (int) Math.floor(x * GRID_SIZE / cols);
if (row < 0 || row >= GRID_SIZE || col < 0 || col >= GRID_SIZE) {
Log.e(TAG, "It is not expected to get touch event outside of picture");
return ;
}
int idx = row * GRID_SIZE + col;
int idxtoswap = -1;
// left
if (idxtoswap < 0 && col > 0)
if (mIndexes[idx - 1] == GRID_EMPTY_INDEX)
idxtoswap = idx - 1;
// right
if (idxtoswap < 0 && col < GRID_SIZE - 1)
if (mIndexes[idx + 1] == GRID_EMPTY_INDEX)
idxtoswap = idx + 1;
// top
if (idxtoswap < 0 && row > 0)
if (mIndexes[idx - GRID_SIZE] == GRID_EMPTY_INDEX)
idxtoswap = idx - GRID_SIZE;
// bottom
if (idxtoswap < 0 && row < GRID_SIZE - 1)
if (mIndexes[idx + GRID_SIZE] == GRID_EMPTY_INDEX)
idxtoswap = idx + GRID_SIZE;
// swap
if (idxtoswap >= 0) {
synchronized (this) {
int touched = mIndexes[idx];
mIndexes[idx] = mIndexes[idxtoswap];
mIndexes[idxtoswap] = touched;
}
}
}
private void drawGrid(int cols, int rows, Mat drawMat) {
for (int i = 1; i < GRID_SIZE; i++) {
Imgproc.line(drawMat, new Point(0, i * rows / GRID_SIZE), new Point(cols, i * rows / GRID_SIZE), new Scalar(0, 255, 0, 255), 3);
Imgproc.line(drawMat, new Point(i * cols / GRID_SIZE, 0), new Point(i * cols / GRID_SIZE, rows), new Scalar(0, 255, 0, 255), 3);
}
}
private static void shuffle(int[] array) {
for (int i = array.length; i > 1; i--) {
int temp = array[i - 1];
int randIx = (int) (Math.random() * i);
array[i - 1] = array[randIx];
array[randIx] = temp;
}
}
private boolean isPuzzleSolvable() {
int sum = 0;
for (int i = 0; i < GRID_AREA; i++) {
if (mIndexes[i] == GRID_EMPTY_INDEX)
sum += (i / GRID_SIZE) + 1;
else {
int smaller = 0;
for (int j = i + 1; j < GRID_AREA; j++) {
if (mIndexes[j] < mIndexes[i])
smaller++;
}
sum += smaller;
}
}
return sum % 2 == 0;
}
}
| bsd-3-clause |
kumarrus/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/HsqlList.java | 2168 | /* Copyright (c) 2001-2009, The HSQL Development Group
* 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 HSQL Development Group 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* 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 org.hsqldb_voltpatches.lib;
/**
* This should be used as the datatype for parameters and instance variables
* instead of HsqlArrayList or HsqlLinkedList to allow interchangable use of the
* two.
*
* @author dnordahl@users
* @version 1.7.2
* @since 1.7.2
*/
public interface HsqlList extends Collection {
void add(int index, Object element);
boolean add(Object element);
Object get(int index);
Object remove(int index);
Object set(int index, Object element);
boolean isEmpty();
int size();
Iterator iterator();
}
| agpl-3.0 |
dulvac/sling | tooling/maven/slingstart-maven-plugin/src/main/java/org/apache/sling/maven/slingstart/run/StopMojo.java | 3583 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sling.maven.slingstart.run;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
/**
* Stops the running launchpad instances.
*
*/
@Mojo(
name = "stop",
defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST,
threadSafe = true
)
public class StopMojo extends StartMojo {
@Override
public void execute() throws MojoExecutionException {
if (this.skipLaunchpad) {
this.getLog().info("Executing of the stop-multiple launchpad mojo is disabled by configuration.");
return;
}
// read configurations
final Properties launchpadConfigProps = new Properties();
Reader reader = null;
try {
reader = new FileReader(this.systemPropertiesFile);
launchpadConfigProps.load(reader);
} catch ( final IOException ioe) {
throw new MojoExecutionException("Unable to read launchpad runner configuration properties.", ioe);
} finally {
IOUtils.closeQuietly(reader);
}
final int instances = Integer.valueOf(launchpadConfigProps.getProperty("launchpad.instances"));
final List<ProcessDescription> configurations = new ArrayList<ProcessDescription>();
for(int i=1;i<=instances;i++) {
final String id = launchpadConfigProps.getProperty("launchpad.instance.id." + String.valueOf(i));
final ProcessDescription config = ProcessDescriptionProvider.getInstance().getRunConfiguration(id);
if ( config == null ) {
getLog().warn("No launchpad configuration found for instance " + id);
} else {
configurations.add(config);
}
}
if (configurations.size() > 0) {
getLog().info(new StringBuilder("Stopping ").append(configurations.size()).append(" Launchpad instances").toString());
for (final ProcessDescription cfg : configurations) {
try {
LauncherCallable.stop(this.getLog(), cfg);
ProcessDescriptionProvider.getInstance().removeRunConfiguration(cfg.getId());
} catch (Exception e) {
throw new MojoExecutionException("Could not stop launchpad " + cfg.getId(), e);
}
}
} else {
getLog().warn("No stored configuration file was found at " + this.systemPropertiesFile + " - no Launchapd will be stopped");
}
}
}
| apache-2.0 |
GlenRSmith/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/UpdateProcessAction.java | 6629 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.ml.action;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.tasks.BaseTasksResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.StatusToXContentObject;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.ml.job.config.JobUpdate;
import org.elasticsearch.xpack.core.ml.job.config.MlFilter;
import org.elasticsearch.xpack.core.ml.job.config.ModelPlotConfig;
import org.elasticsearch.xpack.core.ml.job.config.PerPartitionCategorizationConfig;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
public class UpdateProcessAction extends ActionType<UpdateProcessAction.Response> {
public static final UpdateProcessAction INSTANCE = new UpdateProcessAction();
public static final String NAME = "cluster:internal/xpack/ml/job/update/process";
private UpdateProcessAction() {
super(NAME, UpdateProcessAction.Response::new);
}
public static class Response extends BaseTasksResponse implements StatusToXContentObject, Writeable {
private final boolean isUpdated;
public Response() {
super(null, null);
this.isUpdated = true;
}
public Response(StreamInput in) throws IOException {
super(in);
isUpdated = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(isUpdated);
}
public boolean isUpdated() {
return isUpdated;
}
@Override
public RestStatus status() {
return RestStatus.ACCEPTED;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("updated", isUpdated);
builder.endObject();
return builder;
}
@Override
public int hashCode() {
return Objects.hashCode(isUpdated);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Response other = (Response) obj;
return this.isUpdated == other.isUpdated;
}
}
public static class Request extends JobTaskRequest<Request> {
private ModelPlotConfig modelPlotConfig;
private PerPartitionCategorizationConfig perPartitionCategorizationConfig;
private List<JobUpdate.DetectorUpdate> detectorUpdates;
private MlFilter filter;
private boolean updateScheduledEvents = false;
public Request(StreamInput in) throws IOException {
super(in);
modelPlotConfig = in.readOptionalWriteable(ModelPlotConfig::new);
perPartitionCategorizationConfig = in.readOptionalWriteable(PerPartitionCategorizationConfig::new);
if (in.readBoolean()) {
detectorUpdates = in.readList(JobUpdate.DetectorUpdate::new);
}
filter = in.readOptionalWriteable(MlFilter::new);
updateScheduledEvents = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalWriteable(modelPlotConfig);
out.writeOptionalWriteable(perPartitionCategorizationConfig);
boolean hasDetectorUpdates = detectorUpdates != null;
out.writeBoolean(hasDetectorUpdates);
if (hasDetectorUpdates) {
out.writeList(detectorUpdates);
}
out.writeOptionalWriteable(filter);
out.writeBoolean(updateScheduledEvents);
}
public Request(
String jobId,
ModelPlotConfig modelPlotConfig,
PerPartitionCategorizationConfig perPartitionCategorizationConfig,
List<JobUpdate.DetectorUpdate> detectorUpdates,
MlFilter filter,
boolean updateScheduledEvents
) {
super(jobId);
this.modelPlotConfig = modelPlotConfig;
this.perPartitionCategorizationConfig = perPartitionCategorizationConfig;
this.detectorUpdates = detectorUpdates;
this.filter = filter;
this.updateScheduledEvents = updateScheduledEvents;
}
public ModelPlotConfig getModelPlotConfig() {
return modelPlotConfig;
}
public PerPartitionCategorizationConfig getPerPartitionCategorizationConfig() {
return perPartitionCategorizationConfig;
}
public List<JobUpdate.DetectorUpdate> getDetectorUpdates() {
return detectorUpdates;
}
public MlFilter getFilter() {
return filter;
}
public boolean isUpdateScheduledEvents() {
return updateScheduledEvents;
}
@Override
public int hashCode() {
return Objects.hash(
getJobId(),
modelPlotConfig,
perPartitionCategorizationConfig,
detectorUpdates,
filter,
updateScheduledEvents
);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Request other = (Request) obj;
return Objects.equals(getJobId(), other.getJobId())
&& Objects.equals(modelPlotConfig, other.modelPlotConfig)
&& Objects.equals(perPartitionCategorizationConfig, other.perPartitionCategorizationConfig)
&& Objects.equals(detectorUpdates, other.detectorUpdates)
&& Objects.equals(filter, other.filter)
&& Objects.equals(updateScheduledEvents, other.updateScheduledEvents);
}
}
}
| apache-2.0 |
subhrajyotim/camunda-bpm-platform | qa/integration-tests-engine/src/test/java/org/camunda/bpm/integrationtest/deployment/war/TestWarDeployment.java | 1697 | /**
* Copyright (C) 2011, 2012 camunda services GmbH
*
* 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.camunda.bpm.integrationtest.deployment.war;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.integrationtest.util.AbstractFoxPlatformIntegrationTest;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class TestWarDeployment extends AbstractFoxPlatformIntegrationTest {
@Deployment
public static WebArchive processArchive() {
return initWebArchiveDeployment()
.addAsResource("org/camunda/bpm/integrationtest/testDeployProcessArchive.bpmn20.xml");
}
@Test
public void testDeployProcessArchive() {
Assert.assertNotNull(processEngine);
RepositoryService repositoryService = processEngine.getRepositoryService();
long count = repositoryService.createProcessDefinitionQuery()
.processDefinitionKey("testDeployProcessArchive")
.count();
Assert.assertEquals(1, count);
}
}
| apache-2.0 |
GlenRSmith/elasticsearch | server/src/main/java/org/elasticsearch/threadpool/ThreadPoolStats.java | 5488 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.threadpool;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.ToXContentFragment;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ThreadPoolStats implements Writeable, ToXContentFragment, Iterable<ThreadPoolStats.Stats> {
public static class Stats implements Writeable, ToXContentFragment, Comparable<Stats> {
private final String name;
private final int threads;
private final int queue;
private final int active;
private final long rejected;
private final int largest;
private final long completed;
public Stats(String name, int threads, int queue, int active, long rejected, int largest, long completed) {
this.name = name;
this.threads = threads;
this.queue = queue;
this.active = active;
this.rejected = rejected;
this.largest = largest;
this.completed = completed;
}
public Stats(StreamInput in) throws IOException {
name = in.readString();
threads = in.readInt();
queue = in.readInt();
active = in.readInt();
rejected = in.readLong();
largest = in.readInt();
completed = in.readLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeInt(threads);
out.writeInt(queue);
out.writeInt(active);
out.writeLong(rejected);
out.writeInt(largest);
out.writeLong(completed);
}
public String getName() {
return this.name;
}
public int getThreads() {
return this.threads;
}
public int getQueue() {
return this.queue;
}
public int getActive() {
return this.active;
}
public long getRejected() {
return rejected;
}
public int getLargest() {
return largest;
}
public long getCompleted() {
return this.completed;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
if (threads != -1) {
builder.field(Fields.THREADS, threads);
}
if (queue != -1) {
builder.field(Fields.QUEUE, queue);
}
if (active != -1) {
builder.field(Fields.ACTIVE, active);
}
if (rejected != -1) {
builder.field(Fields.REJECTED, rejected);
}
if (largest != -1) {
builder.field(Fields.LARGEST, largest);
}
if (completed != -1) {
builder.field(Fields.COMPLETED, completed);
}
builder.endObject();
return builder;
}
@Override
public int compareTo(Stats other) {
if ((getName() == null) && (other.getName() == null)) {
return 0;
} else if ((getName() != null) && (other.getName() == null)) {
return 1;
} else if (getName() == null) {
return -1;
} else {
int compare = getName().compareTo(other.getName());
if (compare == 0) {
compare = Integer.compare(getThreads(), other.getThreads());
}
return compare;
}
}
}
private List<Stats> stats;
public ThreadPoolStats(List<Stats> stats) {
Collections.sort(stats);
this.stats = stats;
}
public ThreadPoolStats(StreamInput in) throws IOException {
stats = in.readList(Stats::new);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeList(stats);
}
@Override
public Iterator<Stats> iterator() {
return stats.iterator();
}
static final class Fields {
static final String THREAD_POOL = "thread_pool";
static final String THREADS = "threads";
static final String QUEUE = "queue";
static final String ACTIVE = "active";
static final String REJECTED = "rejected";
static final String LARGEST = "largest";
static final String COMPLETED = "completed";
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject(Fields.THREAD_POOL);
for (Stats stat : stats) {
stat.toXContent(builder, params);
}
builder.endObject();
return builder;
}
}
| apache-2.0 |
vongosling/cglib-ext | src/proxy/net/sf/cglib/proxy/CallbackGenerator.java | 1311 | /*
* Copyright 2003,2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.cglib.proxy;
import java.util.List;
import net.sf.cglib.core.*;
interface CallbackGenerator
{
void generate(ClassEmitter ce, Context context, List methods) throws Exception;
void generateStatic(CodeEmitter e, Context context, List methods) throws Exception;
interface Context
{
ClassLoader getClassLoader();
CodeEmitter beginMethod(ClassEmitter ce, MethodInfo method);
int getOriginalModifiers(MethodInfo method);
int getIndex(MethodInfo method);
void emitCallback(CodeEmitter ce, int index);
Signature getImplSignature(MethodInfo method);
void emitInvoke(CodeEmitter e, MethodInfo method);
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/drools-master/drools-workbench-models/drools-workbench-models-datamodel-api/src/main/java/org/drools/workbench/models/datamodel/rule/ExpressionUnboundFact.java | 1906 | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.workbench.models.datamodel.rule;
public class ExpressionUnboundFact extends ExpressionPart {
private String factType;
public ExpressionUnboundFact() {
}
public ExpressionUnboundFact( String factType ) {
super( factType,
factType,
factType );
this.factType = factType;
}
public String getFactType() {
return factType;
}
@Override
public void accept( ExpressionVisitor visitor ) {
visitor.visit( this );
}
@Override
public boolean equals( Object o ) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
if ( !super.equals( o ) ) {
return false;
}
ExpressionUnboundFact that = (ExpressionUnboundFact) o;
if ( factType != null ? !factType.equals( that.factType ) : that.factType != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = ~~result;
result = 31 * result + ( factType != null ? factType.hashCode() : 0 );
result = ~~result;
return result;
}
}
| mit |
cymcsg/UltimateAndroid | deprecated/UltimateAndroidGradle/demoofui/src/main/java/com/marshalchen/common/demoofui/observablescrollview/ToolbarControlWebViewActivity.java | 5205 | /*
* Copyright 2014 Soichiro Kashima
*
* 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.marshalchen.common.demoofui.observablescrollview;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ObservableWebView;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.marshalchen.common.demoofui.R;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
public class ToolbarControlWebViewActivity extends ActionBarActivity {
private View mHeaderView;
private View mToolbarView;
private ObservableScrollView mScrollView;
private boolean mFirstScroll;
private boolean mDragging;
private int mBaseTranslationY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.observable_scroll_view_activity_toolbarcontrolwebview);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
mHeaderView = findViewById(R.id.header);
ViewCompat.setElevation(mHeaderView, getResources().getDimension(R.dimen.toolbar_elevation));
mToolbarView = findViewById(R.id.toolbar);
mScrollView = (ObservableScrollView) findViewById(R.id.scroll);
mScrollView.setScrollViewCallbacks(mScrollViewScrollCallbacks);
ObservableWebView mWebView = (ObservableWebView) findViewById(R.id.web);
mWebView.setScrollViewCallbacks(mWebViewScrollCallbacks);
mWebView.loadUrl("file:///android_asset/lipsum.html");
}
private ObservableScrollViewCallbacks mScrollViewScrollCallbacks = new ObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
if (mDragging) {
int toolbarHeight = mToolbarView.getHeight();
if (mFirstScroll) {
mFirstScroll = false;
float currentHeaderTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (-toolbarHeight < currentHeaderTranslationY && toolbarHeight < scrollY) {
mBaseTranslationY = scrollY;
}
}
int headerTranslationY = Math.min(0, Math.max(-toolbarHeight, -(scrollY - mBaseTranslationY)));
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewHelper.setTranslationY(mHeaderView, headerTranslationY);
}
}
@Override
public void onDownMotionEvent() {
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
mDragging = false;
mBaseTranslationY = 0;
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
int toolbarHeight = mToolbarView.getHeight();
if (scrollState == ScrollState.UP) {
if (toolbarHeight < mScrollView.getCurrentScrollY()) {
if (headerTranslationY != -toolbarHeight) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(-toolbarHeight).setDuration(200).start();
}
}
} else if (scrollState == ScrollState.DOWN) {
if (toolbarHeight < mScrollView.getCurrentScrollY()) {
if (headerTranslationY != 0) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start();
}
}
}
}
};
private ObservableScrollViewCallbacks mWebViewScrollCallbacks = new ObservableScrollViewCallbacks() {
@Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
}
@Override
public void onDownMotionEvent() {
// Workaround: WebView inside a ScrollView absorbs down motion events, so observing
// down motion event from the WebView is required.
mFirstScroll = mDragging = true;
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
}
};
}
| apache-2.0 |
zmarkan/okhttp | okhttp-tests/src/test/java/okhttp3/ResponseTest.java | 3177 | /*
* Copyright (C) 2016 Square, 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 okhttp3;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSource;
import okio.Okio;
import okio.Source;
import okio.Timeout;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public final class ResponseTest {
@Test public void peekShorterThanResponse() throws Exception {
Response response = newResponse(responseBody("abcdef"));
ResponseBody peekedBody = response.peekBody(3);
assertEquals("abc", peekedBody.string());
assertEquals("abcdef", response.body().string());
}
@Test public void peekLongerThanResponse() throws Exception {
Response response = newResponse(responseBody("abc"));
ResponseBody peekedBody = response.peekBody(6);
assertEquals("abc", peekedBody.string());
assertEquals("abc", response.body().string());
}
@Test public void peekAfterReadingResponse() throws Exception {
Response response = newResponse(responseBody("abc"));
assertEquals("abc", response.body().string());
try {
response.peekBody(3);
fail();
} catch (IllegalStateException expected) {
}
}
@Test public void eachPeakIsIndependent() throws Exception {
Response response = newResponse(responseBody("abcdef"));
ResponseBody p1 = response.peekBody(4);
ResponseBody p2 = response.peekBody(2);
assertEquals("abcdef", response.body().string());
assertEquals("abcd", p1.string());
assertEquals("ab", p2.string());
}
/**
* Returns a new response body that refuses to be read once it has been closed. This is true of
* most {@link BufferedSource} instances, but not of {@link Buffer}.
*/
private ResponseBody responseBody(String content) {
final Buffer data = new Buffer().writeUtf8(content);
Source source = new Source() {
boolean closed;
@Override public void close() throws IOException {
closed = true;
}
@Override public long read(Buffer sink, long byteCount) throws IOException {
if (closed) throw new IllegalStateException();
return data.read(sink, byteCount);
}
@Override public Timeout timeout() {
return Timeout.NONE;
}
};
return ResponseBody.create(null, -1, Okio.buffer(source));
}
private Response newResponse(ResponseBody responseBody) {
return new Response.Builder()
.request(new Request.Builder()
.url("https://example.com/")
.build())
.protocol(Protocol.HTTP_1_1)
.code(200)
.body(responseBody)
.build();
}
}
| apache-2.0 |
FauxFaux/jdk9-jdk | src/java.desktop/share/classes/com/sun/media/sound/ModelDestination.java | 5633 | /*
* Copyright (c) 2007, 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.media.sound;
/**
* This class is used to identify destinations in connection blocks,
* see ModelConnectionBlock.
*
* @author Karl Helgason
*/
public final class ModelDestination {
public static final ModelIdentifier DESTINATION_NONE = null;
public static final ModelIdentifier DESTINATION_KEYNUMBER
= new ModelIdentifier("noteon", "keynumber");
public static final ModelIdentifier DESTINATION_VELOCITY
= new ModelIdentifier("noteon", "velocity");
public static final ModelIdentifier DESTINATION_PITCH
= new ModelIdentifier("osc", "pitch"); // cent
public static final ModelIdentifier DESTINATION_GAIN
= new ModelIdentifier("mixer", "gain"); // cB
public static final ModelIdentifier DESTINATION_PAN
= new ModelIdentifier("mixer", "pan"); // 0.1 %
public static final ModelIdentifier DESTINATION_REVERB
= new ModelIdentifier("mixer", "reverb"); // 0.1 %
public static final ModelIdentifier DESTINATION_CHORUS
= new ModelIdentifier("mixer", "chorus"); // 0.1 %
public static final ModelIdentifier DESTINATION_LFO1_DELAY
= new ModelIdentifier("lfo", "delay", 0); // timecent
public static final ModelIdentifier DESTINATION_LFO1_FREQ
= new ModelIdentifier("lfo", "freq", 0); // cent
public static final ModelIdentifier DESTINATION_LFO2_DELAY
= new ModelIdentifier("lfo", "delay", 1); // timecent
public static final ModelIdentifier DESTINATION_LFO2_FREQ
= new ModelIdentifier("lfo", "freq", 1); // cent
public static final ModelIdentifier DESTINATION_EG1_DELAY
= new ModelIdentifier("eg", "delay", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_ATTACK
= new ModelIdentifier("eg", "attack", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_HOLD
= new ModelIdentifier("eg", "hold", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_DECAY
= new ModelIdentifier("eg", "decay", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_SUSTAIN
= new ModelIdentifier("eg", "sustain", 0);
// 0.1 % (I want this to be value not %)
public static final ModelIdentifier DESTINATION_EG1_RELEASE
= new ModelIdentifier("eg", "release", 0); // timecent
public static final ModelIdentifier DESTINATION_EG1_SHUTDOWN
= new ModelIdentifier("eg", "shutdown", 0); // timecent
public static final ModelIdentifier DESTINATION_EG2_DELAY
= new ModelIdentifier("eg", "delay", 1); // timecent
public static final ModelIdentifier DESTINATION_EG2_ATTACK
= new ModelIdentifier("eg", "attack", 1); // timecent
public static final ModelIdentifier DESTINATION_EG2_HOLD
= new ModelIdentifier("eg", "hold", 1); // 0.1 %
public static final ModelIdentifier DESTINATION_EG2_DECAY
= new ModelIdentifier("eg", "decay", 1); // timecent
public static final ModelIdentifier DESTINATION_EG2_SUSTAIN
= new ModelIdentifier("eg", "sustain", 1);
// 0.1 % ( I want this to be value not %)
public static final ModelIdentifier DESTINATION_EG2_RELEASE
= new ModelIdentifier("eg", "release", 1); // timecent
public static final ModelIdentifier DESTINATION_EG2_SHUTDOWN
= new ModelIdentifier("eg", "shutdown", 1); // timecent
public static final ModelIdentifier DESTINATION_FILTER_FREQ
= new ModelIdentifier("filter", "freq", 0); // cent
public static final ModelIdentifier DESTINATION_FILTER_Q
= new ModelIdentifier("filter", "q", 0); // cB
private ModelIdentifier destination = DESTINATION_NONE;
private ModelTransform transform = new ModelStandardTransform();
public ModelDestination() {
}
public ModelDestination(ModelIdentifier id) {
destination = id;
}
public ModelIdentifier getIdentifier() {
return destination;
}
public void setIdentifier(ModelIdentifier destination) {
this.destination = destination;
}
public ModelTransform getTransform() {
return transform;
}
public void setTransform(ModelTransform transform) {
this.transform = transform;
}
}
| gpl-2.0 |
arunasujith/wso2-axis2 | modules/jaxws/src/org/apache/axis2/jaxws/message/databinding/impl/SOAPEnvelopeBlockImpl.java | 5741 | /*
* 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.axis2.jaxws.message.databinding.impl;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMOutputFormat;
import org.apache.axis2.jaxws.ExceptionFactory;
import org.apache.axis2.jaxws.message.Message;
import org.apache.axis2.jaxws.message.databinding.SOAPEnvelopeBlock;
import org.apache.axis2.jaxws.message.factory.BlockFactory;
import org.apache.axis2.jaxws.message.factory.MessageFactory;
import org.apache.axis2.jaxws.message.impl.BlockImpl;
import org.apache.axis2.jaxws.message.util.SOAPElementReader;
import org.apache.axis2.jaxws.registry.FactoryRegistry;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.ws.WebServiceException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
/**
*
*
*/
public class SOAPEnvelopeBlockImpl extends BlockImpl implements SOAPEnvelopeBlock {
/**
* Called by SOAPEnvelopeBlockFactory
*
* @param busObject
* @param busContext
* @param qName
* @param factory
*/
public SOAPEnvelopeBlockImpl(Object busObject, Object busContext,
QName qName, BlockFactory factory) {
super(busObject,
busContext,
(qName == null) ? getQName((SOAPEnvelope)busObject) : qName,
factory);
}
/**
* Called by SOAPEnvelopeBlockFactory
*
* @param omElement
* @param busContext
* @param qName
* @param factory
*/
public SOAPEnvelopeBlockImpl(OMElement omElement, Object busContext,
QName qName, BlockFactory factory) {
super(omElement, busContext, qName, factory);
}
/* (non-Javadoc)
* @see org.apache.axis2.jaxws.message.impl.BlockImpl#_getBOFromReader(javax.xml.stream.XMLStreamReader, java.lang.Object)
*/
@Override
protected Object _getBOFromReader(XMLStreamReader reader, Object busContext)
throws XMLStreamException, WebServiceException {
MessageFactory mf = (MessageFactory)FactoryRegistry.getFactory(MessageFactory.class);
Message message = mf.createFrom(reader, null);
SOAPEnvelope env = message.getAsSOAPEnvelope();
this.setQName(getQName(env));
return env;
}
/* (non-Javadoc)
* @see org.apache.axis2.jaxws.message.impl.BlockImpl#_getReaderFromBO(java.lang.Object, java.lang.Object)
*/
@Override
protected XMLStreamReader _getReaderFromBO(Object busObj, Object busContext)
throws XMLStreamException, WebServiceException {
return new SOAPElementReader((SOAPElement)busObj);
}
/* (non-Javadoc)
* @see org.apache.axis2.jaxws.message.impl.BlockImpl#_outputFromBO(java.lang.Object, java.lang.Object, javax.xml.stream.XMLStreamWriter)
*/
@Override
protected void _outputFromBO(Object busObject, Object busContext,
XMLStreamWriter writer)
throws XMLStreamException, WebServiceException {
XMLStreamReader reader = _getReaderFromBO(busObject, busContext);
_outputFromReader(reader, writer);
}
/**
* Get the QName of the envelope
*
* @param env
* @return QName
*/
private static QName getQName(SOAPEnvelope env) {
return new QName(env.getNamespaceURI(), env.getLocalName(), env.getPrefix());
}
public boolean isElementData() {
return true;
}
public void close() {
return; // Nothing to close
}
public InputStream getXMLInputStream(String encoding) throws UnsupportedEncodingException {
byte[] bytes = getXMLBytes(encoding);
return new ByteArrayInputStream(bytes);
}
public Object getObject() {
try {
return getBusinessObject(false);
} catch (XMLStreamException e) {
throw ExceptionFactory.makeWebServiceException(e);
}
}
public boolean isDestructiveRead() {
return false;
}
public boolean isDestructiveWrite() {
return false;
}
public byte[] getXMLBytes(String encoding) throws UnsupportedEncodingException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OMOutputFormat format = new OMOutputFormat();
format.setCharSetEncoding(encoding);
try {
serialize(baos, format);
baos.flush();
return baos.toByteArray();
} catch (XMLStreamException e) {
throw ExceptionFactory.makeWebServiceException(e);
} catch (IOException e) {
throw ExceptionFactory.makeWebServiceException(e);
}
}
}
| apache-2.0 |
yhnishi/cassandra | src/java/org/apache/cassandra/schema/KeyspaceParams.java | 3724 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.schema;
import java.util.Map;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
/**
* An immutable class representing keyspace parameters (durability and replication).
*/
public final class KeyspaceParams
{
public static final boolean DEFAULT_DURABLE_WRITES = true;
/**
* This determines durable writes for the {@link org.apache.cassandra.config.SchemaConstants#SCHEMA_KEYSPACE_NAME}
* and {@link org.apache.cassandra.config.SchemaConstants#SYSTEM_KEYSPACE_NAME} keyspaces,
* the only reason it is not final is for commitlog unit tests. It should only be changed for testing purposes.
*/
@VisibleForTesting
public static boolean DEFAULT_LOCAL_DURABLE_WRITES = true;
public enum Option
{
DURABLE_WRITES,
REPLICATION;
@Override
public String toString()
{
return name().toLowerCase();
}
}
public final boolean durableWrites;
public final ReplicationParams replication;
public KeyspaceParams(boolean durableWrites, ReplicationParams replication)
{
this.durableWrites = durableWrites;
this.replication = replication;
}
public static KeyspaceParams create(boolean durableWrites, Map<String, String> replication)
{
return new KeyspaceParams(durableWrites, ReplicationParams.fromMap(replication));
}
public static KeyspaceParams local()
{
return new KeyspaceParams(DEFAULT_LOCAL_DURABLE_WRITES, ReplicationParams.local());
}
public static KeyspaceParams simple(int replicationFactor)
{
return new KeyspaceParams(true, ReplicationParams.simple(replicationFactor));
}
public static KeyspaceParams simpleTransient(int replicationFactor)
{
return new KeyspaceParams(false, ReplicationParams.simple(replicationFactor));
}
public static KeyspaceParams nts(Object... args)
{
return new KeyspaceParams(true, ReplicationParams.nts(args));
}
public void validate(String name)
{
replication.validate(name);
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (!(o instanceof KeyspaceParams))
return false;
KeyspaceParams p = (KeyspaceParams) o;
return durableWrites == p.durableWrites && replication.equals(p.replication);
}
@Override
public int hashCode()
{
return Objects.hashCode(durableWrites, replication);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add(Option.DURABLE_WRITES.toString(), durableWrites)
.add(Option.REPLICATION.toString(), replication)
.toString();
}
}
| apache-2.0 |
wangcy6/storm_app | frame/kafka-0.11.0/kafka-0.11.0.1-src/connect/runtime/src/main/java/org/apache/kafka/connect/storage/MemoryOffsetBackingStore.java | 4169 | /*
* 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.kafka.connect.storage;
import org.apache.kafka.connect.errors.ConnectException;
import org.apache.kafka.connect.runtime.WorkerConfig;
import org.apache.kafka.connect.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* Implementation of OffsetBackingStore that doesn't actually persist any data. To ensure this
* behaves similarly to a real backing store, operations are executed asynchronously on a
* background thread.
*/
public class MemoryOffsetBackingStore implements OffsetBackingStore {
private static final Logger log = LoggerFactory.getLogger(MemoryOffsetBackingStore.class);
protected Map<ByteBuffer, ByteBuffer> data = new HashMap<>();
protected ExecutorService executor;
public MemoryOffsetBackingStore() {
}
@Override
public void configure(WorkerConfig config) {
}
@Override
public void start() {
executor = Executors.newSingleThreadExecutor();
}
@Override
public void stop() {
if (executor != null) {
executor.shutdown();
// Best effort wait for any get() and set() tasks (and caller's callbacks) to complete.
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (!executor.shutdownNow().isEmpty()) {
throw new ConnectException("Failed to stop MemoryOffsetBackingStore. Exiting without cleanly " +
"shutting down pending tasks and/or callbacks.");
}
executor = null;
}
}
@Override
public Future<Map<ByteBuffer, ByteBuffer>> get(
final Collection<ByteBuffer> keys,
final Callback<Map<ByteBuffer, ByteBuffer>> callback) {
return executor.submit(new Callable<Map<ByteBuffer, ByteBuffer>>() {
@Override
public Map<ByteBuffer, ByteBuffer> call() throws Exception {
Map<ByteBuffer, ByteBuffer> result = new HashMap<>();
for (ByteBuffer key : keys) {
result.put(key, data.get(key));
}
if (callback != null)
callback.onCompletion(null, result);
return result;
}
});
}
@Override
public Future<Void> set(final Map<ByteBuffer, ByteBuffer> values,
final Callback<Void> callback) {
return executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (Map.Entry<ByteBuffer, ByteBuffer> entry : values.entrySet()) {
data.put(entry.getKey(), entry.getValue());
}
save();
if (callback != null)
callback.onCompletion(null, null);
return null;
}
});
}
// Hook to allow subclasses to persist data
protected void save() {
}
}
| apache-2.0 |
FauxFaux/jdk9-langtools | test/tools/javac/generics/Multibound1.java | 321 | /*
* @test /nodynamiccopyright/
* @bug 4482403
* @summary javac failed to check second bound
* @author gafter
*
* @compile/fail/ref=Multibound1.out -XDrawDiagnostics Multibound1.java
*/
package Multibound1;
interface A {}
interface B {}
class C<T extends A&B> {}
class D implements A {}
class E extends C<D> {}
| gpl-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-rds/src/main/java/com/amazonaws/services/rds/model/ResetDBParameterGroupResult.java | 3865 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.rds.model;
import java.io.Serializable;
/**
* <p>
* Contains the result of a successful invocation of the
* ModifyDBParameterGroup or ResetDBParameterGroup action.
* </p>
*/
public class ResetDBParameterGroupResult implements Serializable, Cloneable {
/**
* Provides the name of the DB parameter group.
*/
private String dBParameterGroupName;
/**
* Provides the name of the DB parameter group.
*
* @return Provides the name of the DB parameter group.
*/
public String getDBParameterGroupName() {
return dBParameterGroupName;
}
/**
* Provides the name of the DB parameter group.
*
* @param dBParameterGroupName Provides the name of the DB parameter group.
*/
public void setDBParameterGroupName(String dBParameterGroupName) {
this.dBParameterGroupName = dBParameterGroupName;
}
/**
* Provides the name of the DB parameter group.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param dBParameterGroupName Provides the name of the DB parameter group.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ResetDBParameterGroupResult withDBParameterGroupName(String dBParameterGroupName) {
this.dBParameterGroupName = dBParameterGroupName;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getDBParameterGroupName() != null) sb.append("DBParameterGroupName: " + getDBParameterGroupName() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getDBParameterGroupName() == null) ? 0 : getDBParameterGroupName().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof ResetDBParameterGroupResult == false) return false;
ResetDBParameterGroupResult other = (ResetDBParameterGroupResult)obj;
if (other.getDBParameterGroupName() == null ^ this.getDBParameterGroupName() == null) return false;
if (other.getDBParameterGroupName() != null && other.getDBParameterGroupName().equals(this.getDBParameterGroupName()) == false) return false;
return true;
}
@Override
public ResetDBParameterGroupResult clone() {
try {
return (ResetDBParameterGroupResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!",
e);
}
}
}
| apache-2.0 |
akosyakov/intellij-community | python/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibCanonicalPathProvider.java | 3015 | /*
* Copyright 2000-2014 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.jetbrains.python.codeInsight.stdlib;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.psi.resolve.PyCanonicalPathProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public class PyStdlibCanonicalPathProvider implements PyCanonicalPathProvider {
@Nullable
@Override
public QualifiedName getCanonicalPath(@NotNull QualifiedName qName, PsiElement foothold) {
return restoreStdlibCanonicalPath(qName);
}
public static QualifiedName restoreStdlibCanonicalPath(QualifiedName qName) {
if (qName.getComponentCount() > 0) {
final List<String> components = qName.getComponents();
final String head = components.get(0);
if (head.equals("_abcoll") || head.equals("_collections")) {
components.set(0, "collections");
return QualifiedName.fromComponents(components);
}
else if (head.equals("posix") || head.equals("nt")) {
components.set(0, "os");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_functools")) {
components.set(0, "functools");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_struct")) {
components.set(0, "struct");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_io") || head.equals("_pyio") || head.equals("_fileio")) {
components.set(0, "io");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_datetime")) {
components.set(0, "datetime");
return QualifiedName.fromComponents(components);
}
else if (head.equals("ntpath") || head.equals("posixpath") || head.equals("path")) {
final List<String> result = new ArrayList<String>();
result.add("os");
components.set(0, "path");
result.addAll(components);
return QualifiedName.fromComponents(result);
}
else if (head.equals("_sqlite3")) {
components.set(0, "sqlite3");
return QualifiedName.fromComponents(components);
}
else if (head.equals("_pickle")) {
components.set(0, "pickle");
return QualifiedName.fromComponents(components);
}
}
return null;
}
}
| apache-2.0 |
wimvds/elasticsearch | core/src/test/java/org/elasticsearch/script/GroovyScriptIT.java | 7046 | /*
* 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.script;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.script.groovy.GroovyScriptEngineService;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;
import static org.hamcrest.Matchers.equalTo;
/**
* Various tests for Groovy scripting
*/
public class GroovyScriptIT extends ESIntegTestCase {
@Test
public void testGroovyBigDecimalTransformation() {
client().prepareIndex("test", "doc", "1").setSource("foo", 5).setRefresh(true).get();
// Test that something that would usually be a BigDecimal is transformed into a Double
assertScript("def n = 1.23; assert n instanceof Double;");
assertScript("def n = 1.23G; assert n instanceof Double;");
assertScript("def n = BigDecimal.ONE; assert n instanceof BigDecimal;");
}
public void assertScript(String script) {
SearchResponse resp = client().prepareSearch("test")
.setSource(new BytesArray("{\"query\": {\"match_all\": {}}," +
"\"sort\":{\"_script\": {\"script\": \""+ script +
"; 1\", \"type\": \"number\", \"lang\": \"groovy\"}}}")).get();
assertNoFailures(resp);
}
@Test
public void testGroovyExceptionSerialization() throws Exception {
List<IndexRequestBuilder> reqs = new ArrayList<>();
for (int i = 0; i < randomIntBetween(50, 500); i++) {
reqs.add(client().prepareIndex("test", "doc", "" + i).setSource("foo", "bar"));
}
indexRandom(true, false, reqs);
try {
client().prepareSearch("test")
.setQuery(
constantScoreQuery(scriptQuery(new Script("1 == not_found", ScriptType.INLINE, GroovyScriptEngineService.NAME,
null)))).get();
fail("should have thrown an exception");
} catch (SearchPhaseExecutionException e) {
assertThat(e.toString()+ "should not contained NotSerializableTransportException",
e.toString().contains("NotSerializableTransportException"), equalTo(false));
assertThat(e.toString()+ "should have contained GroovyScriptExecutionException",
e.toString().contains("GroovyScriptExecutionException"), equalTo(true));
assertThat(e.toString()+ "should have contained not_found",
e.toString().contains("No such property: not_found"), equalTo(true));
}
try {
client().prepareSearch("test")
.setQuery(constantScoreQuery(scriptQuery(new Script("assert false", ScriptType.INLINE, "groovy", null)))).get();
fail("should have thrown an exception");
} catch (SearchPhaseExecutionException e) {
assertThat(e.toString() + "should not contained NotSerializableTransportException",
e.toString().contains("NotSerializableTransportException"), equalTo(false));
assertThat(e.toString() + "should have contained GroovyScriptExecutionException",
e.toString().contains("GroovyScriptExecutionException"), equalTo(true));
assertThat(e.toString()+ "should have contained an assert error",
e.toString().contains("AssertionError[assert false"), equalTo(true));
}
}
@Test
public void testGroovyScriptAccess() {
client().prepareIndex("test", "doc", "1").setSource("foo", "quick brow fox jumped over the lazy dog", "bar", 1).get();
client().prepareIndex("test", "doc", "2").setSource("foo", "fast jumping spiders", "bar", 2).get();
client().prepareIndex("test", "doc", "3").setSource("foo", "dog spiders that can eat a dog", "bar", 3).get();
refresh();
// doc[] access
SearchResponse resp = client().prepareSearch("test").setQuery(functionScoreQuery(matchAllQuery())
.add(
scriptFunction(new Script("doc['bar'].value", ScriptType.INLINE, "groovy", null)))
.boostMode(CombineFunction.REPLACE)).get();
assertNoFailures(resp);
assertOrderedSearchHits(resp, "3", "2", "1");
}
public void testScoreAccess() {
client().prepareIndex("test", "doc", "1").setSource("foo", "quick brow fox jumped over the lazy dog", "bar", 1).get();
client().prepareIndex("test", "doc", "2").setSource("foo", "fast jumping spiders", "bar", 2).get();
client().prepareIndex("test", "doc", "3").setSource("foo", "dog spiders that can eat a dog", "bar", 3).get();
refresh();
// _score can be accessed
SearchResponse resp = client().prepareSearch("test").setQuery(functionScoreQuery(matchQuery("foo", "dog"))
.add(scriptFunction(new Script("_score", ScriptType.INLINE, "groovy", null)))
.boostMode(CombineFunction.REPLACE)).get();
assertNoFailures(resp);
assertSearchHits(resp, "3", "1");
// _score is comparable
// NOTE: it is important to use 0.0 instead of 0 instead Groovy will do an integer comparison
// and if the score if between 0 and 1 it will be considered equal to 0 due to the cast
resp = client()
.prepareSearch("test")
.setQuery(
functionScoreQuery(matchQuery("foo", "dog")).add(
scriptFunction(new Script("_score > 0.0 ? _score : 0", ScriptType.INLINE, "groovy", null))).boostMode(
CombineFunction.REPLACE)).get();
assertNoFailures(resp);
assertSearchHits(resp, "3", "1");
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-efs/src/main/java/com/amazonaws/services/elasticfilesystem/model/FileSystemNotFoundException.java | 2190 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticfilesystem.model;
import com.amazonaws.AmazonServiceException;
/**
* <p>
* Returned if the specified <code>FileSystemId</code> does not exist in the
* requester's AWS account.
* </p>
*/
public class FileSystemNotFoundException extends AmazonServiceException {
private static final long serialVersionUID = 1L;
private String errorCode;
/**
* Constructs a new FileSystemNotFoundException with the specified error
* message.
*
* @param message
* Describes the error encountered.
*/
public FileSystemNotFoundException(String message) {
super(message);
}
/**
* Sets the value of the ErrorCode property for this object.
*
* @param errorCode
* The new value for the ErrorCode property for this object.
*/
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
/**
* Returns the value of the ErrorCode property for this object.
*
* @return The value of the ErrorCode property for this object.
*/
public String getErrorCode() {
return this.errorCode;
}
/**
* Sets the value of the ErrorCode property for this object.
*
* @param errorCode
* The new value for the ErrorCode property for this object.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public FileSystemNotFoundException withErrorCode(String errorCode) {
setErrorCode(errorCode);
return this;
}
} | apache-2.0 |
cloudbearings/BroadleafCommerce | admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/web/filter/BroadleafAdminTimeZoneResolver.java | 1370 | /*
* #%L
* BroadleafCommerce Open Admin Platform
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.openadmin.web.filter;
import org.broadleafcommerce.common.web.BroadleafTimeZoneResolverImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
import java.util.TimeZone;
/**
*
* @author Phillip Verheyden (phillipuniverse)
*/
@Component("blAdminTimeZoneResolver")
public class BroadleafAdminTimeZoneResolver extends BroadleafTimeZoneResolverImpl {
@Override
public TimeZone resolveTimeZone(WebRequest request) {
//TODO: eventually this should support a using a timezone from the currently logged in Admin user preferences
return super.resolveTimeZone(request);
}
}
| apache-2.0 |
cengizhanozcan/BroadleafCommerce | admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/security/service/RowLevelSecurityService.java | 1996 | /*
* #%L
* BroadleafCommerce Open Admin Platform
* %%
* Copyright (C) 2009 - 2014 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.openadmin.server.security.service;
import java.util.List;
/**
* <p>
* Provides row-level security to the various CRUD operations in the admin
*
* <p>
* This security service can be extended by the use of {@link RowLevelSecurityProviders}, of which this service has a list.
* To add additional providers, add this to an applicationContext merged into the admin application:
*
* {@code
* <bean id="blCustomRowSecurityProviders" class="org.springframework.beans.factory.config.ListFactoryBean" >
* <property name="sourceList">
* <list>
* <ref bean="customProvider" />
* </list>
* </property>
* </bean>
* <bean class="org.broadleafcommerce.common.extensibility.context.merge.LateStageMergeBeanPostProcessor">
* <property name="collectionRef" value="blCustomRowSecurityProviders" />
* <property name="targetRef" value="blRowLevelSecurityProviders" />
* </bean>
* }
*
* @author Phillip Verheyden (phillipuniverse)
* @author Brian Polster (bpolster)
*/
public interface RowLevelSecurityService extends RowLevelSecurityProvider {
/**
* Gets all of the registered providers
* @return the providers configured for this service
*/
public List<RowLevelSecurityProvider> getProviders();
}
| apache-2.0 |
XtremeMP-Project/xtrememp-fx | xtrememp-audio-spi-vorbis/src/com/jcraft/jorbis/PsyInfo.java | 2222 | /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/* JOrbis
* Copyright (C) 2000 ymnk, JCraft,Inc.
*
* Written by: 2000 ymnk<ymnk@jcraft.com>
*
* Many thanks to
* Monty <monty@xiph.org> and
* The XIPHOPHORUS Company http://www.xiph.org/ .
* JOrbis has been based on their awesome works, Vorbis codec.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License
* as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package com.jcraft.jorbis;
// psychoacoustic setup
class PsyInfo{
int athp;
int decayp;
int smoothp;
int noisefitp;
int noisefit_subblock;
float noisefit_threshdB;
float ath_att;
int tonemaskp;
float[] toneatt_125Hz=new float[5];
float[] toneatt_250Hz=new float[5];
float[] toneatt_500Hz=new float[5];
float[] toneatt_1000Hz=new float[5];
float[] toneatt_2000Hz=new float[5];
float[] toneatt_4000Hz=new float[5];
float[] toneatt_8000Hz=new float[5];
int peakattp;
float[] peakatt_125Hz=new float[5];
float[] peakatt_250Hz=new float[5];
float[] peakatt_500Hz=new float[5];
float[] peakatt_1000Hz=new float[5];
float[] peakatt_2000Hz=new float[5];
float[] peakatt_4000Hz=new float[5];
float[] peakatt_8000Hz=new float[5];
int noisemaskp;
float[] noiseatt_125Hz=new float[5];
float[] noiseatt_250Hz=new float[5];
float[] noiseatt_500Hz=new float[5];
float[] noiseatt_1000Hz=new float[5];
float[] noiseatt_2000Hz=new float[5];
float[] noiseatt_4000Hz=new float[5];
float[] noiseatt_8000Hz=new float[5];
float max_curve_dB;
float attack_coeff;
float decay_coeff;
void free(){
}
}
| bsd-3-clause |
Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/base/android/java/src/org/chromium/base/TraceEvent.java | 11372 | // Copyright 2014 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;
import android.os.Looper;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.util.Log;
import android.util.Printer;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
/**
* Java mirror of Chrome trace event API. See base/trace_event/trace_event.h. Unlike the native
* version, Java does not have stack objects, so a TRACE_EVENT() which does both TRACE_EVENT_BEGIN()
* and TRACE_EVENT_END() in ctor/dtor is not possible.
* It is OK to use tracing before the native library has loaded, but such traces will
* be ignored. (Perhaps we could devise to buffer them up in future?).
*/
@JNINamespace("base::android")
public class TraceEvent {
private static volatile boolean sEnabled = false;
private static volatile boolean sATraceEnabled = false; // True when taking an Android systrace.
private static class BasicLooperMonitor implements Printer {
@Override
public void println(final String line) {
if (line.startsWith(">")) {
beginHandling(line);
} else {
assert line.startsWith("<");
endHandling(line);
}
}
void beginHandling(final String line) {
if (sEnabled) nativeBeginToplevel();
}
void endHandling(final String line) {
if (sEnabled) nativeEndToplevel();
}
}
/**
* A class that records, traces and logs statistics about the UI thead's Looper.
* The output of this class can be used in a number of interesting ways:
* <p>
* <ol><li>
* When using chrometrace, there will be a near-continuous line of
* measurements showing both event dispatches as well as idles;
* </li><li>
* Logging messages are output for events that run too long on the
* event dispatcher, making it easy to identify problematic areas;
* </li><li>
* Statistics are output whenever there is an idle after a non-trivial
* amount of activity, allowing information to be gathered about task
* density and execution cadence on the Looper;
* </li></ol>
* <p>
* The class attaches itself as an idle handler to the main Looper, and
* monitors the execution of events and idle notifications. Task counters
* accumulate between idle notifications and get reset when a new idle
* notification is received.
*/
private static final class IdleTracingLooperMonitor extends BasicLooperMonitor
implements MessageQueue.IdleHandler {
// Tags for dumping to logcat or TraceEvent
private static final String TAG = "TraceEvent.LooperMonitor";
private static final String IDLE_EVENT_NAME = "Looper.queueIdle";
// Calculation constants
private static final long FRAME_DURATION_MILLIS = 1000L / 60L; // 60 FPS
// A reasonable threshold for defining a Looper event as "long running"
private static final long MIN_INTERESTING_DURATION_MILLIS =
FRAME_DURATION_MILLIS;
// A reasonable threshold for a "burst" of tasks on the Looper
private static final long MIN_INTERESTING_BURST_DURATION_MILLIS =
MIN_INTERESTING_DURATION_MILLIS * 3;
// Stats tracking
private long mLastIdleStartedAt = 0L;
private long mLastWorkStartedAt = 0L;
private int mNumTasksSeen = 0;
private int mNumIdlesSeen = 0;
private int mNumTasksSinceLastIdle = 0;
// State
private boolean mIdleMonitorAttached = false;
// Called from within the begin/end methods only.
// This method can only execute on the looper thread, because that is
// the only thread that is permitted to call Looper.myqueue().
private final void syncIdleMonitoring() {
if (sEnabled && !mIdleMonitorAttached) {
// approximate start time for computational purposes
mLastIdleStartedAt = SystemClock.elapsedRealtime();
Looper.myQueue().addIdleHandler(this);
mIdleMonitorAttached = true;
Log.v(TAG, "attached idle handler");
} else if (mIdleMonitorAttached && !sEnabled) {
Looper.myQueue().removeIdleHandler(this);
mIdleMonitorAttached = false;
Log.v(TAG, "detached idle handler");
}
}
@Override
final void beginHandling(final String line) {
// Close-out any prior 'idle' period before starting new task.
if (mNumTasksSinceLastIdle == 0) {
TraceEvent.end(IDLE_EVENT_NAME);
}
mLastWorkStartedAt = SystemClock.elapsedRealtime();
syncIdleMonitoring();
super.beginHandling(line);
}
@Override
final void endHandling(final String line) {
final long elapsed = SystemClock.elapsedRealtime()
- mLastWorkStartedAt;
if (elapsed > MIN_INTERESTING_DURATION_MILLIS) {
traceAndLog(Log.WARN, "observed a task that took "
+ elapsed + "ms: " + line);
}
super.endHandling(line);
syncIdleMonitoring();
mNumTasksSeen++;
mNumTasksSinceLastIdle++;
}
private static void traceAndLog(int level, String message) {
TraceEvent.instant("TraceEvent.LooperMonitor:IdleStats", message);
Log.println(level, TAG, message);
}
@Override
public final boolean queueIdle() {
final long now = SystemClock.elapsedRealtime();
if (mLastIdleStartedAt == 0) mLastIdleStartedAt = now;
final long elapsed = now - mLastIdleStartedAt;
mNumIdlesSeen++;
TraceEvent.begin(IDLE_EVENT_NAME, mNumTasksSinceLastIdle + " tasks since last idle.");
if (elapsed > MIN_INTERESTING_BURST_DURATION_MILLIS) {
// Dump stats
String statsString = mNumTasksSeen + " tasks and "
+ mNumIdlesSeen + " idles processed so far, "
+ mNumTasksSinceLastIdle + " tasks bursted and "
+ elapsed + "ms elapsed since last idle";
traceAndLog(Log.DEBUG, statsString);
}
mLastIdleStartedAt = now;
mNumTasksSinceLastIdle = 0;
return true; // stay installed
}
}
// Holder for monitor avoids unnecessary construction on non-debug runs
private static final class LooperMonitorHolder {
private static final BasicLooperMonitor sInstance =
CommandLine.getInstance().hasSwitch(BaseSwitches.ENABLE_IDLE_TRACING)
? new IdleTracingLooperMonitor() : new BasicLooperMonitor();
}
/**
* Register an enabled observer, such that java traces are always enabled with native.
*/
public static void registerNativeEnabledObserver() {
nativeRegisterEnabledObserver();
}
/**
* Notification from native that tracing is enabled/disabled.
*/
@CalledByNative
public static void setEnabled(boolean enabled) {
sEnabled = enabled;
// Android M+ systrace logs this on its own. Only log it if not writing to Android systrace.
if (sATraceEnabled) return;
ThreadUtils.getUiThreadLooper().setMessageLogging(
enabled ? LooperMonitorHolder.sInstance : null);
}
/**
* Enables or disabled Android systrace path of Chrome tracing. If enabled, all Chrome
* traces will be also output to Android systrace. Because of the overhead of Android
* systrace, this is for WebView only.
*/
public static void setATraceEnabled(boolean enabled) {
if (sATraceEnabled == enabled) return;
sATraceEnabled = enabled;
if (enabled) {
// Calls TraceEvent.setEnabled(true) via
// TraceLog::EnabledStateObserver::OnTraceLogEnabled
nativeStartATrace();
} else {
// Calls TraceEvent.setEnabled(false) via
// TraceLog::EnabledStateObserver::OnTraceLogDisabled
nativeStopATrace();
}
}
/**
* @return True if tracing is enabled, false otherwise.
* It is safe to call trace methods without checking if TraceEvent
* is enabled.
*/
public static boolean enabled() {
return sEnabled;
}
/**
* Triggers the 'instant' native trace event with no arguments.
* @param name The name of the event.
*/
public static void instant(String name) {
if (sEnabled) nativeInstant(name, null);
}
/**
* Triggers the 'instant' native trace event.
* @param name The name of the event.
* @param arg The arguments of the event.
*/
public static void instant(String name, String arg) {
if (sEnabled) nativeInstant(name, arg);
}
/**
* Triggers the 'start' native trace event with no arguments.
* @param name The name of the event.
* @param id The id of the asynchronous event.
*/
public static void startAsync(String name, long id) {
if (sEnabled) nativeStartAsync(name, id);
}
/**
* Triggers the 'finish' native trace event with no arguments.
* @param name The name of the event.
* @param id The id of the asynchronous event.
*/
public static void finishAsync(String name, long id) {
if (sEnabled) nativeFinishAsync(name, id);
}
/**
* Triggers the 'begin' native trace event with no arguments.
* @param name The name of the event.
*/
public static void begin(String name) {
if (sEnabled) nativeBegin(name, null);
}
/**
* Triggers the 'begin' native trace event.
* @param name The name of the event.
* @param arg The arguments of the event.
*/
public static void begin(String name, String arg) {
if (sEnabled) nativeBegin(name, arg);
}
/**
* Triggers the 'end' native trace event with no arguments.
* @param name The name of the event.
*/
public static void end(String name) {
if (sEnabled) nativeEnd(name, null);
}
/**
* Triggers the 'end' native trace event.
* @param name The name of the event.
* @param arg The arguments of the event.
*/
public static void end(String name, String arg) {
if (sEnabled) nativeEnd(name, arg);
}
private static native void nativeRegisterEnabledObserver();
private static native void nativeStartATrace();
private static native void nativeStopATrace();
private static native void nativeInstant(String name, String arg);
private static native void nativeBegin(String name, String arg);
private static native void nativeEnd(String name, String arg);
private static native void nativeBeginToplevel();
private static native void nativeEndToplevel();
private static native void nativeStartAsync(String name, long id);
private static native void nativeFinishAsync(String name, long id);
}
| mit |
rokn/Count_Words_2015 | testing/openjdk/jdk/make/tools/src/build/tools/jdwpgen/AltNode.java | 4156 | /*
* Copyright (c) 1998, 1999, 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 build.tools.jdwpgen;
import java.util.*;
import java.io.*;
class AltNode extends AbstractGroupNode implements TypeNode {
SelectNode select = null;
void constrain(Context ctx) {
super.constrain(ctx);
if (!(nameNode instanceof NameValueNode)) {
error("Alt name must have value: " + nameNode);
}
if (parent instanceof SelectNode) {
select = (SelectNode)parent;
} else {
error("Alt must be in Select");
}
}
void document(PrintWriter writer) {
docRowStart(writer);
writer.println("<td colspan=" +
(maxStructIndent - structIndent + 1) + ">");
writer.println("Case " + nameNode.name + " - if <i>" +
((SelectNode)parent).typeNode.name +
"</i> is " + nameNode.value() + ":");
writer.println("<td>" + comment() + " ");
++structIndent;
super.document(writer);
--structIndent;
}
String javaClassImplements() {
return " extends " + select.commonBaseClass();
}
void genJavaClassSpecifics(PrintWriter writer, int depth) {
indent(writer, depth);
writer.print("static final " + select.typeNode.javaType());
writer.println(" ALT_ID = " + nameNode.value() + ";");
if (context.isWritingCommand()) {
genJavaCreateMethod(writer, depth);
} else {
indent(writer, depth);
writer.println(select.typeNode.javaParam() + "() {");
indent(writer, depth+1);
writer.println("return ALT_ID;");
indent(writer, depth);
writer.println("}");
}
super.genJavaClassSpecifics(writer, depth);
}
void genJavaWriteMethod(PrintWriter writer, int depth) {
genJavaWriteMethod(writer, depth, "");
}
void genJavaReadsSelectCase(PrintWriter writer, int depth, String common) {
indent(writer, depth);
writer.println("case " + nameNode.value() + ":");
indent(writer, depth+1);
writer.println(common + " = new " + name + "(vm, ps);");
indent(writer, depth+1);
writer.println("break;");
}
void genJavaCreateMethod(PrintWriter writer, int depth) {
indent(writer, depth);
writer.print("static " + select.name() + " create(");
writer.print(javaParams());
writer.println(") {");
indent(writer, depth+1);
writer.print("return new " + select.name() + "(");
writer.print("ALT_ID, new " + javaClassName() + "(");
for (Iterator it = components.iterator(); it.hasNext();) {
TypeNode tn = (TypeNode)it.next();
writer.print(tn.name());
if (it.hasNext()) {
writer.print(", ");
}
}
writer.println("));");
indent(writer, depth);
writer.println("}");
}
}
| mit |
supercwn/KJFrameForAndroid | KJFrame/app/src/main/java/org/kymjs/blog/ui/widget/RecordButtonUtil.java | 5318 | /*
* Copyright (c) 2015, 张涛.
*
* 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.kymjs.blog.ui.widget;
import java.io.File;
import java.io.IOException;
import org.kymjs.blog.AppConfig;
import org.kymjs.blog.R;
import org.kymjs.kjframe.ui.KJActivityStack;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.FileUtils;
import org.kymjs.kjframe.utils.StringUtils;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.widget.TextView;
/**
*
* {@link #RecordButton}需要的工具类
*
* @author kymjs (http://www.kymjs.com/)
*
*/
public class RecordButtonUtil {
private final static String TAG = "AudioUtil";
public static final String AUDOI_DIR = FileUtils.getSDCardPath()
+ File.separator + AppConfig.audioPath; // 录音音频保存根路径
private String mAudioPath; // 要播放的声音的路径
private boolean mIsRecording;// 是否正在录音
private boolean mIsPlaying;// 是否正在播放
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private OnPlayListener listener;
public boolean isPlaying() {
return mIsPlaying;
}
/**
* 设置要播放的声音的路径
*
* @param path
*/
public void setAudioPath(String path) {
this.mAudioPath = path;
}
/**
* 播放声音结束时调用
*
* @param l
*/
public void setOnPlayListener(OnPlayListener l) {
this.listener = l;
}
// 初始化 录音器
private void initRecorder() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(mAudioPath);
mIsRecording = true;
}
/**
* 开始录音,并保存到文件中
*/
public void recordAudio() {
initRecorder();
try {
mRecorder.prepare();
mRecorder.start();
} catch (IOException e) {
ViewInject.toast("小屁孩不听你说话了,请返回重试");
}
}
/**
* 获取音量值,只是针对录音音量
*
* @return
*/
public int getVolumn() {
int volumn = 0;
// 录音
if (mRecorder != null && mIsRecording) {
volumn = mRecorder.getMaxAmplitude();
if (volumn != 0)
volumn = (int) (10 * Math.log(volumn) / Math.log(10)) / 5;
}
return volumn;
}
/**
* 停止录音
*/
public void stopRecord() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
mIsRecording = false;
}
}
public void stopPlay() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
mIsPlaying = false;
if (listener != null) {
listener.stopPlay();
}
}
}
public void startPlay(String audioPath, TextView timeView) {
if (!mIsPlaying) {
if (!StringUtils.isEmpty(audioPath)) {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(audioPath);
mPlayer.prepare();
if (timeView != null) {
int len = (mPlayer.getDuration() + 500) / 1000;
timeView.setText(len + "s");
}
mPlayer.start();
if (listener != null) {
listener.starPlay();
}
mIsPlaying = true;
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
ViewInject.toast(KJActivityStack.create().topActivity()
.getString(R.string.record_sound_notfound));
}
} else {
stopPlay();
} // end playing
}
/**
* 开始播放
*/
public void startPlay() {
startPlay(mAudioPath, null);
}
public interface OnPlayListener {
/**
* 播放声音结束时调用
*/
void stopPlay();
/**
* 播放声音开始时调用
*/
void starPlay();
}
}
| apache-2.0 |
tkafalas/pentaho-kettle | plugins/salesforce/core/src/test/java/org/pentaho/di/trans/steps/salesforce/SalesforceStepTest.java | 6334 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.salesforce;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.Mockito;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.mock.StepMockHelper;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class SalesforceStepTest {
@ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment();
private StepMockHelper<SalesforceStepMeta, SalesforceStepData> smh;
@BeforeClass
public static void setUpBeforeClass() throws KettleException {
KettleEnvironment.init( false );
}
@Before
public void setUp() throws KettleException {
smh =
new StepMockHelper<SalesforceStepMeta, SalesforceStepData>( "Salesforce", SalesforceStepMeta.class,
SalesforceStepData.class );
when( smh.logChannelInterfaceFactory.create( any(), any( LoggingObjectInterface.class ) ) ).thenReturn(
smh.logChannelInterface );
when( smh.trans.isRunning() ).thenReturn( true );
}
@After
public void cleanUp() {
smh.cleanUp();
}
@Test
public void testErrorHandling() {
SalesforceStepMeta meta = mock( SalesforceStepMeta.class, Mockito.CALLS_REAL_METHODS );
assertFalse( meta.supportsErrorHandling() );
}
@Test
public void testInitDispose() {
SalesforceStepMeta meta = mock( SalesforceStepMeta.class, Mockito.CALLS_REAL_METHODS );
SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) );
/*
* Salesforce Step should fail if username and password are not set
* We should not set a default account for all users
*/
meta.setDefault();
assertFalse( step.init( meta, smh.stepDataInterface ) );
meta.setDefault();
meta.setTargetURL( null );
assertFalse( step.init( meta, smh.stepDataInterface ) );
meta.setDefault();
meta.setUsername( "anonymous" );
assertFalse( step.init( meta, smh.stepDataInterface ) );
meta.setDefault();
meta.setUsername( "anonymous" );
meta.setPassword( "myPwd" );
meta.setModule( null );
assertFalse( step.init( meta, smh.stepDataInterface ) );
/*
* After setting username and password, we should have enough defaults to properly init
*/
meta.setDefault();
meta.setUsername( "anonymous" );
meta.setPassword( "myPwd" );
assertTrue( step.init( meta, smh.stepDataInterface ) );
// Dispose check
assertNotNull( smh.stepDataInterface.connection );
step.dispose( meta, smh.stepDataInterface );
assertNull( smh.stepDataInterface.connection );
}
class MockSalesforceStep extends SalesforceStep {
public MockSalesforceStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr,
TransMeta transMeta, Trans trans ) {
super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
}
}
@Test
public void createIntObjectTest() throws KettleValueException {
SalesforceStep step =
spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) );
ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class );
Mockito.when( valueMeta.getType() ).thenReturn( ValueMetaInterface.TYPE_INTEGER );
Object value = step.normalizeValue( valueMeta, 100L );
Assert.assertTrue( value instanceof Integer );
}
@Test
public void createDateObjectTest() throws KettleValueException, ParseException {
SalesforceStep step =
spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) );
ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class );
DateFormat dateFormat = new SimpleDateFormat( "dd-MM-yyyy hh:mm:ss" );
Date date = dateFormat.parse( "12-10-2017 15:10:25" );
Mockito.when( valueMeta.isDate() ).thenReturn( true );
Mockito.when( valueMeta.getDateFormatTimeZone() ).thenReturn( TimeZone.getTimeZone( "UTC" ) );
Mockito.when( valueMeta.getDate( Mockito.eq( date ) ) ).thenReturn( date );
Object value = step.normalizeValue( valueMeta, date );
Assert.assertTrue( value instanceof Calendar );
DateFormat minutesDateFormat = new SimpleDateFormat( "mm:ss" );
//check not missing minutes and seconds
Assert.assertEquals( minutesDateFormat.format( date ), minutesDateFormat.format( ( (Calendar) value ).getTime() ) );
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/model/transform/InvalidParameterValueExceptionUnmarshaller.java | 2012 | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.glacier.model.transform;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.transform.GlacierErrorUnmarshaller;
import com.amazonaws.util.json.JSONObject;
import com.amazonaws.services.glacier.model.InvalidParameterValueException;
public class InvalidParameterValueExceptionUnmarshaller extends GlacierErrorUnmarshaller {
public InvalidParameterValueExceptionUnmarshaller() {
super(InvalidParameterValueException.class);
}
@Override
public boolean match(String errorTypeFromHeader, JSONObject json) throws Exception {
if (errorTypeFromHeader == null) {
// Parse error type from the JSON content if it's not available in the response headers
String errorCodeFromContent = parseErrorCode(json);
return (errorCodeFromContent != null && errorCodeFromContent.equals("InvalidParameterValueException"));
} else {
return errorTypeFromHeader.equals("InvalidParameterValueException");
}
}
@Override
public AmazonServiceException unmarshall(JSONObject json) throws Exception {
InvalidParameterValueException e = (InvalidParameterValueException)super.unmarshall(json);
e.setErrorCode("InvalidParameterValueException");
e.setType(parseMember("Type", json));
e.setCode(parseMember("Code", json));
return e;
}
}
| apache-2.0 |
zjupure/SneezeReader | weibosdk/src/main/java/com/sina/weibo/sdk/openapi/models/Status.java | 5659 | /*
* Copyright (C) 2010-2013 The SINA WEIBO 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.sina.weibo.sdk.openapi.models;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* 微博结构体。
*
* @author SINA
* @since 2013-11-22
*/
public class Status {
/** 微博创建时间 */
public String created_at;
/** 微博ID */
public String id;
/** 微博MID */
public String mid;
/** 字符串型的微博ID */
public String idstr;
/** 微博信息内容 */
public String text;
/** 微博来源 */
public String source;
/** 是否已收藏,true:是,false:否 */
public boolean favorited;
/** 是否被截断,true:是,false:否 */
public boolean truncated;
/**(暂未支持)回复ID */
public String in_reply_to_status_id;
/**(暂未支持)回复人UID */
public String in_reply_to_user_id;
/**(暂未支持)回复人昵称 */
public String in_reply_to_screen_name;
/** 缩略图片地址(小图),没有时不返回此字段 */
public String thumbnail_pic;
/** 中等尺寸图片地址(中图),没有时不返回此字段 */
public String bmiddle_pic;
/** 原始图片地址(原图),没有时不返回此字段 */
public String original_pic;
/** 地理信息字段 */
public Geo geo;
/** 微博作者的用户信息字段 */
public User user;
/** 被转发的原微博信息字段,当该微博为转发微博时返回 */
public Status retweeted_status;
/** 转发数 */
public int reposts_count;
/** 评论数 */
public int comments_count;
/** 表态数 */
public int attitudes_count;
/** 暂未支持 */
public int mlevel;
/**
* 微博的可见性及指定可见分组信息。该 object 中 type 取值,
* 0:普通微博,1:私密微博,3:指定分组微博,4:密友微博;
* list_id为分组的组号
*/
public Visible visible;
/** 微博配图地址。多图时返回多图链接。无配图返回"[]" */
public ArrayList<String> pic_urls;
/** 微博流内的推广微博ID */
//public Ad ad;
public static Status parse(String jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
return Status.parse(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public static Status parse(JSONObject jsonObject) {
if (null == jsonObject) {
return null;
}
Status status = new Status();
status.created_at = jsonObject.optString("created_at");
status.id = jsonObject.optString("id");
status.mid = jsonObject.optString("mid");
status.idstr = jsonObject.optString("idstr");
status.text = jsonObject.optString("text");
status.source = jsonObject.optString("source");
status.favorited = jsonObject.optBoolean("favorited", false);
status.truncated = jsonObject.optBoolean("truncated", false);
// Have NOT supported
status.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");
status.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");
status.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");
status.thumbnail_pic = jsonObject.optString("thumbnail_pic");
status.bmiddle_pic = jsonObject.optString("bmiddle_pic");
status.original_pic = jsonObject.optString("original_pic");
status.geo = Geo.parse(jsonObject.optJSONObject("geo"));
status.user = User.parse(jsonObject.optJSONObject("user"));
status.retweeted_status = Status.parse(jsonObject.optJSONObject("retweeted_status"));
status.reposts_count = jsonObject.optInt("reposts_count");
status.comments_count = jsonObject.optInt("comments_count");
status.attitudes_count = jsonObject.optInt("attitudes_count");
status.mlevel = jsonObject.optInt("mlevel", -1); // Have NOT supported
status.visible = Visible.parse(jsonObject.optJSONObject("visible"));
JSONArray picUrlsArray = jsonObject.optJSONArray("pic_urls");
if (picUrlsArray != null && picUrlsArray.length() > 0) {
int length = picUrlsArray.length();
status.pic_urls = new ArrayList<String>(length);
JSONObject tmpObject = null;
for (int ix = 0; ix < length; ix++) {
tmpObject = picUrlsArray.optJSONObject(ix);
if (tmpObject != null) {
status.pic_urls.add(tmpObject.optString("thumbnail_pic"));
}
}
}
//status.ad = jsonObject.optString("ad", "");
return status;
}
}
| apache-2.0 |
corochoone/elasticsearch | src/main/java/org/elasticsearch/search/aggregations/bucket/filter/InternalFilter.java | 2222 | /*
* 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.bucket.filter;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.search.aggregations.AggregationStreams;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.bucket.InternalSingleBucketAggregation;
import java.io.IOException;
/**
*
*/
public class InternalFilter extends InternalSingleBucketAggregation implements Filter {
public final static Type TYPE = new Type("filter");
public final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public InternalFilter readResult(StreamInput in) throws IOException {
InternalFilter result = new InternalFilter();
result.readFrom(in);
return result;
}
};
public static void registerStreams() {
AggregationStreams.registerStream(STREAM, TYPE.stream());
}
InternalFilter() {} // for serialization
InternalFilter(String name, long docCount, InternalAggregations subAggregations) {
super(name, docCount, subAggregations);
}
@Override
public Type type() {
return TYPE;
}
@Override
protected InternalSingleBucketAggregation newAggregation(String name, long docCount, InternalAggregations subAggregations) {
return new InternalFilter(name, docCount, subAggregations);
}
} | apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/impl/parser/ParserContext.java | 6989 | /*
* 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.xsom.impl.parser;
import com.sun.xml.internal.xsom.XSSchemaSet;
import com.sun.xml.internal.xsom.impl.ElementDecl;
import com.sun.xml.internal.xsom.impl.SchemaImpl;
import com.sun.xml.internal.xsom.impl.SchemaSetImpl;
import com.sun.xml.internal.xsom.parser.AnnotationParserFactory;
import com.sun.xml.internal.xsom.parser.XMLParser;
import com.sun.xml.internal.xsom.parser.XSOMParser;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
/**
* Provides context information to be used by {@link NGCCRuntimeEx}s.
*
* <p>
* This class does the actual processing for {@link XSOMParser},
* but to hide the details from the public API, this class in
* a different package.
*
* @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class ParserContext {
/** SchemaSet to which a newly parsed schema is put in. */
public final SchemaSetImpl schemaSet = new SchemaSetImpl();
private final XSOMParser owner;
final XMLParser parser;
private final Vector<Patch> patchers = new Vector<Patch>();
private final Vector<Patch> errorCheckers = new Vector<Patch>();
/**
* Documents that are parsed already. Used to avoid cyclic inclusion/double
* inclusion of schemas. Set of {@link SchemaDocumentImpl}s.
*
* The actual data structure is map from {@link SchemaDocumentImpl} to itself,
* so that we can access the {@link SchemaDocumentImpl} itself.
*/
public final Map<SchemaDocumentImpl, SchemaDocumentImpl> parsedDocuments = new HashMap<SchemaDocumentImpl, SchemaDocumentImpl>();
public ParserContext( XSOMParser owner, XMLParser parser ) {
this.owner = owner;
this.parser = parser;
try {
parse(new InputSource(ParserContext.class.getResource("datatypes.xsd").toExternalForm()));
SchemaImpl xs = (SchemaImpl)
schemaSet.getSchema("http://www.w3.org/2001/XMLSchema");
xs.addSimpleType(schemaSet.anySimpleType,true);
xs.addComplexType(schemaSet.anyType,true);
} catch( SAXException e ) {
// this must be a bug of XSOM
if(e.getException()!=null)
e.getException().printStackTrace();
else
e.printStackTrace();
throw new InternalError();
}
}
public EntityResolver getEntityResolver() {
return owner.getEntityResolver();
}
public AnnotationParserFactory getAnnotationParserFactory() {
return owner.getAnnotationParserFactory();
}
/**
* Parses a new XML Schema document.
*/
public void parse( InputSource source ) throws SAXException {
newNGCCRuntime().parseEntity(source,false,null,null);
}
public XSSchemaSet getResult() throws SAXException {
// run all the patchers
for (Patch patcher : patchers)
patcher.run();
patchers.clear();
// build the element substitutability map
Iterator itr = schemaSet.iterateElementDecls();
while(itr.hasNext())
((ElementDecl)itr.next()).updateSubstitutabilityMap();
// run all the error checkers
for (Patch patcher : errorCheckers)
patcher.run();
errorCheckers.clear();
if(hadError) return null;
else return schemaSet;
}
public NGCCRuntimeEx newNGCCRuntime() {
return new NGCCRuntimeEx(this);
}
/** Once an error is detected, this flag is set to true. */
private boolean hadError = false;
/** Turns on the error flag. */
void setErrorFlag() { hadError=true; }
/**
* PatchManager implementation, which is accessible only from
* NGCCRuntimEx.
*/
final PatcherManager patcherManager = new PatcherManager() {
public void addPatcher( Patch patch ) {
patchers.add(patch);
}
public void addErrorChecker( Patch patch ) {
errorCheckers.add(patch);
}
public void reportError( String msg, Locator src ) throws SAXException {
// set a flag to true to avoid returning a corrupted object.
setErrorFlag();
SAXParseException e = new SAXParseException(msg,src);
if(errorHandler==null)
throw e;
else
errorHandler.error(e);
}
};
/**
* ErrorHandler proxy to turn on the hadError flag when an error
* is found.
*/
final ErrorHandler errorHandler = new ErrorHandler() {
private ErrorHandler getErrorHandler() {
if( owner.getErrorHandler()==null )
return noopHandler;
else
return owner.getErrorHandler();
}
public void warning(SAXParseException e) throws SAXException {
getErrorHandler().warning(e);
}
public void error(SAXParseException e) throws SAXException {
setErrorFlag();
getErrorHandler().error(e);
}
public void fatalError(SAXParseException e) throws SAXException {
setErrorFlag();
getErrorHandler().fatalError(e);
}
};
/**
* {@link ErrorHandler} that does nothing.
*/
final ErrorHandler noopHandler = new ErrorHandler() {
public void warning(SAXParseException e) {
}
public void error(SAXParseException e) {
}
public void fatalError(SAXParseException e) {
setErrorFlag();
}
};
}
| mit |
wangcy6/storm_app | frame/kafka-0.11.0/kafka-0.11.0.1-src/connect/runtime/src/main/java/org/apache/kafka/connect/runtime/standalone/StandaloneConfig.java | 1709 | /*
* 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.kafka.connect.runtime.standalone;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.connect.runtime.WorkerConfig;
import java.util.Map;
public class StandaloneConfig extends WorkerConfig {
private static final ConfigDef CONFIG;
/**
* <code>offset.storage.file.filename</code>
*/
public static final String OFFSET_STORAGE_FILE_FILENAME_CONFIG = "offset.storage.file.filename";
private static final String OFFSET_STORAGE_FILE_FILENAME_DOC = "File to store offset data in";
static {
CONFIG = baseConfigDef()
.define(OFFSET_STORAGE_FILE_FILENAME_CONFIG,
ConfigDef.Type.STRING,
ConfigDef.Importance.HIGH,
OFFSET_STORAGE_FILE_FILENAME_DOC);
}
public StandaloneConfig(Map<String, String> props) {
super(CONFIG, props);
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/sun/text/resources/sr/FormatData_sr_ME.java | 3546 | /*
* Copyright (c) 2007, 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.
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright (C) 1991-2007 Unicode, Inc. All rights reserved.
* Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of the Unicode data files and any associated documentation (the "Data
* Files") or Unicode software and any associated documentation (the
* "Software") to deal in the Data Files or Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Data Files or Software, and
* to permit persons to whom the Data Files or Software are furnished to do
* so, provided that (a) the above copyright notice(s) and this permission
* notice appear with all copies of the Data Files or Software, (b) both the
* above copyright notice(s) and this permission notice appear in associated
* documentation, and (c) there is clear notice in each modified Data File or
* in the Software as well as in the documentation associated with the Data
* File(s) or Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR
* CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in these Data Files or Software without prior written
* authorization of the copyright holder.
*/
package sun.text.resources.sr;
import sun.util.resources.ParallelListResourceBundle;
public class FormatData_sr_ME extends ParallelListResourceBundle {
protected final Object[][] getContents() {
return new Object[][] {
};
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk/jdk/test/javax/sound/midi/Gervill/SoftAudioSynthesizer/GetFormat.java | 2359 | /*
* Copyright (c) 2007, 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.
*/
/* @test
@summary Test SoftAudioSynthesizer getFormat method */
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Patch;
import javax.sound.sampled.*;
import com.sun.media.sound.*;
public class GetFormat {
private static void assertEquals(Object a, Object b) throws Exception
{
if(!a.equals(b))
throw new RuntimeException("assertEquals fails!");
}
private static void assertTrue(boolean value) throws Exception
{
if(!value)
throw new RuntimeException("assertTrue fails!");
}
public static void main(String[] args) throws Exception {
AudioSynthesizer synth = new SoftSynthesizer();
AudioFormat defformat = synth.getFormat();
assertTrue(defformat != null);
synth.openStream(null, null);
assertTrue(synth.getFormat().toString().equals(defformat.toString()));
synth.close();
AudioFormat custformat = new AudioFormat(8000, 16, 1, true, false);
synth.openStream(custformat, null);
assertTrue(synth.getFormat().toString().equals(custformat.toString()));
synth.close();
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/java/lang/CharacterName.java | 4017 | /*
* Copyright (c) 2010, 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 java.lang;
import java.io.DataInputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.Arrays;
import java.util.zip.InflaterInputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
class CharacterName {
private static SoftReference<byte[]> refStrPool;
private static int[][] lookup;
private static synchronized byte[] initNamePool() {
byte[] strPool = null;
if (refStrPool != null && (strPool = refStrPool.get()) != null)
return strPool;
DataInputStream dis = null;
try {
dis = new DataInputStream(new InflaterInputStream(
AccessController.doPrivileged(new PrivilegedAction<InputStream>()
{
public InputStream run() {
return getClass().getResourceAsStream("uniName.dat");
}
})));
lookup = new int[(Character.MAX_CODE_POINT + 1) >> 8][];
int total = dis.readInt();
int cpEnd = dis.readInt();
byte ba[] = new byte[cpEnd];
dis.readFully(ba);
int nameOff = 0;
int cpOff = 0;
int cp = 0;
do {
int len = ba[cpOff++] & 0xff;
if (len == 0) {
len = ba[cpOff++] & 0xff;
// always big-endian
cp = ((ba[cpOff++] & 0xff) << 16) |
((ba[cpOff++] & 0xff) << 8) |
((ba[cpOff++] & 0xff));
} else {
cp++;
}
int hi = cp >> 8;
if (lookup[hi] == null) {
lookup[hi] = new int[0x100];
}
lookup[hi][cp&0xff] = (nameOff << 8) | len;
nameOff += len;
} while (cpOff < cpEnd);
strPool = new byte[total - cpEnd];
dis.readFully(strPool);
refStrPool = new SoftReference<>(strPool);
} catch (Exception x) {
throw new InternalError(x.getMessage(), x);
} finally {
try {
if (dis != null)
dis.close();
} catch (Exception xx) {}
}
return strPool;
}
public static String get(int cp) {
byte[] strPool = null;
if (refStrPool == null || (strPool = refStrPool.get()) == null)
strPool = initNamePool();
int off = 0;
if (lookup[cp>>8] == null ||
(off = lookup[cp>>8][cp&0xff]) == 0)
return null;
@SuppressWarnings("deprecation")
String result = new String(strPool, 0, off >>> 8, off & 0xff); // ASCII
return result;
}
}
| mit |
himanshuag/elasticsearch | core/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java | 19229 | /*
* 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.discovery.zen.fd;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ProcessedClusterStateNonMasterUpdateTask;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.discovery.zen.NotMasterException;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.elasticsearch.transport.TransportRequestOptions.options;
/**
* A fault detection that pings the master periodically to see if its alive.
*/
public class MasterFaultDetection extends FaultDetection {
public static final String MASTER_PING_ACTION_NAME = "internal:discovery/zen/fd/master_ping";
public static interface Listener {
/** called when pinging the master failed, like a timeout, transport disconnects etc */
void onMasterFailure(DiscoveryNode masterNode, String reason);
}
private final ClusterService clusterService;
private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
private volatile MasterPinger masterPinger;
private final Object masterNodeMutex = new Object();
private volatile DiscoveryNode masterNode;
private volatile int retryCount;
private final AtomicBoolean notifiedMasterFailure = new AtomicBoolean();
public MasterFaultDetection(Settings settings, ThreadPool threadPool, TransportService transportService,
ClusterName clusterName, ClusterService clusterService) {
super(settings, threadPool, transportService, clusterName);
this.clusterService = clusterService;
logger.debug("[master] uses ping_interval [{}], ping_timeout [{}], ping_retries [{}]", pingInterval, pingRetryTimeout, pingRetryCount);
transportService.registerRequestHandler(MASTER_PING_ACTION_NAME, MasterPingRequest::new, ThreadPool.Names.SAME, new MasterPingRequestHandler());
}
public DiscoveryNode masterNode() {
return this.masterNode;
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public void restart(DiscoveryNode masterNode, String reason) {
synchronized (masterNodeMutex) {
if (logger.isDebugEnabled()) {
logger.debug("[master] restarting fault detection against master [{}], reason [{}]", masterNode, reason);
}
innerStop();
innerStart(masterNode);
}
}
public void start(final DiscoveryNode masterNode, String reason) {
synchronized (masterNodeMutex) {
if (logger.isDebugEnabled()) {
logger.debug("[master] starting fault detection against master [{}], reason [{}]", masterNode, reason);
}
innerStart(masterNode);
}
}
private void innerStart(final DiscoveryNode masterNode) {
this.masterNode = masterNode;
this.retryCount = 0;
this.notifiedMasterFailure.set(false);
// try and connect to make sure we are connected
try {
transportService.connectToNode(masterNode);
} catch (final Exception e) {
// notify master failure (which stops also) and bail..
notifyMasterFailure(masterNode, "failed to perform initial connect [" + e.getMessage() + "]");
return;
}
if (masterPinger != null) {
masterPinger.stop();
}
this.masterPinger = new MasterPinger();
// we start pinging slightly later to allow the chosen master to complete it's own master election
threadPool.schedule(pingInterval, ThreadPool.Names.SAME, masterPinger);
}
public void stop(String reason) {
synchronized (masterNodeMutex) {
if (masterNode != null) {
if (logger.isDebugEnabled()) {
logger.debug("[master] stopping fault detection against master [{}], reason [{}]", masterNode, reason);
}
}
innerStop();
}
}
private void innerStop() {
// also will stop the next ping schedule
this.retryCount = 0;
if (masterPinger != null) {
masterPinger.stop();
masterPinger = null;
}
this.masterNode = null;
}
@Override
public void close() {
super.close();
stop("closing");
this.listeners.clear();
transportService.removeHandler(MASTER_PING_ACTION_NAME);
}
@Override
protected void handleTransportDisconnect(DiscoveryNode node) {
synchronized (masterNodeMutex) {
if (!node.equals(this.masterNode)) {
return;
}
if (connectOnNetworkDisconnect) {
try {
transportService.connectToNode(node);
// if all is well, make sure we restart the pinger
if (masterPinger != null) {
masterPinger.stop();
}
this.masterPinger = new MasterPinger();
// we use schedule with a 0 time value to run the pinger on the pool as it will run on later
threadPool.schedule(TimeValue.timeValueMillis(0), ThreadPool.Names.SAME, masterPinger);
} catch (Exception e) {
logger.trace("[master] [{}] transport disconnected (with verified connect)", masterNode);
notifyMasterFailure(masterNode, "transport disconnected (with verified connect)");
}
} else {
logger.trace("[master] [{}] transport disconnected", node);
notifyMasterFailure(node, "transport disconnected");
}
}
}
private void notifyMasterFailure(final DiscoveryNode masterNode, final String reason) {
if (notifiedMasterFailure.compareAndSet(false, true)) {
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
for (Listener listener : listeners) {
listener.onMasterFailure(masterNode, reason);
}
}
});
stop("master failure, " + reason);
}
}
private class MasterPinger implements Runnable {
private volatile boolean running = true;
public void stop() {
this.running = false;
}
@Override
public void run() {
if (!running) {
// return and don't spawn...
return;
}
final DiscoveryNode masterToPing = masterNode;
if (masterToPing == null) {
// master is null, should not happen, but we are still running, so reschedule
threadPool.schedule(pingInterval, ThreadPool.Names.SAME, MasterPinger.this);
return;
}
final MasterPingRequest request = new MasterPingRequest(clusterService.localNode().id(), masterToPing.id(), clusterName);
final TransportRequestOptions options = options().withType(TransportRequestOptions.Type.PING).withTimeout(pingRetryTimeout);
transportService.sendRequest(masterToPing, MASTER_PING_ACTION_NAME, request, options, new BaseTransportResponseHandler<MasterPingResponseResponse>() {
@Override
public MasterPingResponseResponse newInstance() {
return new MasterPingResponseResponse();
}
@Override
public void handleResponse(MasterPingResponseResponse response) {
if (!running) {
return;
}
// reset the counter, we got a good result
MasterFaultDetection.this.retryCount = 0;
// check if the master node did not get switched on us..., if it did, we simply return with no reschedule
if (masterToPing.equals(MasterFaultDetection.this.masterNode())) {
// we don't stop on disconnection from master, we keep pinging it
threadPool.schedule(pingInterval, ThreadPool.Names.SAME, MasterPinger.this);
}
}
@Override
public void handleException(TransportException exp) {
if (!running) {
return;
}
synchronized (masterNodeMutex) {
// check if the master node did not get switched on us...
if (masterToPing.equals(MasterFaultDetection.this.masterNode())) {
if (exp instanceof ConnectTransportException || exp.getCause() instanceof ConnectTransportException) {
handleTransportDisconnect(masterToPing);
return;
} else if (exp.getCause() instanceof NotMasterException) {
logger.debug("[master] pinging a master {} that is no longer a master", masterNode);
notifyMasterFailure(masterToPing, "no longer master");
return;
} else if (exp.getCause() instanceof ThisIsNotTheMasterYouAreLookingForException) {
logger.debug("[master] pinging a master {} that is not the master", masterNode);
notifyMasterFailure(masterToPing, "not master");
return;
} else if (exp.getCause() instanceof NodeDoesNotExistOnMasterException) {
logger.debug("[master] pinging a master {} but we do not exists on it, act as if its master failure", masterNode);
notifyMasterFailure(masterToPing, "do not exists on master, act as master failure");
return;
}
int retryCount = ++MasterFaultDetection.this.retryCount;
logger.trace("[master] failed to ping [{}], retry [{}] out of [{}]", exp, masterNode, retryCount, pingRetryCount);
if (retryCount >= pingRetryCount) {
logger.debug("[master] failed to ping [{}], tried [{}] times, each with maximum [{}] timeout", masterNode, pingRetryCount, pingRetryTimeout);
// not good, failure
notifyMasterFailure(masterToPing, "failed to ping, tried [" + pingRetryCount + "] times, each with maximum [" + pingRetryTimeout + "] timeout");
} else {
// resend the request, not reschedule, rely on send timeout
transportService.sendRequest(masterToPing, MASTER_PING_ACTION_NAME, request, options, this);
}
}
}
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
);
}
}
/** Thrown when a ping reaches the wrong node */
static class ThisIsNotTheMasterYouAreLookingForException extends IllegalStateException {
ThisIsNotTheMasterYouAreLookingForException(String msg) {
super(msg);
}
ThisIsNotTheMasterYouAreLookingForException() {
}
@Override
public Throwable fillInStackTrace() {
return null;
}
}
static class NodeDoesNotExistOnMasterException extends IllegalStateException {
@Override
public Throwable fillInStackTrace() {
return null;
}
}
private class MasterPingRequestHandler implements TransportRequestHandler<MasterPingRequest> {
@Override
public void messageReceived(final MasterPingRequest request, final TransportChannel channel) throws Exception {
final DiscoveryNodes nodes = clusterService.state().nodes();
// check if we are really the same master as the one we seemed to be think we are
// this can happen if the master got "kill -9" and then another node started using the same port
if (!request.masterNodeId.equals(nodes.localNodeId())) {
throw new ThisIsNotTheMasterYouAreLookingForException();
}
// ping from nodes of version < 1.4.0 will have the clustername set to null
if (request.clusterName != null && !request.clusterName.equals(clusterName)) {
logger.trace("master fault detection ping request is targeted for a different [{}] cluster then us [{}]", request.clusterName, clusterName);
throw new ThisIsNotTheMasterYouAreLookingForException("master fault detection ping request is targeted for a different [" + request.clusterName + "] cluster then us [" + clusterName + "]");
}
// when we are elected as master or when a node joins, we use a cluster state update thread
// to incorporate that information in the cluster state. That cluster state is published
// before we make it available locally. This means that a master ping can come from a node
// that has already processed the new CS but it is not known locally.
// Therefore, if we fail we have to check again under a cluster state thread to make sure
// all processing is finished.
//
if (!nodes.localNodeMaster() || !nodes.nodeExists(request.nodeId)) {
logger.trace("checking ping from [{}] under a cluster state thread", request.nodeId);
clusterService.submitStateUpdateTask("master ping (from: [" + request.nodeId + "])", new ProcessedClusterStateNonMasterUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) throws Exception {
// if we are no longer master, fail...
DiscoveryNodes nodes = currentState.nodes();
if (!nodes.localNodeMaster()) {
throw new NotMasterException("local node is not master");
}
if (!nodes.nodeExists(request.nodeId)) {
throw new NodeDoesNotExistOnMasterException();
}
return currentState;
}
@Override
public void onFailure(String source, @Nullable Throwable t) {
if (t == null) {
t = new ElasticsearchException("unknown error while processing ping");
}
try {
channel.sendResponse(t);
} catch (IOException e) {
logger.warn("error while sending ping response", e);
}
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
try {
channel.sendResponse(new MasterPingResponseResponse());
} catch (IOException e) {
logger.warn("error while sending ping response", e);
}
}
});
} else {
// send a response, and note if we are connected to the master or not
channel.sendResponse(new MasterPingResponseResponse());
}
}
}
public static class MasterPingRequest extends TransportRequest {
private String nodeId;
private String masterNodeId;
private ClusterName clusterName;
public MasterPingRequest() {
}
private MasterPingRequest(String nodeId, String masterNodeId, ClusterName clusterName) {
this.nodeId = nodeId;
this.masterNodeId = masterNodeId;
this.clusterName = clusterName;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
nodeId = in.readString();
masterNodeId = in.readString();
clusterName = ClusterName.readClusterName(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(nodeId);
out.writeString(masterNodeId);
clusterName.writeTo(out);
}
}
private static class MasterPingResponseResponse extends TransportResponse {
private MasterPingResponseResponse() {
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
}
}
| apache-2.0 |
nknize/elasticsearch | client/rest-high-level/src/test/java/org/elasticsearch/client/ml/StopDatafeedResponseTests.java | 1469 | /*
* 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.client.ml;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractXContentTestCase;
import java.io.IOException;
public class StopDatafeedResponseTests extends AbstractXContentTestCase<StopDatafeedResponse> {
@Override
protected StopDatafeedResponse createTestInstance() {
return new StopDatafeedResponse(randomBoolean());
}
@Override
protected StopDatafeedResponse doParseInstance(XContentParser parser) throws IOException {
return StopDatafeedResponse.fromXContent(parser);
}
@Override
protected boolean supportsUnknownFields() {
return true;
}
}
| apache-2.0 |
cshannon/activemq-artemis | tests/activemq5-unit-tests/src/test/java/org/apache/activemq/filter/DestinationFilterTest.java | 3298 | /**
* 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.activemq.filter;
import junit.framework.TestCase;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
public class DestinationFilterTest extends TestCase {
public void testPrefixFilter() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue(">"));
assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof PrefixDestinationFilter);
System.out.println(filter);
assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic(">")));
}
public void testWildcardFilter() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*"));
assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof WildcardDestinationFilter);
assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B")));
}
public void testCompositeFilter() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.B,B.C"));
assertTrue("Filter not parsed well: " + filter.getClass(), filter instanceof CompositeDestinationFilter);
assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B")));
}
public void testMatchesChild() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*.C"));
assertFalse("Filter matched wrong destination type", filter.matches(new ActiveMQTopic("A.B")));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C")));
filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.*"));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B")));
assertFalse("Filter did match", filter.matches(new ActiveMQQueue("A")));
}
public void testMatchesAny() throws Exception {
DestinationFilter filter = DestinationFilter.parseFilter(new ActiveMQQueue("A.>.>"));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.C")));
assertFalse("Filter did match", filter.matches(new ActiveMQQueue("B")));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B")));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A.B.C.D.E.F")));
assertTrue("Filter did not match", filter.matches(new ActiveMQQueue("A")));
}
}
| apache-2.0 |
rogerxaic/gestock | src/org/jsoup/parser/CharacterReader.java | 10826 | package org.jsoup.parser;
import org.jsoup.helper.Validate;
import java.util.Arrays;
import java.util.Locale;
/**
CharacterReader consumes tokens off a string. To replace the old TokenQueue.
*/
final class CharacterReader {
static final char EOF = (char) -1;
private static final int maxCacheLen = 12;
private final char[] input;
private final int length;
private int pos = 0;
private int mark = 0;
private final String[] stringCache = new String[512]; // holds reused strings in this doc, to lessen garbage
CharacterReader(String input) {
Validate.notNull(input);
this.input = input.toCharArray();
this.length = this.input.length;
}
int pos() {
return pos;
}
boolean isEmpty() {
return pos >= length;
}
char current() {
return pos >= length ? EOF : input[pos];
}
char consume() {
char val = pos >= length ? EOF : input[pos];
pos++;
return val;
}
void unconsume() {
pos--;
}
void advance() {
pos++;
}
void mark() {
mark = pos;
}
void rewindToMark() {
pos = mark;
}
String consumeAsString() {
return new String(input, pos++, 1);
}
/**
* Returns the number of characters between the current position and the next instance of the input char
* @param c scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
int nextIndexOf(char c) {
// doesn't handle scanning for surrogates
for (int i = pos; i < length; i++) {
if (c == input[i])
return i - pos;
}
return -1;
}
/**
* Returns the number of characters between the current position and the next instance of the input sequence
*
* @param seq scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
int nextIndexOf(CharSequence seq) {
// doesn't handle scanning for surrogates
char startChar = seq.charAt(0);
for (int offset = pos; offset < length; offset++) {
// scan to first instance of startchar:
if (startChar != input[offset])
while(++offset < length && startChar != input[offset]) { /* empty */ }
int i = offset + 1;
int last = i + seq.length()-1;
if (offset < length && last <= length) {
for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++) { /* empty */ }
if (i == last) // found full sequence
return offset - pos;
}
}
return -1;
}
String consumeTo(char c) {
int offset = nextIndexOf(c);
if (offset != -1) {
String consumed = cacheString(pos, offset);
pos += offset;
return consumed;
} else {
return consumeToEnd();
}
}
String consumeTo(String seq) {
int offset = nextIndexOf(seq);
if (offset != -1) {
String consumed = cacheString(pos, offset);
pos += offset;
return consumed;
} else {
return consumeToEnd();
}
}
String consumeToAny(final char... chars) {
final int start = pos;
final int remaining = length;
OUTER: while (pos < remaining) {
for (char c : chars) {
if (input[pos] == c)
break OUTER;
}
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeToAnySorted(final char... chars) {
final int start = pos;
final int remaining = length;
final char[] val = input;
while (pos < remaining) {
if (Arrays.binarySearch(chars, val[pos]) >= 0)
break;
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeData() {
// &, <, null
final int start = pos;
final int remaining = length;
final char[] val = input;
while (pos < remaining) {
final char c = val[pos];
if (c == '&'|| c == '<' || c == TokeniserState.nullChar)
break;
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeTagName() {
// '\t', '\n', '\r', '\f', ' ', '/', '>', nullChar
final int start = pos;
final int remaining = length;
final char[] val = input;
while (pos < remaining) {
final char c = val[pos];
if (c == '\t'|| c == '\n'|| c == '\r'|| c == '\f'|| c == ' '|| c == '/'|| c == '>'|| c == TokeniserState.nullChar)
break;
pos++;
}
return pos > start ? cacheString(start, pos-start) : "";
}
String consumeToEnd() {
String data = cacheString(pos, length-pos);
pos = length;
return data;
}
String consumeLetterSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
pos++;
else
break;
}
return cacheString(start, pos - start);
}
String consumeLetterThenDigitSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
pos++;
else
break;
}
while (!isEmpty()) {
char c = input[pos];
if (c >= '0' && c <= '9')
pos++;
else
break;
}
return cacheString(start, pos - start);
}
String consumeHexSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))
pos++;
else
break;
}
return cacheString(start, pos - start);
}
String consumeDigitSequence() {
int start = pos;
while (pos < length) {
char c = input[pos];
if (c >= '0' && c <= '9')
pos++;
else
break;
}
return cacheString(start, pos - start);
}
boolean matches(char c) {
return !isEmpty() && input[pos] == c;
}
boolean matches(String seq) {
int scanLength = seq.length();
if (scanLength > length - pos)
return false;
for (int offset = 0; offset < scanLength; offset++)
if (seq.charAt(offset) != input[pos+offset])
return false;
return true;
}
boolean matchesIgnoreCase(String seq) {
int scanLength = seq.length();
if (scanLength > length - pos)
return false;
for (int offset = 0; offset < scanLength; offset++) {
char upScan = Character.toUpperCase(seq.charAt(offset));
char upTarget = Character.toUpperCase(input[pos + offset]);
if (upScan != upTarget)
return false;
}
return true;
}
boolean matchesAny(char... seq) {
if (isEmpty())
return false;
char c = input[pos];
for (char seek : seq) {
if (seek == c)
return true;
}
return false;
}
boolean matchesAnySorted(char[] seq) {
return !isEmpty() && Arrays.binarySearch(seq, input[pos]) >= 0;
}
boolean matchesLetter() {
if (isEmpty())
return false;
char c = input[pos];
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
boolean matchesDigit() {
if (isEmpty())
return false;
char c = input[pos];
return (c >= '0' && c <= '9');
}
boolean matchConsume(String seq) {
if (matches(seq)) {
pos += seq.length();
return true;
} else {
return false;
}
}
boolean matchConsumeIgnoreCase(String seq) {
if (matchesIgnoreCase(seq)) {
pos += seq.length();
return true;
} else {
return false;
}
}
boolean containsIgnoreCase(String seq) {
// used to check presence of </title>, </style>. only finds consistent case.
String loScan = seq.toLowerCase(Locale.ENGLISH);
String hiScan = seq.toUpperCase(Locale.ENGLISH);
return (nextIndexOf(loScan) > -1) || (nextIndexOf(hiScan) > -1);
}
@Override
public String toString() {
return new String(input, pos, length - pos);
}
/**
* Caches short strings, as a flywheel pattern, to reduce GC load. Just for this doc, to prevent leaks.
* <p />
* Simplistic, and on hash collisions just falls back to creating a new string, vs a full HashMap with Entry list.
* That saves both having to create objects as hash keys, and running through the entry list, at the expense of
* some more duplicates.
*/
private String cacheString(final int start, final int count) {
final char[] val = input;
final String[] cache = stringCache;
// limit (no cache):
if (count > maxCacheLen)
return new String(val, start, count);
// calculate hash:
int hash = 0;
int offset = start;
for (int i = 0; i < count; i++) {
hash = 31 * hash + val[offset++];
}
// get from cache
final int index = hash & cache.length - 1;
String cached = cache[index];
if (cached == null) { // miss, add
cached = new String(val, start, count);
cache[index] = cached;
} else { // hashcode hit, check equality
if (rangeEquals(start, count, cached)) {
// hit
return cached;
} else { // hashcode conflict
cached = new String(val, start, count);
}
}
return cached;
}
/**
* Check if the value of the provided range equals the string.
*/
boolean rangeEquals(final int start, int count, final String cached) {
if (count == cached.length()) {
char one[] = input;
int i = start;
int j = 0;
while (count-- != 0) {
if (one[i++] != cached.charAt(j++))
return false;
}
return true;
}
return false;
}
}
| unlicense |
tkafalas/pentaho-kettle | engine/src/test/java/org/pentaho/di/job/entries/evaluatetablecontent/MockDriver.java | 3801 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.job.entries.evaluatetablecontent;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import org.mockito.stubbing.Answer;
public class MockDriver implements Driver {
private static final List<MockDriver> drivers = new ArrayList<MockDriver>();
public static synchronized void registerInstance() throws SQLException {
MockDriver driver = new MockDriver();
DriverManager.registerDriver( driver );
drivers.add( driver );
}
public static synchronized void deregeisterInstances() throws SQLException {
for ( Driver driver : drivers ) {
DriverManager.deregisterDriver( driver );
}
drivers.clear();
}
public MockDriver() {
}
@Override
public boolean acceptsURL( String url ) throws SQLException {
return true;
}
@Override
public Connection connect( String url, Properties info ) throws SQLException {
Connection conn = mock( Connection.class );
Statement stmt = mock( Statement.class );
ResultSet rs = mock( ResultSet.class );
ResultSetMetaData md = mock( ResultSetMetaData.class );
when( stmt.getMaxRows() ).thenReturn( 5 );
when( stmt.getResultSet() ).thenReturn( rs );
when( stmt.executeQuery( anyString() ) ).thenReturn( rs );
when( rs.getMetaData() ).thenReturn( md );
when( rs.getLong( anyInt() ) ).thenReturn( 5L );
when( rs.next() ).thenAnswer( new Answer<Boolean>() {
private int count = 0;
public Boolean answer( org.mockito.invocation.InvocationOnMock invocation ) throws Throwable {
return count++ == 0;
}
} );
when( md.getColumnCount() ).thenReturn( 1 );
when( md.getColumnName( anyInt() ) ).thenReturn( "count" );
when( md.getColumnType( anyInt() ) ).thenReturn( java.sql.Types.INTEGER );
when( conn.createStatement() ).thenReturn( stmt );
return conn;
}
@Override
public int getMajorVersion() {
return 0;
}
@Override
public int getMinorVersion() {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
@Override
public DriverPropertyInfo[] getPropertyInfo( String url, Properties info ) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean jdbcCompliant() {
// TODO Auto-generated method stub
return false;
}
}
| apache-2.0 |
wseyler/pentaho-kettle | core/src/main/java/org/pentaho/di/core/KettleAttributeInterface.java | 1533 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core;
public interface KettleAttributeInterface {
/**
* @return the key for this attribute, usually the repository code.
*/
public String getKey();
/**
* @return the xmlCode
*/
public String getXmlCode();
/**
* @return the repCode
*/
public String getRepCode();
/**
* @return the description
*/
public String getDescription();
/**
* @return the tooltip
*/
public String getTooltip();
/**
* @return the type
*/
public int getType();
/**
* @return The parent interface.
*/
public KettleAttributeInterface getParent();
}
| apache-2.0 |
bryce-anderson/netty | transport/src/main/java/io/netty/channel/DefaultSelectStrategy.java | 1101 | /*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* 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.netty.channel;
import io.netty.util.IntSupplier;
/**
* Default select strategy.
*/
final class DefaultSelectStrategy implements SelectStrategy {
static final SelectStrategy INSTANCE = new DefaultSelectStrategy();
private DefaultSelectStrategy() { }
@Override
public int calculateStrategy(IntSupplier selectSupplier, boolean hasTasks) throws Exception {
return hasTasks ? selectSupplier.get() : SelectStrategy.SELECT;
}
}
| apache-2.0 |
arnaudsj/titanium_mobile | android/titanium/src/org/appcelerator/kroll/KrollPropertyChange.java | 846 | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package org.appcelerator.kroll;
public class KrollPropertyChange {
protected String name;
protected Object oldValue, newValue;
public KrollPropertyChange(String name, Object oldValue, Object newValue) {
this.name = name;
this.oldValue = oldValue;
this.newValue = newValue;
}
public void fireEvent(KrollProxy proxy, KrollProxyListener listener) {
if (listener != null) {
listener.propertyChanged(name, oldValue, newValue, proxy);
}
}
public String getName() {
return name;
}
public Object getOldValue() {
return oldValue;
}
public Object getNewValue() {
return newValue;
}
}
| apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/inspection/defUse/UnusedVariable.java | 50 | class Foo {
public void foo() {
int i;
}
} | apache-2.0 |
kuzemchik/presto | presto-main/src/main/java/com/facebook/presto/metadata/SpecializedFunctionKey.java | 2138 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.metadata;
import com.facebook.presto.spi.type.Type;
import java.util.Map;
import java.util.Objects;
import static com.google.common.base.Preconditions.checkNotNull;
public class SpecializedFunctionKey
{
private final ParametricFunction function;
private final Map<String, Type> boundTypeParameters;
private final int arity;
public SpecializedFunctionKey(ParametricFunction function, Map<String, Type> boundTypeParameters, int arity)
{
this.function = checkNotNull(function, "function is null");
this.boundTypeParameters = checkNotNull(boundTypeParameters, "boundTypeParameters is null");
this.arity = arity;
}
public ParametricFunction getFunction()
{
return function;
}
public Map<String, Type> getBoundTypeParameters()
{
return boundTypeParameters;
}
public int getArity()
{
return arity;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SpecializedFunctionKey that = (SpecializedFunctionKey) o;
return Objects.equals(arity, that.arity) &&
Objects.equals(boundTypeParameters, that.boundTypeParameters) &&
Objects.equals(function.getSignature(), that.function.getSignature());
}
@Override
public int hashCode()
{
return Objects.hash(function.getSignature(), boundTypeParameters, arity);
}
}
| apache-2.0 |
zero-rp/miniblink49 | third_party/skia/platform_tools/android/app/src/com/skia/SkiaSampleView.java | 10208 | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package com.skia;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.opengl.EGL14;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;
public class SkiaSampleView extends GLSurfaceView {
private final SkiaSampleRenderer mSampleRenderer;
private boolean mRequestedOpenGLAPI; // true == use (desktop) OpenGL. false == use OpenGL ES.
private int mRequestedMSAASampleCount;
public SkiaSampleView(Context ctx, String cmdLineFlags, boolean useOpenGL, int msaaSampleCount) {
super(ctx);
mSampleRenderer = new SkiaSampleRenderer(this, cmdLineFlags);
mRequestedMSAASampleCount = msaaSampleCount;
setEGLContextClientVersion(2);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
setEGLConfigChooser(8, 8, 8, 8, 0, 8);
} else {
mRequestedOpenGLAPI = useOpenGL;
setEGLConfigChooser(new SampleViewEGLConfigChooser());
}
setRenderer(mSampleRenderer);
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int count = event.getPointerCount();
for (int i = 0; i < count; i++) {
final float x = event.getX(i);
final float y = event.getY(i);
final int owner = event.getPointerId(i);
int action = event.getAction() & MotionEvent.ACTION_MASK;
switch (action) {
case MotionEvent.ACTION_POINTER_UP:
action = MotionEvent.ACTION_UP;
break;
case MotionEvent.ACTION_POINTER_DOWN:
action = MotionEvent.ACTION_DOWN;
break;
default:
break;
}
final int finalAction = action;
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.handleClick(owner, x, y, finalAction);
}
});
}
return true;
}
public void inval() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.postInval();
}
});
}
public void terminate() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.term();
}
});
}
public void showOverview() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.showOverview();
}
});
}
public void nextSample() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.nextSample();
}
});
}
public void previousSample() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.previousSample();
}
});
}
public void goToSample(final int position) {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.goToSample(position);
}
});
}
public void toggleRenderingMode() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleRenderingMode();
}
});
}
public void toggleSlideshow() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleSlideshow();
}
});
}
public void toggleFPS() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleFPS();
}
});
}
public void toggleTiling() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleTiling();
}
});
}
public void toggleBBox() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.toggleBBox();
}
});
}
public void saveToPDF() {
queueEvent(new Runnable() {
@Override
public void run() {
mSampleRenderer.saveToPDF();
}
});
}
public boolean getUsesOpenGLAPI() {
return mRequestedOpenGLAPI;
}
public int getMSAASampleCount() {
return mSampleRenderer.getMSAASampleCount();
}
private class SampleViewEGLConfigChooser implements GLSurfaceView.EGLConfigChooser {
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
int numConfigs = 0;
int[] configSpec = null;
int[] value = new int[1];
int[] validAPIs = new int[] {
EGL14.EGL_OPENGL_API,
EGL14.EGL_OPENGL_ES_API
};
int initialAPI = mRequestedOpenGLAPI ? 0 : 1;
for (int i = initialAPI; i < validAPIs.length && numConfigs == 0; i++) {
int currentAPI = validAPIs[i];
EGL14.eglBindAPI(currentAPI);
// setup the renderableType which will only be included in the
// spec if we are attempting to get access to the OpenGL APIs.
int renderableType = EGL14.EGL_OPENGL_BIT;
if (currentAPI == EGL14.EGL_OPENGL_API) {
renderableType = EGL14.EGL_OPENGL_ES2_BIT;
}
if (mRequestedMSAASampleCount > 0) {
configSpec = new int[] {
EGL10.EGL_RED_SIZE, 8,
EGL10.EGL_GREEN_SIZE, 8,
EGL10.EGL_BLUE_SIZE, 8,
EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_SAMPLE_BUFFERS, 1,
EGL10.EGL_SAMPLES, mRequestedMSAASampleCount,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
// EGL_RENDERABLE_TYPE is only needed when attempting to use
// the OpenGL API (not ES) and causes many EGL drivers to fail
// with a BAD_ATTRIBUTE error.
if (!mRequestedOpenGLAPI) {
configSpec[16] = EGL10.EGL_NONE;
Log.i("Skia", "spec: " + configSpec);
}
if (!egl.eglChooseConfig(display, configSpec, null, 0, value)) {
Log.i("Skia", "Could not get MSAA context count: " + mRequestedMSAASampleCount);
}
numConfigs = value[0];
}
if (numConfigs <= 0) {
// Try without multisampling.
configSpec = new int[] {
EGL10.EGL_RED_SIZE, 8,
EGL10.EGL_GREEN_SIZE, 8,
EGL10.EGL_BLUE_SIZE, 8,
EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_STENCIL_SIZE, 8,
EGL10.EGL_RENDERABLE_TYPE, renderableType,
EGL10.EGL_NONE
};
// EGL_RENDERABLE_TYPE is only needed when attempting to use
// the OpenGL API (not ES) and causes many EGL drivers to fail
// with a BAD_ATTRIBUTE error.
if (!mRequestedOpenGLAPI) {
configSpec[12] = EGL10.EGL_NONE;
Log.i("Skia", "spec: " + configSpec);
}
if (!egl.eglChooseConfig(display, configSpec, null, 0, value)) {
Log.i("Skia", "Could not get non-MSAA context count");
}
numConfigs = value[0];
}
}
if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec");
}
// Get all matching configurations.
EGLConfig[] configs = new EGLConfig[numConfigs];
if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs, value)) {
throw new IllegalArgumentException("Could not get config data");
}
for (int i = 0; i < configs.length; ++i) {
EGLConfig config = configs[i];
if (findConfigAttrib(egl, display, config , EGL10.EGL_RED_SIZE, 0) == 8 &&
findConfigAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0) == 8 &&
findConfigAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0) == 8 &&
findConfigAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0) == 8 &&
findConfigAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0) == 8) {
return config;
}
}
throw new IllegalArgumentException("Could not find suitable EGL config");
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display,
EGLConfig config, int attribute, int defaultValue) {
int[] value = new int[1];
if (egl.eglGetConfigAttrib(display, config, attribute, value)) {
return value[0];
}
return defaultValue;
}
}
}
| apache-2.0 |
apache/maven | maven-compat/src/main/java/org/apache/maven/repository/metadata/GraphConflictResolver.java | 1822 | package org.apache.maven.repository.metadata;
/*
* 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 org.apache.maven.artifact.ArtifactScopeEnum;
/**
* Resolves conflicts in the supplied dependency graph.
* Different implementations will implement different conflict resolution policies.
*
* @author <a href="mailto:oleg@codehaus.org">Oleg Gusakov</a>
*/
public interface GraphConflictResolver
{
String ROLE = GraphConflictResolver.class.getName();
/**
* Cleanses the supplied graph by leaving only one directed versioned edge\
* between any two nodes, if multiple exists. Uses scope relationships, defined
* in <code>ArtifactScopeEnum</code>
*
* @param graph the "dirty" graph to be simplified via conflict resolution
* @param scope scope for which the graph should be resolved
*
* @return resulting "clean" graph for the specified scope
*
* @since 3.0
*/
MetadataGraph resolveConflicts( MetadataGraph graph, ArtifactScopeEnum scope )
throws GraphConflictResolutionException;
}
| apache-2.0 |
WilliamNouet/nifi | nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-cluster/src/main/java/org/apache/nifi/cluster/coordination/flow/FlowElection.java | 3255 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.cluster.coordination.flow;
import org.apache.nifi.cluster.protocol.DataFlow;
import org.apache.nifi.cluster.protocol.NodeIdentifier;
/**
* <p>
* A FlowElection is responsible for examining multiple versions of a dataflow and determining which of
* the versions is the "correct" version of the flow.
* </p>
*/
public interface FlowElection {
/**
* Checks if the election has completed or not.
*
* @return <code>true</code> if the election has completed, <code>false</code> otherwise.
*/
boolean isElectionComplete();
/**
* Returns <code>true</code> if a vote has already been counted for the given Node Identifier, <code>false</code> otherwise.
*
* @param nodeIdentifier the identifier of the node
* @return <code>true</code> if a vote has already been counted for the given Node Identifier, <code>false</code> otherwise.
*/
boolean isVoteCounted(NodeIdentifier nodeIdentifier);
/**
* If the election has not yet completed, adds the given DataFlow to the list of candidates
* (if it is not already in the running) and increments the number of votes for this DataFlow by 1.
* If the election has completed, the given candidate is ignored, and the already-elected DataFlow
* will be returned. If the election has not yet completed, a vote will be cast for the given
* candidate and <code>null</code> will be returned, signifying that no candidate has yet been chosen.
*
* @param candidate the DataFlow to vote for and add to the pool of candidates if not already present
* @param nodeIdentifier the identifier of the node casting the vote
*
* @return the elected {@link DataFlow}, or <code>null</code> if no DataFlow has yet been elected
*/
DataFlow castVote(DataFlow candidate, NodeIdentifier nodeIdentifier);
/**
* Returns the DataFlow that has been elected as the "correct" version of the flow, or <code>null</code>
* if the election has not yet completed.
*
* @return the DataFlow that has been elected as the "correct" version of the flow, or <code>null</code>
* if the election has not yet completed.
*/
DataFlow getElectedDataFlow();
/**
* Returns a human-readable description of the status of the election
*
* @return a human-readable description of the status of the election
*/
String getStatusDescription();
}
| apache-2.0 |
akosyakov/intellij-community | jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsProjectSerializationTest.java | 11503 | /*
* Copyright 2000-2012 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.jps.model.serialization;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.testFramework.PlatformTestUtil;
import org.jdom.Element;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsEncodingConfigurationService;
import org.jetbrains.jps.model.JpsEncodingProjectConfiguration;
import org.jetbrains.jps.model.artifact.JpsArtifactService;
import org.jetbrains.jps.model.java.*;
import org.jetbrains.jps.model.library.JpsLibrary;
import org.jetbrains.jps.model.library.JpsOrderRootType;
import org.jetbrains.jps.model.library.sdk.JpsSdkReference;
import org.jetbrains.jps.model.module.*;
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* @author nik
*/
public class JpsProjectSerializationTest extends JpsSerializationTestCase {
public static final String SAMPLE_PROJECT_PATH = "/jps/model-serialization/testData/sampleProject";
public void testLoadProject() {
loadProject(SAMPLE_PROJECT_PATH);
String baseDirPath = getTestDataFileAbsolutePath(SAMPLE_PROJECT_PATH);
assertTrue(FileUtil.filesEqual(new File(baseDirPath), JpsModelSerializationDataService.getBaseDirectory(myProject)));
assertEquals("sampleProjectName", myProject.getName());
List<JpsModule> modules = myProject.getModules();
assertEquals(3, modules.size());
JpsModule main = modules.get(0);
assertEquals("main", main.getName());
JpsModule util = modules.get(1);
assertEquals("util", util.getName());
JpsModule xxx = modules.get(2);
assertEquals("xxx", xxx.getName());
assertTrue(FileUtil.filesEqual(new File(baseDirPath, "util"), JpsModelSerializationDataService.getBaseDirectory(util)));
List<JpsLibrary> libraries = myProject.getLibraryCollection().getLibraries();
assertEquals(3, libraries.size());
List<JpsDependencyElement> dependencies = util.getDependenciesList().getDependencies();
assertEquals(4, dependencies.size());
JpsSdkDependency sdkDependency = assertInstanceOf(dependencies.get(0), JpsSdkDependency.class);
assertSame(JpsJavaSdkType.INSTANCE, sdkDependency.getSdkType());
JpsSdkReference<?> reference = sdkDependency.getSdkReference();
assertNotNull(reference);
assertEquals("1.5", reference.getSdkName());
assertInstanceOf(dependencies.get(1), JpsModuleSourceDependency.class);
assertInstanceOf(dependencies.get(2), JpsLibraryDependency.class);
assertInstanceOf(dependencies.get(3), JpsLibraryDependency.class);
JpsSdkDependency inheritedSdkDependency = assertInstanceOf(main.getDependenciesList().getDependencies().get(0), JpsSdkDependency.class);
JpsSdkReference<?> projectSdkReference = inheritedSdkDependency.getSdkReference();
assertNotNull(projectSdkReference);
assertEquals("1.6", projectSdkReference.getSdkName());
assertEquals(getUrl("xxx/output"), JpsJavaExtensionService.getInstance().getOutputUrl(xxx, true));
assertEquals(getUrl("xxx/output"), JpsJavaExtensionService.getInstance().getOutputUrl(xxx, false));
}
public void testFileBasedProjectNameAndBaseDir() {
String relativePath = "/jps/model-serialization/testData/run-configurations/run-configurations.ipr";
String absolutePath = getTestDataFileAbsolutePath(relativePath);
loadProject(relativePath);
assertEquals("run-configurations", myProject.getName());
assertTrue(FileUtil.filesEqual(new File(absolutePath).getParentFile(), JpsModelSerializationDataService.getBaseDirectory(myProject)));
}
public void testDirectoryBasedProjectName() {
loadProject("/jps/model-serialization/testData/run-configurations-dir");
assertEquals("run-configurations-dir", myProject.getName());
}
public void testImlUnderDotIdea() {
loadProject("/jps/model-serialization/testData/imlUnderDotIdea");
JpsModule module = assertOneElement(myProject.getModules());
JpsModuleSourceRoot root = assertOneElement(module.getSourceRoots());
assertEquals(getUrl("src"), root.getUrl());
}
public void testProjectSdkWithoutType() {
loadProject("/jps/model-serialization/testData/projectSdkWithoutType/projectSdkWithoutType.ipr");
JpsSdkReference<JpsDummyElement> reference = myProject.getSdkReferencesTable().getSdkReference(JpsJavaSdkType.INSTANCE);
assertNotNull(reference);
assertEquals("1.6", reference.getSdkName());
}
public void testInvalidDependencyScope() {
loadProject("/jps/model-serialization/testData/invalidDependencyScope/invalidDependencyScope.ipr");
JpsModule module = assertOneElement(myProject.getModules());
List<JpsDependencyElement> dependencies = module.getDependenciesList().getDependencies();
assertEquals(3, dependencies.size());
JpsJavaDependencyExtension extension = JpsJavaExtensionService.getInstance().getDependencyExtension(dependencies.get(2));
assertNotNull(extension);
assertEquals(JpsJavaDependencyScope.COMPILE, extension.getScope());
}
public void testDuplicatedModuleLibrary() {
loadProject("/jps/model-serialization/testData/duplicatedModuleLibrary/duplicatedModuleLibrary.ipr");
JpsModule module = assertOneElement(myProject.getModules());
List<JpsDependencyElement> dependencies = module.getDependenciesList().getDependencies();
assertEquals(4, dependencies.size());
JpsLibrary lib1 = assertInstanceOf(dependencies.get(2), JpsLibraryDependency.class).getLibrary();
assertNotNull(lib1);
assertSameElements(lib1.getRootUrls(JpsOrderRootType.COMPILED), getUrl("data/lib1"));
JpsLibrary lib2 = assertInstanceOf(dependencies.get(3), JpsLibraryDependency.class).getLibrary();
assertNotSame(lib1, lib2);
assertNotNull(lib2);
assertSameElements(lib2.getRootUrls(JpsOrderRootType.COMPILED), getUrl("data/lib2"));
}
public void testDotIdeaUnderDotIdea() {
loadProject("/jps/model-serialization/testData/matryoshka/.idea");
JpsJavaProjectExtension extension = JpsJavaExtensionService.getInstance().getProjectExtension(myProject);
assertNotNull(extension);
assertEquals(getUrl("out"), extension.getOutputUrl());
}
public void testLoadEncoding() {
loadProject(SAMPLE_PROJECT_PATH);
JpsEncodingConfigurationService service = JpsEncodingConfigurationService.getInstance();
assertEquals("UTF-8", service.getProjectEncoding(myModel));
JpsEncodingProjectConfiguration configuration = service.getEncodingConfiguration(myProject);
assertNotNull(configuration);
assertEquals("UTF-8", configuration.getProjectEncoding());
assertEquals("windows-1251", configuration.getEncoding(new File(getAbsolutePath("util"))));
assertEquals("windows-1251", configuration.getEncoding(new File(getAbsolutePath("util/foo/bar/file.txt"))));
assertEquals("UTF-8", configuration.getEncoding(new File(getAbsolutePath("other"))));
}
public void testResourceRoots() {
String projectPath = "/jps/model-serialization/testData/resourceRoots/";
loadProject(projectPath + "resourceRoots.ipr");
JpsModule module = assertOneElement(myProject.getModules());
List<JpsModuleSourceRoot> roots = module.getSourceRoots();
assertSame(JavaSourceRootType.SOURCE, roots.get(0).getRootType());
checkResourceRoot(roots.get(1), false, "");
checkResourceRoot(roots.get(2), true, "");
checkResourceRoot(roots.get(3), true, "foo");
doTestSaveModule(module, projectPath + "resourceRoots.iml");
}
private static void checkResourceRoot(JpsModuleSourceRoot root, boolean forGenerated, String relativeOutput) {
assertSame(JavaResourceRootType.RESOURCE, root.getRootType());
JavaResourceRootProperties properties = root.getProperties(JavaResourceRootType.RESOURCE);
assertNotNull(properties);
assertEquals(forGenerated, properties.isForGeneratedSources());
assertEquals(relativeOutput, properties.getRelativeOutputPath());
}
public void testSaveProject() {
loadProject(SAMPLE_PROJECT_PATH);
List<JpsModule> modules = myProject.getModules();
doTestSaveModule(modules.get(0), SAMPLE_PROJECT_PATH + "/main.iml");
doTestSaveModule(modules.get(1), SAMPLE_PROJECT_PATH + "/util/util.iml");
//tod[nik] remember that test output root wasn't specified and doesn't save it to avoid unnecessary modifications of iml files
//doTestSaveModule(modules.get(2), "xxx/xxx.iml");
File[] libs = getFileInSampleProject(".idea/libraries").listFiles();
assertNotNull(libs);
for (File libFile : libs) {
String libName = FileUtil.getNameWithoutExtension(libFile);
JpsLibrary library = myProject.getLibraryCollection().findLibrary(libName);
assertNotNull(libName, library);
doTestSaveLibrary(libFile, libName, library);
}
}
private void doTestSaveLibrary(File libFile, String libName, JpsLibrary library) {
try {
Element actual = new Element("library");
JpsLibraryTableSerializer.saveLibrary(library, actual, libName);
JpsMacroExpander
macroExpander = JpsProjectLoader.createProjectMacroExpander(Collections.<String, String>emptyMap(), getFileInSampleProject(""));
Element rootElement = JpsLoaderBase.loadRootElement(libFile, macroExpander);
Element expected = rootElement.getChild("library");
PlatformTestUtil.assertElementsEqual(expected, actual);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
private void doTestSaveModule(JpsModule module, final String moduleFilePath) {
try {
Element actual = JDomSerializationUtil.createComponentElement("NewModuleRootManager");
JpsModuleRootModelSerializer.saveRootModel(module, actual);
File imlFile = new File(getTestDataFileAbsolutePath(moduleFilePath));
Element rootElement = loadModuleRootTag(imlFile);
Element expected = JDomSerializationUtil.findComponent(rootElement, "NewModuleRootManager");
PlatformTestUtil.assertElementsEqual(expected, actual);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public File getFileInSampleProject(String relativePath) {
return new File(getTestDataFileAbsolutePath(SAMPLE_PROJECT_PATH + "/" + relativePath));
}
public void testLoadIdeaProject() {
long start = System.currentTimeMillis();
loadProjectByAbsolutePath(PathManager.getHomePath());
assertTrue(myProject.getModules().size() > 0);
System.out.println("JpsProjectSerializationTest: " + myProject.getModules().size() + " modules, " + myProject.getLibraryCollection().getLibraries().size() + " libraries and " +
JpsArtifactService.getInstance().getArtifacts(myProject).size() + " artifacts loaded in " + (System.currentTimeMillis() - start) + "ms");
}
}
| apache-2.0 |
rodriguezdevera/sakai | edu-services/gradebook-service/api/src/java/org/sakaiproject/service/gradebook/shared/GradebookExternalAssessmentService.java | 14476 | /**********************************************************************************
*
* $Id$
*
***********************************************************************************
*
* Copyright (c) 2007, 2008 The Sakai 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/ECL-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.sakaiproject.service.gradebook.shared;
import java.util.Date;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* This service is designed for use by external assessment engines. These use
* the Gradebook as a passive mirror of their own assignments and scores,
* letting Gradebook users see those assignments alongside Gradebook-managed
* assignments, and combine them when calculating a course grade. The Gradebook
* application itself will not modify externally-managed assignments and scores.
*
* <b>WARNING</b>: Because the Gradebook project team is not responsible for
* defining the external clients' requirements, the Gradebook service does not
* attempt to guess at their authorization needs. Our administrative and
* external-assessment methods simply follow orders and assume that the caller
* has taken the responsibility of "doing the right thing." DO NOT wrap these
* methods in an open web service!
*/
public interface GradebookExternalAssessmentService {
/**
* @deprecated Replaced by
* {@link addExternalAssessment(String, String, String, String, Double, Date, String, Boolean)}
*/
public void addExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, double points, Date dueDate, String externalServiceDescription)
throws GradebookNotFoundException, ConflictingAssignmentNameException,
ConflictingExternalIdException, AssignmentHasIllegalPointsException;
/**
* Add an externally-managed assessment to a gradebook to be treated as a
* read-only assignment. The gradebook application will not modify the
* assessment properties or create any scores for the assessment.
* Since each assignment in a given gradebook must have a unique name,
* conflicts are possible.
*
* @param gradebookUid
* @param externalId
* some unique identifier which Samigo uses for the assessment.
* The externalId is globally namespaced within the gradebook, so
* if other apps decide to put assessments into the gradebook,
* they should prefix their externalIds with a well known (and
* unique within sakai) string.
* @param externalUrl
* a link to go to if the instructor or student wants to look at the assessment
* in Samigo; if null, no direct link will be provided in the
* gradebook, and the user will have to navigate to the assessment
* within the other application
* @param title
* @param points
* this is the total amount of points available and must be greater than zero.
* it could be null if it's an ungraded item.
* @param dueDate
* @param externalServiceDescription
* @param ungraded
*
* @param externalServiceDescription
* what to display as the source of the assignment (e.g., "from Samigo")
*
*/
public void addExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, Double points, Date dueDate, String externalServiceDescription, Boolean ungraded)
throws GradebookNotFoundException, ConflictingAssignmentNameException,
ConflictingExternalIdException, AssignmentHasIllegalPointsException;
/**
* This method is identical to {@link #addExternalAssessment(String, String, String, String, Double, Date, String, Boolean)} but
* allows you to also specify the associated Category for this assignment. If the gradebook is set up for categories and
* categoryId is null, assignment category will be unassigned
* @param gradebookUid
* @param externalId
* @param externalUrl
* @param title
* @param points
* @param dueDate
* @param externalServiceDescription
* @param ungraded
* @param categoryId
* @throws GradebookNotFoundException
* @throws ConflictingAssignmentNameException
* @throws ConflictingExternalIdException
* @throws AssignmentHasIllegalPointsException
* @throws InvalidCategoryException
*/
public void addExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, Double points, Date dueDate, String externalServiceDescription, Boolean ungraded, Long categoryId)
throws GradebookNotFoundException, ConflictingAssignmentNameException,
ConflictingExternalIdException, AssignmentHasIllegalPointsException, InvalidCategoryException;
/**
* @deprecated Replaced by
* {@link updateExternalAssessment(String, String, String, String, Double, Date, Boolean)}
*/
public void updateExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, double points, Date dueDate)
throws GradebookNotFoundException, AssessmentNotFoundException,
ConflictingAssignmentNameException, AssignmentHasIllegalPointsException;
/**
* Update an external assessment
* @param gradebookUid
* @param externalId
* @param externalUrl
* @param title
* @param points
* @param dueDate
* @param ungraded
* @throws GradebookNotFoundException
* @throws AssessmentNotFoundException
* @throws ConflictingAssignmentNameException
* @throws AssignmentHasIllegalPointsException
*/
public void updateExternalAssessment(String gradebookUid, String externalId, String externalUrl,
String title, Double points, Date dueDate, Boolean ungraded)
throws GradebookNotFoundException, AssessmentNotFoundException,
ConflictingAssignmentNameException, AssignmentHasIllegalPointsException;
/**
* Remove the assessment reference from the gradebook. Although Samigo
* doesn't currently delete assessments, an instructor can retract an
* assessment to keep it from students. Since such an assessment would
* presumably no longer be used to calculate final grades, Samigo should
* also remove that assessment from the gradebook.
*
* @param externalId
* the UID of the assessment
*/
public void removeExternalAssessment(String gradebookUid, String externalId)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Updates an external score for an external assignment in the gradebook.
*
* @param gradebookUid
* The Uid of the gradebook
* @param externalId
* The external ID of the assignment/assessment
* @param studentUid
* The unique id of the student
* @param points
* The number of points earned on this assessment, or null if a score
* should be removed
*/
public void updateExternalAssessmentScore(String gradebookUid, String externalId,
String studentUid, String points)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
*
* @param gradebookUid
* @param externalId
* @param studentUidsToScores
* @throws GradebookNotFoundException
* @throws AssessmentNotFoundException
*
* @deprecated Replaced by
* {@link updateExternalAssessmentScoresString(String, String, Map<String, String)}
*/
public void updateExternalAssessmentScores(String gradebookUid,
String externalId, Map<String, Double> studentUidsToScores)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Updates a set of external scores for an external assignment in the gradebook.
*
* @param gradebookUid
* The Uid of the gradebook
* @param externalId
* The external ID of the assignment/assessment
* @param studentUidsToScores
* A map whose String keys are the unique ID strings of the students and whose
* String values are points earned on this assessment or null if the score
* should be removed.
*/
public void updateExternalAssessmentScoresString(String gradebookUid,
String externalId, Map<String, String> studentUidsToScores)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Updates an external comment for an external assignment in the gradebook.
*
* @param gradebookUid
* The Uid of the gradebook
* @param externalId
* The external ID of the assignment/assessment
* @param studentUid
* The unique id of the student
* @param comment
* The comment to be added to this grade, or null if a comment
* should be removed
*/
public void updateExternalAssessmentComment(String gradebookUid,
String externalId, String studentUid, String comment )
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Updates a set of external comments for an external assignment in the gradebook.
*
* @param gradebookUid
* The Uid of the gradebook
* @param externalId
* The external ID of the assignment/assessment
* @param studentUidsToScores
* A map whose String keys are the unique ID strings of the students and whose
* String values are comments or null if the comments
* should be removed.
*/
public void updateExternalAssessmentComments(String gradebookUid,
String externalId, Map<String, String> studentUidsToComments)
throws GradebookNotFoundException, AssessmentNotFoundException;
/**
* Check to see if an assignment with the given name already exists
* in the given gradebook. This will give external assessment systems
* a chance to avoid the ConflictingAssignmentNameException.
*/
public boolean isAssignmentDefined(String gradebookUid, String assignmentTitle)
throws GradebookNotFoundException;
/**
* Check to see if an assignment with the given external id already exists
* in the given gradebook. This will give external assessment systems
* a chance to avoid the ConflictingExternalIdException.
*
* @param gradebookUid The gradebook's unique identifier
* @param externalId The external assessment's external identifier
*/
public boolean isExternalAssignmentDefined(String gradebookUid, String externalId)
throws GradebookNotFoundException;
/**
* Check with the appropriate external service if a specific assignment is
* available only to groups.
*
* @param gradebookUid The gradebook's unique identifier
* @param externalId The external assessment's external identifier
*/
public boolean isExternalAssignmentGrouped(String gradebookUid, String externalId)
throws GradebookNotFoundException;
/**
* Check with the appropriate external service if a specific assignment is
* available to a specific user (i.e., the user is in an appropriate group).
* Note that this method will return true if the assignment exists in the
* gradebook and is marked as externally maintained while no provider
* recognizes it; this is to maintain a safer default (no change from the
* 2.8 release) for tools that have not implemented a provider.
*
* @param gradebookUid The gradebook's unique identifier
* @param externalId The external assessment's external identifier
* @param userId The user ID to check
*/
public boolean isExternalAssignmentVisible(String gradebookUid, String externalId, String userId)
throws GradebookNotFoundException;
/**
* Retrieve all assignments for a gradebook that are marked as externally
* maintained and are visible to the current user. Assignments may be included
* with a null providerAppKey, indicating that the gradebook references the
* assignment, but no provider claims responsibility for it.
*
* @param gradebookUid The gradebook's unique identifier
* @return A map from the externalId of each activity to the providerAppKey
*/
public Map<String, String> getExternalAssignmentsForCurrentUser(String gradebookUid)
throws GradebookNotFoundException;
/**
* Retrieve a list of all visible, external assignments for a set of users.
*
* @param gradebookUid The gradebook's unique identifier
* @param studentIds The collection of student IDs for which to retrieve assignments
* @return A map from the student ID to all visible, external activity IDs
*/
public Map<String, List<String>> getVisibleExternalAssignments(String gradebookUid, Collection<String> studentIds)
throws GradebookNotFoundException;
/**
* Register a new ExternalAssignmentProvider for handling the integration of external
* assessment sources with the sakai gradebook
* Registering more than once will overwrite the current with the new one
*
* @param provider the provider implementation object
*/
public void registerExternalAssignmentProvider(ExternalAssignmentProvider provider);
/**
* Remove/unregister any ExternalAssignmentProvider which is currently registered,
* does nothing if they provider does not exist
*
* @param providerAppKey the unique app key for a provider
*/
public void unregisterExternalAssignmentProvider(String providerAppKey);
/**
* Checks to see whether a gradebook with the given uid exists.
*
* @param gradebookUid
* The gradebook UID to check
* @return Whether the gradebook exists
*/
public boolean isGradebookDefined(String gradebookUid);
/**
* Break the connection between an external assessment engine and an assessment which
* it created, giving it up to the Gradebook application to control from now on.
*
* @param gradebookUid
* @param externalId
*/
public void setExternalAssessmentToGradebookAssignment(String gradebookUid, String externalId);
/**
* Get the category of a gradebook with the externalId given
*
* @param gradebookUId
* @param externalId
* @return
*/
public Long getExternalAssessmentCategoryId(String gradebookUId, String externalId);
}
| apache-2.0 |
apratkin/pentaho-kettle | core/src/org/pentaho/di/core/vfs/configuration/KettleFileSystemConfigBuilderFactory.java | 3605 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core.vfs.configuration;
import java.io.IOException;
import java.lang.reflect.Method;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
/**
* This class supports overriding of config builders by supplying a VariableSpace containing a variable in the format of
* vfs.[scheme].config.parser where [scheme] is one of the VFS schemes (file, http, sftp, etc...)
*
* @author cboyden
*/
public class KettleFileSystemConfigBuilderFactory {
private static Class<?> PKG = KettleVFS.class; // for i18n purposes, needed by Translator2!!
/**
* This factory returns a FileSystemConfigBuilder. Custom FileSystemConfigBuilders can be created by implementing the
* {@link IKettleFileSystemConfigBuilder} or overriding the {@link KettleGenericFileSystemConfigBuilder}
*
* @see org.apache.commons.vfs.FileSystemConfigBuilder
*
* @param varSpace
* A Kettle variable space for resolving VFS config parameters
* @param scheme
* The VFS scheme (FILE, HTTP, SFTP, etc...)
* @return A FileSystemConfigBuilder that can translate Kettle variables into VFS config parameters
* @throws IOException
*/
public static IKettleFileSystemConfigBuilder getConfigBuilder( VariableSpace varSpace, String scheme ) throws IOException {
IKettleFileSystemConfigBuilder result = null;
// Attempt to load the Config Builder from a variable: vfs.config.parser = class
String parserClass = varSpace.getVariable( "vfs." + scheme + ".config.parser" );
if ( parserClass != null ) {
try {
Class<?> configBuilderClass =
KettleFileSystemConfigBuilderFactory.class.getClassLoader().loadClass( parserClass );
Method mGetInstance = configBuilderClass.getMethod( "getInstance" );
if ( ( mGetInstance != null )
&& ( IKettleFileSystemConfigBuilder.class.isAssignableFrom( mGetInstance.getReturnType() ) ) ) {
result = (IKettleFileSystemConfigBuilder) mGetInstance.invoke( null );
} else {
result = (IKettleFileSystemConfigBuilder) configBuilderClass.newInstance();
}
} catch ( Exception e ) {
// Failed to load custom parser. Throw exception.
throw new IOException( BaseMessages.getString( PKG, "CustomVfsSettingsParser.Log.FailedToLoad" ) );
}
} else {
// No custom parser requested, load default
if ( scheme.equalsIgnoreCase( "sftp" ) ) {
result = KettleSftpFileSystemConfigBuilder.getInstance();
} else {
result = KettleGenericFileSystemConfigBuilder.getInstance();
}
}
return result;
}
}
| apache-2.0 |
dantuffery/elasticsearch | src/test/java/org/elasticsearch/action/RejectionActionTests.java | 4951 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action;
import com.google.common.collect.Lists;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope;
import org.junit.Test;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.Matchers.equalTo;
/**
*/
@ClusterScope(scope = ElasticsearchIntegrationTest.Scope.SUITE, numDataNodes = 2)
public class RejectionActionTests extends ElasticsearchIntegrationTest {
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return ImmutableSettings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put("threadpool.search.size", 1)
.put("threadpool.search.queue_size", 1)
.put("threadpool.index.size", 1)
.put("threadpool.index.queue_size", 1)
.put("threadpool.get.size", 1)
.put("threadpool.get.queue_size", 1)
.build();
}
@Test
public void simulateSearchRejectionLoad() throws Throwable {
for (int i = 0; i < 10; i++) {
client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "1").get();
}
int numberOfAsyncOps = randomIntBetween(200, 700);
final CountDownLatch latch = new CountDownLatch(numberOfAsyncOps);
final CopyOnWriteArrayList<Object> responses = Lists.newCopyOnWriteArrayList();
for (int i = 0; i < numberOfAsyncOps; i++) {
client().prepareSearch("test")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setQuery(QueryBuilders.matchQuery("field", "1"))
.execute(new ActionListener<SearchResponse>() {
@Override
public void onResponse(SearchResponse searchResponse) {
responses.add(searchResponse);
latch.countDown();
}
@Override
public void onFailure(Throwable e) {
responses.add(e);
latch.countDown();
}
});
}
latch.await();
assertThat(responses.size(), equalTo(numberOfAsyncOps));
// validate all responses
for (Object response : responses) {
if (response instanceof SearchResponse) {
SearchResponse searchResponse = (SearchResponse) response;
for (ShardSearchFailure failure : searchResponse.getShardFailures()) {
assertTrue("got unexpected reason..." + failure.reason(), failure.reason().toLowerCase(Locale.ENGLISH).contains("rejected"));
}
} else {
Throwable t = (Throwable) response;
Throwable unwrap = ExceptionsHelper.unwrapCause(t);
if (unwrap instanceof SearchPhaseExecutionException) {
SearchPhaseExecutionException e = (SearchPhaseExecutionException) unwrap;
for (ShardSearchFailure failure : e.shardFailures()) {
assertTrue("got unexpected reason..." + failure.reason(), failure.reason().toLowerCase(Locale.ENGLISH).contains("rejected"));
}
} else if ((unwrap instanceof EsRejectedExecutionException) == false) {
throw new AssertionError("unexpected failure", (Throwable) response);
}
}
}
}
}
| apache-2.0 |
marsorp/blog | presto166/presto-parser/src/main/java/com/facebook/presto/sql/tree/NotExpression.java | 1998 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.tree;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
public class NotExpression
extends Expression
{
private final Expression value;
public NotExpression(Expression value)
{
this(Optional.empty(), value);
}
public NotExpression(NodeLocation location, Expression value)
{
this(Optional.of(location), value);
}
private NotExpression(Optional<NodeLocation> location, Expression value)
{
super(location);
requireNonNull(value, "value is null");
this.value = value;
}
public Expression getValue()
{
return value;
}
@Override
public <R, C> R accept(AstVisitor<R, C> visitor, C context)
{
return visitor.visitNotExpression(this, context);
}
@Override
public List<Node> getChildren()
{
return ImmutableList.of(value);
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NotExpression that = (NotExpression) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode()
{
return value.hashCode();
}
}
| apache-2.0 |
kdwink/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/GuessTypeParameters.java | 10162 | /*
* Copyright 2000-2013 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.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.intention.impl.TypeExpression;
import com.intellij.codeInsight.template.TemplateBuilder;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author ven
*/
public class GuessTypeParameters {
private final JVMElementFactory myFactory;
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters");
public GuessTypeParameters(JVMElementFactory factory) {
myFactory = factory;
}
private List<PsiType> matchingTypeParameters (PsiType[] paramVals, PsiTypeParameter[] params, ExpectedTypeInfo info) {
PsiType type = info.getType();
int kind = info.getKind();
List<PsiType> result = new ArrayList<PsiType>();
for (int i = 0; i < paramVals.length; i++) {
PsiType val = paramVals[i];
if (val != null) {
switch (kind) {
case ExpectedTypeInfo.TYPE_STRICTLY:
if (val.equals(type)) result.add(myFactory.createType(params[i]));
break;
case ExpectedTypeInfo.TYPE_OR_SUBTYPE:
if (type.isAssignableFrom(val)) result.add(myFactory.createType(params[i]));
break;
case ExpectedTypeInfo.TYPE_OR_SUPERTYPE:
if (val.isAssignableFrom(type)) result.add(myFactory.createType(params[i]));
break;
}
}
}
return result;
}
public void setupTypeElement (PsiTypeElement typeElement, ExpectedTypeInfo[] infos, PsiSubstitutor substitutor,
TemplateBuilder builder, @Nullable PsiElement context, PsiClass targetClass) {
LOG.assertTrue(typeElement.isValid());
ApplicationManager.getApplication().assertWriteAccessAllowed();
PsiManager manager = typeElement.getManager();
GlobalSearchScope scope = typeElement.getResolveScope();
Project project = manager.getProject();
if (infos.length == 1 && substitutor != null && substitutor != PsiSubstitutor.EMPTY) {
ExpectedTypeInfo info = infos[0];
Map<PsiTypeParameter, PsiType> map = substitutor.getSubstitutionMap();
PsiType[] vals = map.values().toArray(PsiType.createArray(map.size()));
PsiTypeParameter[] params = map.keySet().toArray(new PsiTypeParameter[map.size()]);
List<PsiType> types = matchingTypeParameters(vals, params, info);
if (!types.isEmpty()) {
ContainerUtil.addAll(types, ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project));
builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
return;
}
else {
PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
PsiType type = info.getType();
PsiType defaultType = info.getDefaultType();
try {
PsiTypeElement inplaceTypeElement = ((PsiVariable)factory.createVariableDeclarationStatement("foo", type, null).getDeclaredElements()[0]).getTypeElement();
PsiSubstitutor rawingSubstitutor = getRawingSubstitutor (context, targetClass);
int substitionResult = substituteToTypeParameters(typeElement, inplaceTypeElement, vals, params, builder, rawingSubstitutor, true);
if (substitionResult != SUBSTITUTED_NONE) {
if (substitionResult == SUBSTITUTED_IN_PARAMETERS) {
PsiJavaCodeReferenceElement refElement = typeElement.getInnermostComponentReferenceElement();
LOG.assertTrue(refElement != null && refElement.getReferenceNameElement() != null);
type = getComponentType(type);
LOG.assertTrue(type != null);
defaultType = getComponentType(defaultType);
LOG.assertTrue(defaultType != null);
ExpectedTypeInfo info1 = ExpectedTypesProvider.createInfo(((PsiClassType)defaultType).rawType(),
ExpectedTypeInfo.TYPE_STRICTLY,
((PsiClassType)defaultType).rawType(),
info.getTailType());
MyTypeVisitor visitor = new MyTypeVisitor(manager, scope);
builder.replaceElement(refElement.getReferenceNameElement(),
new TypeExpression(project, ExpectedTypesProvider.processExpectedTypes(new ExpectedTypeInfo[]{info1}, visitor, project)));
}
return;
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
PsiType[] types = infos.length == 0 ? new PsiType[] {typeElement.getType()} : ExpectedTypesProvider.processExpectedTypes(infos, new MyTypeVisitor(manager, scope), project);
builder.replaceElement(typeElement,
new TypeExpression(project, types));
}
private static PsiSubstitutor getRawingSubstitutor(PsiElement context, PsiClass targetClass) {
if (context == null || targetClass == null) return PsiSubstitutor.EMPTY;
PsiTypeParameterListOwner currContext = PsiTreeUtil.getParentOfType(context, PsiTypeParameterListOwner.class);
PsiManager manager = context.getManager();
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
while (currContext != null && !manager.areElementsEquivalent(currContext, targetClass)) {
PsiTypeParameter[] typeParameters = currContext.getTypeParameters();
substitutor = JavaPsiFacade.getInstance(context.getProject()).getElementFactory().createRawSubstitutor(substitutor, typeParameters);
currContext = currContext.getContainingClass();
}
return substitutor;
}
@Nullable
private static PsiClassType getComponentType (PsiType type) {
type = type.getDeepComponentType();
if (type instanceof PsiClassType) return (PsiClassType)type;
return null;
}
private static final int SUBSTITUTED_NONE = 0;
private static final int SUBSTITUTED_IN_REF = 1;
private static final int SUBSTITUTED_IN_PARAMETERS = 2;
private int substituteToTypeParameters (PsiTypeElement typeElement,
PsiTypeElement inplaceTypeElement,
PsiType[] paramVals,
PsiTypeParameter[] params,
TemplateBuilder builder,
PsiSubstitutor rawingSubstitutor,
boolean toplevel) {
PsiType type = inplaceTypeElement.getType();
List<PsiType> types = new ArrayList<PsiType>();
for (int i = 0; i < paramVals.length; i++) {
PsiType val = paramVals[i];
if (val == null) return SUBSTITUTED_NONE;
if (type.equals(val)) {
types.add(myFactory.createType(params[i]));
}
}
if (!types.isEmpty()) {
Project project = typeElement.getProject();
PsiType substituted = rawingSubstitutor.substitute(type);
if (!CommonClassNames.JAVA_LANG_OBJECT.equals(substituted.getCanonicalText()) && (toplevel || substituted.equals(type))) {
types.add(substituted);
}
builder.replaceElement(typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size()))));
return toplevel ? SUBSTITUTED_IN_REF : SUBSTITUTED_IN_PARAMETERS;
}
boolean substituted = false;
PsiJavaCodeReferenceElement ref = typeElement.getInnermostComponentReferenceElement();
PsiJavaCodeReferenceElement inplaceRef = inplaceTypeElement.getInnermostComponentReferenceElement();
if (ref != null) {
LOG.assertTrue(inplaceRef != null);
PsiTypeElement[] innerTypeElements = ref.getParameterList().getTypeParameterElements();
PsiTypeElement[] inplaceInnerTypeElements = inplaceRef.getParameterList().getTypeParameterElements();
for (int i = 0; i < innerTypeElements.length; i++) {
substituted |= substituteToTypeParameters(innerTypeElements[i], inplaceInnerTypeElements[i], paramVals, params, builder,
rawingSubstitutor, false) != SUBSTITUTED_NONE;
}
}
return substituted ? SUBSTITUTED_IN_PARAMETERS : SUBSTITUTED_NONE;
}
public static class MyTypeVisitor extends PsiTypeVisitor<PsiType> {
private final GlobalSearchScope myResolveScope;
private final PsiManager myManager;
public MyTypeVisitor(PsiManager manager, GlobalSearchScope resolveScope) {
myManager = manager;
myResolveScope = resolveScope;
}
@Override
public PsiType visitType(PsiType type) {
if (type.equals(PsiType.NULL)) return PsiType.getJavaLangObject(myManager, myResolveScope);
return type;
}
@Override
public PsiType visitCapturedWildcardType(PsiCapturedWildcardType capturedWildcardType) {
return capturedWildcardType.getUpperBound().accept(this);
}
}
}
| apache-2.0 |
pauloricardomg/cassandra | test/unit/org/apache/cassandra/repair/consistent/AbstractConsistentSessionTest.java | 3628 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.repair.consistent;
import java.net.UnknownHostException;
import java.util.Set;
import java.util.UUID;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.junit.Ignore;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.streaming.PreviewKind;
import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.UUIDGen;
@Ignore
public abstract class AbstractConsistentSessionTest
{
protected static final InetAddressAndPort COORDINATOR;
protected static final InetAddressAndPort PARTICIPANT1;
protected static final InetAddressAndPort PARTICIPANT2;
protected static final InetAddressAndPort PARTICIPANT3;
static
{
try
{
COORDINATOR = InetAddressAndPort.getByName("10.0.0.1");
PARTICIPANT1 = InetAddressAndPort.getByName("10.0.0.1");
PARTICIPANT2 = InetAddressAndPort.getByName("10.0.0.2");
PARTICIPANT3 = InetAddressAndPort.getByName("10.0.0.3");
}
catch (UnknownHostException e)
{
throw new AssertionError(e);
}
DatabaseDescriptor.daemonInitialization();
}
protected static final Set<InetAddressAndPort> PARTICIPANTS = ImmutableSet.of(PARTICIPANT1, PARTICIPANT2, PARTICIPANT3);
protected static Token t(int v)
{
return DatabaseDescriptor.getPartitioner().getToken(ByteBufferUtil.bytes(v));
}
protected static final Range<Token> RANGE1 = new Range<>(t(1), t(2));
protected static final Range<Token> RANGE2 = new Range<>(t(2), t(3));
protected static final Range<Token> RANGE3 = new Range<>(t(4), t(5));
protected static UUID registerSession(ColumnFamilyStore cfs)
{
UUID sessionId = UUIDGen.getTimeUUID();
ActiveRepairService.instance.registerParentRepairSession(sessionId,
COORDINATOR,
Lists.newArrayList(cfs),
Sets.newHashSet(RANGE1, RANGE2, RANGE3),
true,
System.currentTimeMillis(),
true,
PreviewKind.NONE);
return sessionId;
}
}
| apache-2.0 |
MSchantz/Parse-SDK-Android | Parse/src/main/java/com/parse/ParseRemoveOperation.java | 3725 | /*
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.parse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* An operation that removes every instance of an element from an array field.
*/
/** package */ class ParseRemoveOperation implements ParseFieldOperation {
protected final HashSet<Object> objects = new HashSet<>();
public ParseRemoveOperation(Collection<?> coll) {
objects.addAll(coll);
}
@Override
public JSONObject encode(ParseEncoder objectEncoder) throws JSONException {
JSONObject output = new JSONObject();
output.put("__op", "Remove");
output.put("objects", objectEncoder.encode(new ArrayList<>(objects)));
return output;
}
@Override
public ParseFieldOperation mergeWithPrevious(ParseFieldOperation previous) {
if (previous == null) {
return this;
} else if (previous instanceof ParseDeleteOperation) {
return new ParseSetOperation(objects);
} else if (previous instanceof ParseSetOperation) {
Object value = ((ParseSetOperation) previous).getValue();
if (value instanceof JSONArray || value instanceof List) {
return new ParseSetOperation(this.apply(value, null));
} else {
throw new IllegalArgumentException("You can only add an item to a List or JSONArray.");
}
} else if (previous instanceof ParseRemoveOperation) {
HashSet<Object> result = new HashSet<>(((ParseRemoveOperation) previous).objects);
result.addAll(objects);
return new ParseRemoveOperation(result);
} else {
throw new IllegalArgumentException("Operation is invalid after previous operation.");
}
}
@Override
public Object apply(Object oldValue, String key) {
if (oldValue == null) {
return new ArrayList<>();
} else if (oldValue instanceof JSONArray) {
ArrayList<Object> old = ParseFieldOperations.jsonArrayAsArrayList((JSONArray) oldValue);
@SuppressWarnings("unchecked")
ArrayList<Object> newValue = (ArrayList<Object>) this.apply(old, key);
return new JSONArray(newValue);
} else if (oldValue instanceof List) {
ArrayList<Object> result = new ArrayList<>((List<?>) oldValue);
result.removeAll(objects);
// Remove the removed objects from "objects" -- the items remaining
// should be ones that weren't removed by object equality.
ArrayList<Object> objectsToBeRemoved = new ArrayList<>(objects);
objectsToBeRemoved.removeAll(result);
// Build up set of object IDs for any ParseObjects in the remaining objects-to-be-removed
HashSet<String> objectIds = new HashSet<>();
for (Object obj : objectsToBeRemoved) {
if (obj instanceof ParseObject) {
objectIds.add(((ParseObject) obj).getObjectId());
}
}
// And iterate over "result" to see if any other ParseObjects need to be removed
Iterator<Object> resultIterator = result.iterator();
while (resultIterator.hasNext()) {
Object obj = resultIterator.next();
if (obj instanceof ParseObject && objectIds.contains(((ParseObject) obj).getObjectId())) {
resultIterator.remove();
}
}
return result;
} else {
throw new IllegalArgumentException("Operation is invalid after previous operation.");
}
}
}
| bsd-3-clause |
irudyak/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/binary/GridCacheBinaryTransactionalEntryProcessorDeploymentSelfTest.java | 1284 | /*
* 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.binary;
import org.apache.ignite.cache.CacheAtomicityMode;
/**
* Cache EntryProcessor + Deployment for transactional cache.
*/
public class GridCacheBinaryTransactionalEntryProcessorDeploymentSelfTest extends
GridCacheBinaryAtomicEntryProcessorDeploymentSelfTest {
/** {@inheritDoc} */
@Override protected CacheAtomicityMode atomicityMode() {
return CacheAtomicityMode.TRANSACTIONAL;
}
}
| apache-2.0 |
conder/sakai | message/message-api/api/src/java/org/sakaiproject/message/api/MessageHeader.java | 4259 | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai 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/ECL-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.sakaiproject.message.api;
import java.util.Collection;
import java.util.Stack;
import org.sakaiproject.entity.api.AttachmentContainer;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.user.api.User;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* <p>
* MessageHeader is the base Interface for a Sakai Message headers. Header fields common to all message service message headers are defined here.
* </p>
*/
public interface MessageHeader extends AttachmentContainer
{
/**
* <p>
* MessageAccess enumerates different access modes for the message: channel-wide or grouped.
* </p>
*/
public class MessageAccess
{
private final String m_id;
private MessageAccess(String id)
{
m_id = id;
}
public String toString()
{
return m_id;
}
static public MessageAccess fromString(String access)
{
// if (PUBLIC.m_id.equals(access)) return PUBLIC;
if (CHANNEL.m_id.equals(access)) return CHANNEL;
if (GROUPED.m_id.equals(access)) return GROUPED;
return null;
}
/** public access to the message: pubview */
// public static final MessageAccess PUBLIC = new MessageAccess("public");
/** channel (site) level access to the message */
public static final MessageAccess CHANNEL = new MessageAccess("channel");
/** grouped access; only members of the getGroup() groups (authorization groups) have access */
public static final MessageAccess GROUPED = new MessageAccess("grouped");
}
/**
* Access the unique (within the channel) message id.
*
* @return The unique (within the channel) message id.
*/
String getId();
/**
* Access the date/time the message was sent to the channel.
*
* @return The date/time the message was sent to the channel.
*/
Time getDate();
/**
* Access the message order of the message was sent to the channel.
*
* @return The message order of the message was sent to the channel.
*/
Integer getMessage_order();
/**
* Access the User who sent the message to the channel.
*
* @return The User who sent the message to the channel.
*/
User getFrom();
/**
* Access the draft status of the message.
*
* @return True if the message is a draft, false if not.
*/
boolean getDraft();
/**
* Access the groups defined for this message.
*
* @return A Collection (String) of group refs (authorization group ids) defined for this message; empty if none are defined.
*/
Collection<String> getGroups();
/**
* Access the groups, as Group objects, defined for this message.
*
* @return A Collection (Group) of group objects defined for this message; empty if none are defined.
*/
Collection<Group> getGroupObjects();
/**
* Access the access mode for the message - how we compute who has access to the message.
*
* @return The MessageAccess access mode for the message.
*/
MessageAccess getAccess();
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
Element toXml(Document doc, Stack stack);
}
| apache-2.0 |
nburn42/tensorflow | tensorflow/java/src/main/java/org/tensorflow/op/annotation/Operator.java | 3654 | /* Copyright 2017 The TensorFlow Authors. 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.tensorflow.op.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used by classes to make TensorFlow operations conveniently accessible via {@code
* org.tensorflow.op.Ops}.
*
* <p>An annotation processor (TODO: not yet implemented) builds the {@code Ops} class by
* aggregating all classes annotated as {@code @Operator}s. Each annotated class <b>must</b> have at
* least one public static factory method named {@code create} that accepts a {@link
* org.tensorflow.op.Scope} as its first argument. The processor then adds a convenience method in
* the {@code Ops} class. For example:
*
* <pre>{@code
* @Operator
* public final class MyOp implements Op {
* public static MyOp create(Scope scope, Operand operand) {
* ...
* }
* }
* }</pre>
*
* <p>results in a method in the {@code Ops} class
*
* <pre>{@code
* import org.tensorflow.op.Ops;
* ...
* Ops ops = new Ops(graph);
* ...
* ops.myOp(operand);
* // and has exactly the same effect as calling
* // MyOp.create(ops.getScope(), operand);
* }</pre>
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Operator {
/**
* Specify an optional group within the {@code Ops} class.
*
* <p>By default, an annotation processor will create convenience methods directly in the {@code
* Ops} class. An annotated operator may optionally choose to place the method within a group. For
* example:
*
* <pre>{@code
* @Operator(group="math")
* public final class Add extends PrimitiveOp implements Operand {
* ...
* }
* }</pre>
*
* <p>results in the {@code add} method placed within a {@code math} group within the {@code Ops}
* class.
*
* <pre>{@code
* ops.math().add(...);
* }</pre>
*
* <p>The group name must be a <a
* href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java
* identifier</a>.
*/
String group() default "";
/**
* Name for the wrapper method used in the {@code Ops} class.
*
* <p>By default, a processor derives the method name in the {@code Ops} class from the class name
* of the operator. This attribute allow you to provide a different name instead. For example:
*
* <pre>{@code
* @Operator(name="myOperation")
* public final class MyRealOperation implements Operand {
* public static MyRealOperation create(...)
* }
* }</pre>
*
* <p>results in this method added to the {@code Ops} class
*
* <pre>{@code
* ops.myOperation(...);
* // and is the same as calling
* // MyRealOperation.create(...)
* }</pre>
*
* <p>The name must be a <a
* href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8">valid Java
* identifier</a>.
*/
String name() default "";
}
| apache-2.0 |
marktriggs/nyu-sakai-10.4 | providers/jldap/src/java/edu/amc/sakai/user/LdapConnectionLivenessValidator.java | 1307 | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai 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/ECL-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 edu.amc.sakai.user;
import com.novell.ldap.LDAPConnection;
/**
* Pluggable strategy for verifying {@link LDAPConnection}
* "liveness". Typically injected into a
* {@link PooledLDAPConnectionFactory}.
*
* @author dmccallum@unicon.net
*
*/
public interface LdapConnectionLivenessValidator {
public boolean isConnectionAlive(LDAPConnection connectionToTest);
}
| apache-2.0 |
corochoone/elasticsearch | src/test/java/org/elasticsearch/stresstest/indexing/BulkIndexingStressTest.java | 2807 | /*
* 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.stresstest.indexing;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import java.util.concurrent.ThreadLocalRandom;
/**
*/
public class BulkIndexingStressTest {
public static void main(String[] args) {
final int NUMBER_OF_NODES = 4;
final int NUMBER_OF_INDICES = 600;
final int BATCH = 300;
final Settings nodeSettings = ImmutableSettings.settingsBuilder().put("index.number_of_shards", 2).build();
// ESLogger logger = Loggers.getLogger("org.elasticsearch");
// logger.setLevel("DEBUG");
Node[] nodes = new Node[NUMBER_OF_NODES];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = NodeBuilder.nodeBuilder().settings(nodeSettings).node();
}
Client client = nodes.length == 1 ? nodes[0].client() : nodes[1].client();
while (true) {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (int i = 0; i < BATCH; i++) {
bulkRequest.add(Requests.indexRequest("test" + ThreadLocalRandom.current().nextInt(NUMBER_OF_INDICES)).type("type").source("field", "value"));
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
for (BulkItemResponse item : bulkResponse) {
if (item.isFailed()) {
System.out.println("failed response:" + item.getFailureMessage());
}
}
throw new RuntimeException("Failed responses");
}
;
}
}
}
| apache-2.0 |
davidmrtz/TrackingApp | myMapa/library/src/com/google/maps/android/MathUtil.java | 3305 | /*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.maps.android;
import static java.lang.Math.*;
/**
* Utility functions that are used my both PolyUtil and SphericalUtil.
*/
class MathUtil {
/**
* The earth's radius, in meters.
* Mean radius as defined by IUGG.
*/
static final double EARTH_RADIUS = 6371009;
/**
* Restrict x to the range [low, high].
*/
static double clamp(double x, double low, double high) {
return x < low ? low : (x > high ? high : x);
}
/**
* Wraps the given value into the inclusive-exclusive interval between min and max.
* @param n The value to wrap.
* @param min The minimum.
* @param max The maximum.
*/
static double wrap(double n, double min, double max) {
return (n >= min && n < max) ? n : (mod(n - min, max - min) + min);
}
/**
* Returns the non-negative remainder of x / m.
* @param x The operand.
* @param m The modulus.
*/
static double mod(double x, double m) {
return ((x % m) + m) % m;
}
/**
* Returns mercator Y corresponding to latitude.
* See http://en.wikipedia.org/wiki/Mercator_projection .
*/
static double mercator(double lat) {
return log(tan(lat * 0.5 + PI/4));
}
/**
* Returns latitude from mercator Y.
*/
static double inverseMercator(double y) {
return 2 * atan(exp(y)) - PI / 2;
}
/**
* Returns haversine(angle-in-radians).
* hav(x) == (1 - cos(x)) / 2 == sin(x / 2)^2.
*/
static double hav(double x) {
double sinHalf = sin(x * 0.5);
return sinHalf * sinHalf;
}
/**
* Computes inverse haversine. Has good numerical stability around 0.
* arcHav(x) == acos(1 - 2 * x) == 2 * asin(sqrt(x)).
* The argument must be in [0, 1], and the result is positive.
*/
static double arcHav(double x) {
return 2 * asin(sqrt(x));
}
// Given h==hav(x), returns sin(abs(x)).
static double sinFromHav(double h) {
return 2 * sqrt(h * (1 - h));
}
// Returns hav(asin(x)).
static double havFromSin(double x) {
double x2 = x * x;
return x2 / (1 + sqrt(1 - x2)) * .5;
}
// Returns sin(arcHav(x) + arcHav(y)).
static double sinSumFromHav(double x, double y) {
double a = sqrt(x * (1 - x));
double b = sqrt(y * (1 - y));
return 2 * (a + b - 2 * (a * y + b * x));
}
/**
* Returns hav() of distance from (lat1, lng1) to (lat2, lng2) on the unit sphere.
*/
static double havDistance(double lat1, double lat2, double dLng) {
return hav(lat1 - lat2) + hav(dLng) * cos(lat1) * cos(lat2);
}
}
| apache-2.0 |
cyclingengineer/UpnpHomeAutomationBridge | src/org/openhab/binding/maxcube/internal/exceptions/IncorrectMultilineIndexException.java | 737 | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.maxcube.internal.exceptions;
/**
* Will be thrown when there is an attempt to put a new message line into the message processor,
* but the processor is currently processing an other message type.
*
* @author Christian Rockrohr <christian@rockrohr.de>
*/
public class IncorrectMultilineIndexException extends Exception {
private static final long serialVersionUID = -2261755876987011907L;
}
| epl-1.0 |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/BlockReaderUtil.java | 1761 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import java.io.IOException;
/**
* For sharing between the local and remote block reader implementations.
*/
class BlockReaderUtil {
/* See {@link BlockReader#readAll(byte[], int, int)} */
public static int readAll(BlockReader reader,
byte[] buf, int offset, int len) throws IOException {
int n = 0;
for (;;) {
int nread = reader.read(buf, offset + n, len - n);
if (nread <= 0)
return (n == 0) ? nread : n;
n += nread;
if (n >= len)
return n;
}
}
/* See {@link BlockReader#readFully(byte[], int, int)} */
public static void readFully(BlockReader reader,
byte[] buf, int off, int len) throws IOException {
int toRead = len;
while (toRead > 0) {
int ret = reader.read(buf, off, toRead);
if (ret < 0) {
throw new IOException("Premature EOF from inputStream");
}
toRead -= ret;
off += ret;
}
}
} | apache-2.0 |
dgrif/binnavi | src/main/java/com/google/security/zynamics/binnavi/Gui/MainWindow/ProjectTree/Nodes/Module/CModuleNode.java | 8652 | /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.CMain;
import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase;
import com.google.security.zynamics.binnavi.Gui.MainWindow.Implementations.CModuleFunctions;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractLazyComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractNodeComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CProjectTreeNode;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module.Component.CModuleNodeComponent;
import com.google.security.zynamics.binnavi.disassembly.CProjectContainer;
import com.google.security.zynamics.binnavi.disassembly.INaviAddressSpace;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleContainer;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleListenerAdapter;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.binnavi.disassembly.views.IViewContainer;
import com.google.security.zynamics.zylib.gui.SwingInvoker;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Represents module nodes in the project tree.
*/
public final class CModuleNode extends CProjectTreeNode<INaviModule> {
/**
* Used for serialization.
*/
private static final long serialVersionUID = -5643276356053733957L;
/**
* Icon used for loaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module.png"));
/**
* Icon used for unloaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_GRAY =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_gray.png"));
/**
* Icon used for incomplete modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_BROKEN =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_broken.png"));
/**
* Icon used for not yet converted modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_UNCONVERTED =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_light_gray.png"));
/**
* The module described by the node.
*/
private final INaviModule m_module;
/**
* Context in which views of the represented module are opened.
*/
private final IViewContainer m_contextContainer;
/**
* Updates the node on important changes in the represented module.
*/
private final InternalModuleListener m_listener;
/**
* Constructor for modules inside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param addressSpace The address space the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree,
final DefaultMutableTreeNode parentNode,
final IDatabase database,
final INaviAddressSpace addressSpace,
final INaviModule module,
final CProjectContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, addressSpace, module,
contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
addressSpace,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01972: Database argument can't be null");
Preconditions.checkNotNull(addressSpace, "IE01973: Address space can't be null");
m_module = Preconditions.checkNotNull(module, "IE01974: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Constructor for modules outside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree, final DefaultMutableTreeNode parentNode,
final IDatabase database, final INaviModule module, final CModuleContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, null, module, contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
null,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01970: Database can't be null");
m_module = Preconditions.checkNotNull(module, "IE01971: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Creates the child nodes of the module node. One node is added for the native Call graph of the
* module, another node is added that contains all native Flow graph views of the module.
*/
@Override
protected void createChildren() {}
@Override
public void dispose() {
super.dispose();
m_contextContainer.dispose();
m_module.removeListener(m_listener);
deleteChildren();
}
@Override
public void doubleClicked() {
if (m_module.getConfiguration().getRawModule().isComplete() && !m_module.isLoaded()) {
CModuleFunctions.loadModules(getProjectTree(), new INaviModule[] {m_module});
}
}
@Override
public CModuleNodeComponent getComponent() {
return (CModuleNodeComponent) super.getComponent();
}
@Override
public Icon getIcon() {
if (m_module.getConfiguration().getRawModule().isComplete() && m_module.isInitialized()) {
return m_module.isLoaded() ? ICON_MODULE : ICON_MODULE_GRAY;
} else if (m_module.getConfiguration().getRawModule().isComplete()
&& !m_module.isInitialized()) {
return ICON_MODULE_UNCONVERTED;
} else {
return ICON_MODULE_BROKEN;
}
}
@Override
public String toString() {
return m_module.getConfiguration().getName() + " (" + m_module.getFunctionCount() + "/"
+ m_module.getCustomViewCount() + ")";
}
/**
* Updates the node on important changes in the represented module.
*/
private class InternalModuleListener extends CModuleListenerAdapter {
@Override
public void addedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void changedName(final INaviModule module, final String name) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void deletedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
/**
* When the module is loaded, create the child nodes.
*/
@Override
public void loadedModule(final INaviModule module) {
new SwingInvoker() {
@Override
protected void operation() {
createChildren();
getTreeModel().nodeStructureChanged(CModuleNode.this);
}
}.invokeAndWait();
}
}
}
| apache-2.0 |
idea4bsd/idea4bsd | platform/testFramework/src/com/intellij/mock/MockPsiFile.java | 8673 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.mock;
import com.intellij.lang.FileASTNode;
import com.intellij.lang.Language;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.FileContextUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.LocalTimeCounter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class MockPsiFile extends MockPsiElement implements PsiFile {
private final long myModStamp = LocalTimeCounter.currentTime();
private VirtualFile myVirtualFile = null;
public boolean valid = true;
public String text = "";
private final FileViewProvider myFileViewProvider;
private final PsiManager myPsiManager;
public MockPsiFile(@NotNull PsiManager psiManager) {
super(psiManager.getProject());
myPsiManager = psiManager;
myFileViewProvider = new SingleRootFileViewProvider(getManager(), new LightVirtualFile("noname", getFileType(), ""));
}
public MockPsiFile(@NotNull VirtualFile virtualFile, @NotNull PsiManager psiManager) {
super(psiManager.getProject());
myPsiManager = psiManager;
myVirtualFile = virtualFile;
myFileViewProvider = new SingleRootFileViewProvider(getManager(), virtualFile);
}
@Override
public VirtualFile getVirtualFile() {
return myVirtualFile;
}
@Override
public boolean processChildren(final PsiElementProcessor<PsiFileSystemItem> processor) {
return true;
}
@Override
@NotNull
public String getName() {
return "mock.file";
}
@Override
@Nullable
public ItemPresentation getPresentation() {
return null;
}
@Override
public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Not implemented");
}
@Override
public void checkSetName(String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Not implemented");
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public PsiDirectory getContainingDirectory() {
return null;
}
@Nullable
public PsiDirectory getParentDirectory() {
throw new UnsupportedOperationException("Method getParentDirectory is not yet implemented in " + getClass().getName());
}
@Override
public long getModificationStamp() {
return myModStamp;
}
@Override
@NotNull
public PsiFile getOriginalFile() {
return this;
}
@Override
@NotNull
public FileType getFileType() {
return StdFileTypes.JAVA;
}
@Override
@NotNull
public Language getLanguage() {
return StdFileTypes.JAVA.getLanguage();
}
@Override
@NotNull
public PsiFile[] getPsiRoots() {
return new PsiFile[]{this};
}
@Override
@NotNull
public FileViewProvider getViewProvider() {
return myFileViewProvider;
}
@Override
public PsiManager getManager() {
return myPsiManager;
}
@Override
@NotNull
public PsiElement[] getChildren() {
return PsiElement.EMPTY_ARRAY;
}
@Override
public PsiDirectory getParent() {
return null;
}
@Override
public PsiElement getFirstChild() {
return null;
}
@Override
public PsiElement getLastChild() {
return null;
}
@Override
public void acceptChildren(@NotNull PsiElementVisitor visitor) {
}
@Override
public PsiElement getNextSibling() {
return null;
}
@Override
public PsiElement getPrevSibling() {
return null;
}
@Override
public PsiFile getContainingFile() {
return null;
}
@Override
public TextRange getTextRange() {
return null;
}
@Override
public int getStartOffsetInParent() {
return 0;
}
@Override
public int getTextLength() {
return 0;
}
@Override
public PsiElement findElementAt(int offset) {
return null;
}
@Override
public PsiReference findReferenceAt(int offset) {
return null;
}
@Override
public int getTextOffset() {
return 0;
}
@Override
public String getText() {
return text;
}
@Override
@NotNull
public char[] textToCharArray() {
return ArrayUtil.EMPTY_CHAR_ARRAY;
}
@Override
public boolean textMatches(@NotNull CharSequence text) {
return false;
}
@Override
public boolean textMatches(@NotNull PsiElement element) {
return false;
}
@Override
public boolean textContains(char c) {
return false;
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
}
@Override
public PsiElement copy() {
return null;
}
@Override
public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
return null;
}
@Override
public void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException {
}
@Override
public PsiElement addRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addRangeBefore(@NotNull PsiElement first, @NotNull PsiElement last, PsiElement anchor)
throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addRangeAfter(PsiElement first, PsiElement last, PsiElement anchor)
throws IncorrectOperationException {
return null;
}
@Override
public void delete() throws IncorrectOperationException {
}
@Override
public void checkDelete() throws IncorrectOperationException {
}
@Override
public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
}
@Override
public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException {
return null;
}
@Override
public boolean isValid() {
return valid;
}
@Override
public boolean isWritable() {
return false;
}
@Override
public PsiReference getReference() {
return null;
}
@Override
@NotNull
public PsiReference[] getReferences() {
return PsiReference.EMPTY_ARRAY;
}
@Override
public <T> T getCopyableUserData(@NotNull Key<T> key) {
return null;
}
@Override
public <T> void putCopyableUserData(@NotNull Key<T> key, T value) {
}
@Override
@NotNull
public Project getProject() {
final PsiManager manager = getManager();
if (manager == null) throw new PsiInvalidElementAccessException(this);
return manager.getProject();
}
@Override
public boolean isPhysical() {
return true;
}
@Override
public PsiElement getNavigationElement() {
return this;
}
@Override
public PsiElement getOriginalElement() {
return this;
}
@Override
@NotNull
public GlobalSearchScope getResolveScope() {
return GlobalSearchScope.EMPTY_SCOPE;
}
@Override
@NotNull
public SearchScope getUseScope() {
return GlobalSearchScope.EMPTY_SCOPE;
}
@Override
public FileASTNode getNode() {
return null;
}
@Override
public void subtreeChanged() {
}
@Override
public void navigate(boolean requestFocus) {
}
@Override
public boolean canNavigate() {
return false;
}
@Override
public boolean canNavigateToSource() {
return false;
}
@Override
public PsiElement getContext() {
return FileContextUtil.getFileContext(this);
}
}
| apache-2.0 |
asedunov/intellij-community | xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlMarkupDeclImpl.java | 1100 | /*
* Copyright 2000-2014 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.psi.impl.source.xml;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.xml.XmlElementType;
import com.intellij.psi.xml.XmlMarkupDecl;
/**
* @author Mike
*/
public class XmlMarkupDeclImpl extends XmlElementImpl implements XmlMarkupDecl {
public XmlMarkupDeclImpl() {
super(XmlElementType.XML_MARKUP_DECL);
}
@Override
public PsiMetaData getMetaData(){
return MetaRegistry.getMeta(this);
}
}
| apache-2.0 |
saqsun/libgdx | extensions/gdx-bullet/jni/swig-src/linearmath/com/badlogic/gdx/physics/bullet/linearmath/btConvexHullComputer.java | 5913 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.linearmath;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;
public class btConvexHullComputer extends BulletBase {
private long swigCPtr;
protected btConvexHullComputer(final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexHullComputer, normally you should not need this constructor it's intended for low-level usage. */
public btConvexHullComputer(long cPtr, boolean cMemoryOwn) {
this("btConvexHullComputer", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset(long cPtr, boolean cMemoryOwn) {
if (!destroyed)
destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr(btConvexHullComputer obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize() throws Throwable {
if (!destroyed)
destroy();
super.finalize();
}
@Override protected synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
LinearMathJNI.delete_btConvexHullComputer(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
static public class Edge extends BulletBase {
private long swigCPtr;
protected Edge(final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new Edge, normally you should not need this constructor it's intended for low-level usage. */
public Edge(long cPtr, boolean cMemoryOwn) {
this("Edge", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset(long cPtr, boolean cMemoryOwn) {
if (!destroyed)
destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr(Edge obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize() throws Throwable {
if (!destroyed)
destroy();
super.finalize();
}
@Override protected synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
LinearMathJNI.delete_btConvexHullComputer_Edge(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public int getSourceVertex() {
return LinearMathJNI.btConvexHullComputer_Edge_getSourceVertex(swigCPtr, this);
}
public int getTargetVertex() {
return LinearMathJNI.btConvexHullComputer_Edge_getTargetVertex(swigCPtr, this);
}
public btConvexHullComputer.Edge getNextEdgeOfVertex() {
long cPtr = LinearMathJNI.btConvexHullComputer_Edge_getNextEdgeOfVertex(swigCPtr, this);
return (cPtr == 0) ? null : new btConvexHullComputer.Edge(cPtr, false);
}
public btConvexHullComputer.Edge getNextEdgeOfFace() {
long cPtr = LinearMathJNI.btConvexHullComputer_Edge_getNextEdgeOfFace(swigCPtr, this);
return (cPtr == 0) ? null : new btConvexHullComputer.Edge(cPtr, false);
}
public btConvexHullComputer.Edge getReverseEdge() {
long cPtr = LinearMathJNI.btConvexHullComputer_Edge_getReverseEdge(swigCPtr, this);
return (cPtr == 0) ? null : new btConvexHullComputer.Edge(cPtr, false);
}
public Edge() {
this(LinearMathJNI.new_btConvexHullComputer_Edge(), true);
}
}
public void setVertices(btVector3Array value) {
LinearMathJNI.btConvexHullComputer_vertices_set(swigCPtr, this, btVector3Array.getCPtr(value), value);
}
public btVector3Array getVertices() {
long cPtr = LinearMathJNI.btConvexHullComputer_vertices_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3Array(cPtr, false);
}
public void setEdges(SWIGTYPE_p_btAlignedObjectArrayT_btConvexHullComputer__Edge_t value) {
LinearMathJNI.btConvexHullComputer_edges_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_btConvexHullComputer__Edge_t.getCPtr(value));
}
public SWIGTYPE_p_btAlignedObjectArrayT_btConvexHullComputer__Edge_t getEdges() {
long cPtr = LinearMathJNI.btConvexHullComputer_edges_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_btConvexHullComputer__Edge_t(cPtr, false);
}
public void setFaces(SWIGTYPE_p_btAlignedObjectArrayT_int_t value) {
LinearMathJNI.btConvexHullComputer_faces_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_int_t.getCPtr(value));
}
public SWIGTYPE_p_btAlignedObjectArrayT_int_t getFaces() {
long cPtr = LinearMathJNI.btConvexHullComputer_faces_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_int_t(cPtr, false);
}
public float compute(java.nio.FloatBuffer coords, int stride, int count, float shrink, float shrinkClamp) {
assert coords.isDirect() : "Buffer must be allocated direct.";
{
return LinearMathJNI.btConvexHullComputer_compute__SWIG_0(swigCPtr, this, coords, stride, count, shrink, shrinkClamp);
}
}
public float compute(java.nio.DoubleBuffer coords, int stride, int count, float shrink, float shrinkClamp) {
assert coords.isDirect() : "Buffer must be allocated direct.";
{
return LinearMathJNI.btConvexHullComputer_compute__SWIG_1(swigCPtr, this, coords, stride, count, shrink, shrinkClamp);
}
}
public btConvexHullComputer() {
this(LinearMathJNI.new_btConvexHullComputer(), true);
}
}
| apache-2.0 |
YMartsynkevych/camel | components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/operations/CreateOperation.java | 2550 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.zookeeper.operations;
import java.util.List;
import static java.lang.String.format;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
/**
* <code>CreateOperation</code> is a basic Zookeeper operation used to create
* and set the data contained in a given node
*/
public class CreateOperation extends ZooKeeperOperation<String> {
private static final List<ACL> DEFAULT_PERMISSIONS = Ids.OPEN_ACL_UNSAFE;
private static final CreateMode DEFAULT_MODE = CreateMode.EPHEMERAL;
private byte[] data;
private List<ACL> permissions = DEFAULT_PERMISSIONS;
private CreateMode createMode = DEFAULT_MODE;
public CreateOperation(ZooKeeper connection, String node) {
super(connection, node);
}
@Override
public OperationResult<String> getResult() {
try {
String created = connection.create(node, data, permissions, createMode);
if (LOG.isDebugEnabled()) {
LOG.debug(format("Created node '%s' using mode '%s'", created, createMode));
}
// for consistency with other operations return an empty stats set.
return new OperationResult<String>(created, new Stat());
} catch (Exception e) {
return new OperationResult<String>(e);
}
}
public void setData(byte[] data) {
this.data = data;
}
public void setPermissions(List<ACL> permissions) {
this.permissions = permissions;
}
public void setCreateMode(CreateMode createMode) {
this.createMode = createMode;
}
}
| apache-2.0 |
clumsy/intellij-community | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/XPath2Language.java | 1943 | /*
* Copyright 2005 Sascha Weinreuter
*
* 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.intellij.lang.xpath;
import com.intellij.lang.Commenter;
import com.intellij.lang.Language;
import com.intellij.openapi.fileTypes.SingleLazyInstanceSyntaxHighlighterFactory;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import org.jetbrains.annotations.NotNull;
public final class XPath2Language extends Language {
public static final String ID = "XPath2";
XPath2Language() {
super(Language.findLanguageByID(XPathLanguage.ID), ID);
}
@Override
public XPathFileType getAssociatedFileType() {
return XPathFileType.XPATH2;
}
public static class XPathSyntaxHighlighterFactory extends SingleLazyInstanceSyntaxHighlighterFactory {
@NotNull
protected SyntaxHighlighter createHighlighter() {
return new XPathHighlighter(true);
}
}
public static class XPath2Commenter implements Commenter {
@Override
public String getLineCommentPrefix() {
return null;
}
@Override
public String getBlockCommentPrefix() {
return "(:";
}
@Override
public String getBlockCommentSuffix() {
return ":)";
}
@Override
public String getCommentedBlockCommentPrefix() {
return getBlockCommentPrefix();
}
@Override
public String getCommentedBlockCommentSuffix() {
return getBlockCommentSuffix();
}
}
}
| apache-2.0 |
shakamunyi/hadoop-20 | src/test/org/apache/hadoop/mapred/ReliabilityTest.java | 18910 | /**
* 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.mapred;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* This class tests reliability of the framework in the face of failures of
* both tasks and tasktrackers. Steps:
* 1) Get the cluster status
* 2) Get the number of slots in the cluster
* 3) Spawn a sleepjob that occupies the entire cluster (with two waves of maps)
* 4) Get the list of running attempts for the job
* 5) Fail a few of them
* 6) Now fail a few trackers (ssh)
* 7) Job should run to completion
* 8) The above is repeated for the Sort suite of job (randomwriter, sort,
* validator). All jobs must complete, and finally, the sort validation
* should succeed.
* To run the test:
* ./bin/hadoop --config <config> jar
* build/hadoop-<version>-test.jar MRReliabilityTest -libjars
* build/hadoop-<version>-examples.jar [-scratchdir <dir>]"
*
* The scratchdir is optional and by default the current directory on the client
* will be used as the scratch space. Note that password-less SSH must be set up
* between the client machine from where the test is submitted, and the cluster
* nodes where the test runs.
*
* The test should be run on a <b>free</b> cluster where there is no other parallel
* job submission going on. Submission of other jobs while the test runs can cause
* the tests/jobs submitted to fail.
*/
public class ReliabilityTest extends Configured implements Tool {
private String dir;
private static final Log LOG = LogFactory.getLog(ReliabilityTest.class);
private void displayUsage() {
LOG.info("This must be run in only the distributed mode " +
"(LocalJobRunner not supported).\n\tUsage: MRReliabilityTest " +
"-libjars <path to hadoop-examples.jar> [-scratchdir <dir>]" +
"\n[-scratchdir] points to a scratch space on this host where temp" +
" files for this test will be created. Defaults to current working" +
" dir. \nPasswordless SSH must be set up between this host and the" +
" nodes which the test is going to use.\n"+
"The test should be run on a free cluster with no parallel job submission" +
" going on, as the test requires to restart TaskTrackers and kill tasks" +
" any job submission while the tests are running can cause jobs/tests to fail");
System.exit(-1);
}
public int run(String[] args) throws Exception {
Configuration conf = getConf();
if ("local".equals(conf.get("mapred.job.tracker", "local"))) {
displayUsage();
}
String[] otherArgs =
new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length == 2) {
if (otherArgs[0].equals("-scratchdir")) {
dir = otherArgs[1];
} else {
displayUsage();
}
}
else if (otherArgs.length == 0) {
dir = System.getProperty("user.dir");
} else {
displayUsage();
}
//to protect against the case of jobs failing even when multiple attempts
//fail, set some high values for the max attempts
conf.setInt("mapred.map.max.attempts", 10);
conf.setInt("mapred.reduce.max.attempts", 10);
runSleepJobTest(new JobClient(new JobConf(conf)), conf);
runSortJobTests(new JobClient(new JobConf(conf)), conf);
return 0;
}
private void runSleepJobTest(final JobClient jc, final Configuration conf)
throws Exception {
ClusterStatus c = jc.getClusterStatus();
int maxMaps = c.getMaxMapTasks() * 2;
int maxReduces = maxMaps;
int mapSleepTime = (int)c.getTTExpiryInterval();
int reduceSleepTime = mapSleepTime;
String[] sleepJobArgs = new String[] {
"-m", Integer.toString(maxMaps),
"-r", Integer.toString(maxReduces),
"-mt", Integer.toString(mapSleepTime),
"-rt", Integer.toString(reduceSleepTime)};
runTest(jc, conf, "org.apache.hadoop.examples.SleepJob", sleepJobArgs,
new KillTaskThread(jc, 2, 0.2f, false, 2),
new KillTrackerThread(jc, 2, 0.4f, false, 1));
LOG.info("SleepJob done");
}
private void runSortJobTests(final JobClient jc, final Configuration conf)
throws Exception {
String inputPath = "my_reliability_test_input";
String outputPath = "my_reliability_test_output";
FileSystem fs = jc.getFs();
fs.delete(new Path(inputPath), true);
fs.delete(new Path(outputPath), true);
runRandomWriterTest(jc, conf, inputPath);
runSortTest(jc, conf, inputPath, outputPath);
runSortValidatorTest(jc, conf, inputPath, outputPath);
}
private void runRandomWriterTest(final JobClient jc,
final Configuration conf, final String inputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.examples.RandomWriter",
new String[]{inputPath},
null, new KillTrackerThread(jc, 0, 0.4f, false, 1));
LOG.info("RandomWriter job done");
}
private void runSortTest(final JobClient jc, final Configuration conf,
final String inputPath, final String outputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.examples.Sort",
new String[]{inputPath, outputPath},
new KillTaskThread(jc, 2, 0.2f, false, 2),
new KillTrackerThread(jc, 2, 0.8f, false, 1));
LOG.info("Sort job done");
}
private void runSortValidatorTest(final JobClient jc,
final Configuration conf, final String inputPath, final String outputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.mapred.SortValidator", new String[] {
"-sortInput", inputPath, "-sortOutput", outputPath},
new KillTaskThread(jc, 2, 0.2f, false, 1),
new KillTrackerThread(jc, 2, 0.8f, false, 1));
LOG.info("SortValidator job done");
}
private String normalizeCommandPath(String command) {
final String hadoopHome;
if ((hadoopHome = System.getenv("HADOOP_HOME")) != null) {
command = hadoopHome + "/" + command;
}
return command;
}
private void checkJobExitStatus(int status, String jobName) {
if (status != 0) {
LOG.info(jobName + " job failed with status: " + status);
System.exit(status);
} else {
LOG.info(jobName + " done.");
}
}
//Starts the job in a thread. It also starts the taskKill/tasktrackerKill
//threads.
private void runTest(final JobClient jc, final Configuration conf,
final String jobClass, final String[] args, KillTaskThread killTaskThread,
KillTrackerThread killTrackerThread) throws Exception {
Thread t = new Thread("Job Test") {
public void run() {
try {
Class<?> jobClassObj = conf.getClassByName(jobClass);
int status = ToolRunner.run(conf, (Tool)(jobClassObj.newInstance()),
args);
checkJobExitStatus(status, jobClass);
} catch (Exception e) {
LOG.fatal("JOB " + jobClass + " failed to run");
System.exit(-1);
}
}
};
t.setDaemon(true);
t.start();
JobStatus[] jobs;
//get the job ID. This is the job that we just submitted
while ((jobs = jc.jobsToComplete()).length == 0) {
LOG.info("Waiting for the job " + jobClass +" to start");
Thread.sleep(1000);
}
JobID jobId = jobs[jobs.length - 1].getJobID();
RunningJob rJob = jc.getJob(jobId);
if(rJob.isComplete()) {
LOG.error("The last job returned by the querying JobTracker is complete :" +
rJob.getJobID() + " .Exiting the test");
System.exit(-1);
}
while (rJob.getJobState() == JobStatus.PREP) {
LOG.info("JobID : " + jobId + " not started RUNNING yet");
Thread.sleep(1000);
rJob = jc.getJob(jobId);
}
if (killTaskThread != null) {
killTaskThread.setRunningJob(rJob);
killTaskThread.start();
killTaskThread.join();
LOG.info("DONE WITH THE TASK KILL/FAIL TESTS");
}
if (killTrackerThread != null) {
killTrackerThread.setRunningJob(rJob);
killTrackerThread.start();
killTrackerThread.join();
LOG.info("DONE WITH THE TESTS TO DO WITH LOST TASKTRACKERS");
}
t.join();
}
private class KillTrackerThread extends Thread {
private volatile boolean killed = false;
private JobClient jc;
private RunningJob rJob;
final private int thresholdMultiplier;
private float threshold = 0.2f;
private boolean onlyMapsProgress;
private int numIterations;
final private String slavesFile = dir + "/_reliability_test_slaves_file_";
final String shellCommand = normalizeCommandPath("bin/slaves.sh");
final private String STOP_COMMAND = "ps uwwx | grep java | grep " +
"org.apache.hadoop.mapred.TaskTracker"+ " |" +
" grep -v grep | tr -s ' ' | cut -d ' ' -f2 | xargs kill -s STOP";
final private String RESUME_COMMAND = "ps uwwx | grep java | grep " +
"org.apache.hadoop.mapred.TaskTracker"+ " |" +
" grep -v grep | tr -s ' ' | cut -d ' ' -f2 | xargs kill -s CONT";
//Only one instance must be active at any point
public KillTrackerThread(JobClient jc, int threshaldMultiplier,
float threshold, boolean onlyMapsProgress, int numIterations) {
this.jc = jc;
this.thresholdMultiplier = threshaldMultiplier;
this.threshold = threshold;
this.onlyMapsProgress = onlyMapsProgress;
this.numIterations = numIterations;
setDaemon(true);
}
public void setRunningJob(RunningJob rJob) {
this.rJob = rJob;
}
public void kill() {
killed = true;
}
public void run() {
stopStartTrackers(true);
if (!onlyMapsProgress) {
stopStartTrackers(false);
}
}
private void stopStartTrackers(boolean considerMaps) {
if (considerMaps) {
LOG.info("Will STOP/RESUME tasktrackers based on Maps'" +
" progress");
} else {
LOG.info("Will STOP/RESUME tasktrackers based on " +
"Reduces' progress");
}
LOG.info("Initial progress threshold: " + threshold +
". Threshold Multiplier: " + thresholdMultiplier +
". Number of iterations: " + numIterations);
float thresholdVal = threshold;
int numIterationsDone = 0;
while (!killed) {
try {
float progress;
if (jc.getJob(rJob.getID()).isComplete() ||
numIterationsDone == numIterations) {
break;
}
if (considerMaps) {
progress = jc.getJob(rJob.getID()).mapProgress();
} else {
progress = jc.getJob(rJob.getID()).reduceProgress();
}
if (progress >= thresholdVal) {
numIterationsDone++;
ClusterStatus c;
stopTaskTrackers((c = jc.getClusterStatus(true)));
Thread.sleep((int)Math.ceil(1.5 * c.getTTExpiryInterval()));
startTaskTrackers();
thresholdVal = thresholdVal * thresholdMultiplier;
}
Thread.sleep(5000);
} catch (InterruptedException ie) {
killed = true;
return;
} catch (Exception e) {
LOG.fatal(StringUtils.stringifyException(e));
}
}
}
private void stopTaskTrackers(ClusterStatus c) throws Exception {
Collection <String> trackerNames = c.getActiveTrackerNames();
ArrayList<String> trackerNamesList = new ArrayList<String>(trackerNames);
Collections.shuffle(trackerNamesList);
int count = 0;
FileOutputStream fos = new FileOutputStream(new File(slavesFile));
LOG.info(new Date() + " Stopping a few trackers");
for (String tracker : trackerNamesList) {
String host = convertTrackerNameToHostName(tracker);
LOG.info(new Date() + " Marking tracker on host: " + host);
fos.write((host + "\n").getBytes());
if (count++ >= trackerNamesList.size()/2) {
break;
}
}
fos.close();
runOperationOnTT("suspend");
}
private void startTaskTrackers() throws Exception {
LOG.info(new Date() + " Resuming the stopped trackers");
runOperationOnTT("resume");
new File(slavesFile).delete();
}
private void runOperationOnTT(String operation) throws IOException {
Map<String,String> hMap = new HashMap<String,String>();
hMap.put("HADOOP_SLAVES", slavesFile);
StringTokenizer strToken;
if (operation.equals("suspend")) {
strToken = new StringTokenizer(STOP_COMMAND, " ");
} else {
strToken = new StringTokenizer(RESUME_COMMAND, " ");
}
String commandArgs[] = new String[strToken.countTokens() + 1];
int i = 0;
commandArgs[i++] = shellCommand;
while (strToken.hasMoreTokens()) {
commandArgs[i++] = strToken.nextToken();
}
String output = Shell.execCommand(hMap, commandArgs);
if (output != null && !output.equals("")) {
LOG.info(output);
}
}
private String convertTrackerNameToHostName(String trackerName) {
// Convert the trackerName to it's host name
int indexOfColon = trackerName.indexOf(":");
String trackerHostName = (indexOfColon == -1) ?
trackerName :
trackerName.substring(0, indexOfColon);
return trackerHostName.substring("tracker_".length());
}
}
private class KillTaskThread extends Thread {
private volatile boolean killed = false;
private RunningJob rJob;
private JobClient jc;
final private int thresholdMultiplier;
private float threshold = 0.2f;
private boolean onlyMapsProgress;
private int numIterations;
public KillTaskThread(JobClient jc, int thresholdMultiplier,
float threshold, boolean onlyMapsProgress, int numIterations) {
this.jc = jc;
this.thresholdMultiplier = thresholdMultiplier;
this.threshold = threshold;
this.onlyMapsProgress = onlyMapsProgress;
this.numIterations = numIterations;
setDaemon(true);
}
public void setRunningJob(RunningJob rJob) {
this.rJob = rJob;
}
public void kill() {
killed = true;
}
public void run() {
killBasedOnProgress(true);
if (!onlyMapsProgress) {
killBasedOnProgress(false);
}
}
private void killBasedOnProgress(boolean considerMaps) {
boolean fail = false;
if (considerMaps) {
LOG.info("Will kill tasks based on Maps' progress");
} else {
LOG.info("Will kill tasks based on Reduces' progress");
}
LOG.info("Initial progress threshold: " + threshold +
". Threshold Multiplier: " + thresholdMultiplier +
". Number of iterations: " + numIterations);
float thresholdVal = threshold;
int numIterationsDone = 0;
while (!killed) {
try {
float progress;
if (jc.getJob(rJob.getID()).isComplete() ||
numIterationsDone == numIterations) {
break;
}
if (considerMaps) {
progress = jc.getJob(rJob.getID()).mapProgress();
} else {
progress = jc.getJob(rJob.getID()).reduceProgress();
}
if (progress >= thresholdVal) {
numIterationsDone++;
if (numIterationsDone > 0 && numIterationsDone % 2 == 0) {
fail = true; //fail tasks instead of kill
}
ClusterStatus c = jc.getClusterStatus();
LOG.info(new Date() + " Killing a few tasks");
Collection<TaskAttemptID> runningTasks =
new ArrayList<TaskAttemptID>();
TaskReport mapReports[] = jc.getMapTaskReports(rJob.getID());
for (TaskReport mapReport : mapReports) {
if (mapReport.getCurrentStatus() == TIPStatus.RUNNING) {
runningTasks.addAll(mapReport.getRunningTaskAttempts());
}
}
if (runningTasks.size() > c.getTaskTrackers()/2) {
int count = 0;
for (TaskAttemptID t : runningTasks) {
LOG.info(new Date() + " Killed task : " + t);
rJob.killTask(t, fail);
if (count++ > runningTasks.size()/2) { //kill 50%
break;
}
}
}
runningTasks.clear();
TaskReport reduceReports[] = jc.getReduceTaskReports(rJob.getID());
for (TaskReport reduceReport : reduceReports) {
if (reduceReport.getCurrentStatus() == TIPStatus.RUNNING) {
runningTasks.addAll(reduceReport.getRunningTaskAttempts());
}
}
if (runningTasks.size() > c.getTaskTrackers()/2) {
int count = 0;
for (TaskAttemptID t : runningTasks) {
LOG.info(new Date() + " Killed task : " + t);
rJob.killTask(t, fail);
if (count++ > runningTasks.size()/2) { //kill 50%
break;
}
}
}
thresholdVal = thresholdVal * thresholdMultiplier;
}
Thread.sleep(5000);
} catch (InterruptedException ie) {
killed = true;
} catch (Exception e) {
LOG.fatal(StringUtils.stringifyException(e));
}
}
}
}
public static void main(String args[]) throws Exception {
int res = ToolRunner.run(new Configuration(), new ReliabilityTest(), args);
System.exit(res);
}
} | apache-2.0 |
carollynn2253/butterknife | butterknife/src/main/java/butterknife/OnItemSelected.java | 2447 | package butterknife;
import android.view.View;
import butterknife.internal.ListenerClass;
import butterknife.internal.ListenerMethod;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static android.widget.AdapterView.OnItemSelectedListener;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
/**
* Bind a method to an {@link OnItemSelectedListener OnItemSelectedListener} on the view for each
* ID specified.
* <pre><code>
* {@literal @}OnItemSelected(R.id.example_list) void onItemSelected(int position) {
* Toast.makeText(this, "Selected position " + position + "!", Toast.LENGTH_SHORT).show();
* }
* </code></pre>
* Any number of parameters from
* {@link OnItemSelectedListener#onItemSelected(android.widget.AdapterView, android.view.View, int,
* long) onItemSelected} may be used on the method.
* <p>
* To bind to methods other than {@code onItemSelected}, specify a different {@code callback}.
* <pre><code>
* {@literal @}OnItemSelected(value = R.id.example_list, callback = NOTHING_SELECTED)
* void onNothingSelected() {
* Toast.makeText(this, "Nothing selected!", Toast.LENGTH_SHORT).show();
* }
* </code></pre>
*
* @see OnItemSelectedListener
*/
@Target(METHOD)
@Retention(CLASS)
@ListenerClass(
targetType = "android.widget.AdapterView<?>",
setter = "setOnItemSelectedListener",
type = "android.widget.AdapterView.OnItemSelectedListener",
callbacks = OnItemSelected.Callback.class
)
public @interface OnItemSelected {
/** View IDs to which the method will be bound. */
int[] value() default { View.NO_ID };
/** Listener callback to which the method will be bound. */
Callback callback() default Callback.ITEM_SELECTED;
/** {@link OnItemSelectedListener} callback methods. */
enum Callback {
/**
* {@link OnItemSelectedListener#onItemSelected(android.widget.AdapterView, android.view.View,
* int, long)}
*/
@ListenerMethod(
name = "onItemSelected",
parameters = {
"android.widget.AdapterView<?>",
"android.view.View",
"int",
"long"
}
)
ITEM_SELECTED,
/** {@link OnItemSelectedListener#onNothingSelected(android.widget.AdapterView)} */
@ListenerMethod(
name = "onNothingSelected",
parameters = "android.widget.AdapterView<?>"
)
NOTHING_SELECTED
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/test/java/awt/im/4959409/bug4959409.java | 2168 | /*
* Copyright (c) 2007, 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.
*/
/**
*
* @bug 4959409
* @author Naoto Sato
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class bug4959409 extends javax.swing.JApplet {
public void init() {
new TestFrame();
}
}
class TestFrame extends JFrame implements KeyListener {
JTextField text;
JLabel label;
TestFrame () {
text = new JTextField();
text.addKeyListener(this);
label = new JLabel(" ");
Container c = getContentPane();
BorderLayout borderLayout1 = new BorderLayout();
c.setLayout(borderLayout1);
c.add(text, BorderLayout.CENTER);
c.add(label, BorderLayout.SOUTH);
setSize(300, 200);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
int mods = e.getModifiers();
if (code == '1' && mods == KeyEvent.SHIFT_MASK) {
label.setText("KEYPRESS received for Shift+1");
} else {
label.setText(" ");
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
| mit |
ElieSauveterre/cordova-plugin-local-notifications | src/android/ClickActivity.java | 2346 | /*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
package de.appplant.cordova.plugin.localnotification;
import de.appplant.cordova.plugin.notification.Builder;
import de.appplant.cordova.plugin.notification.Notification;
import de.appplant.cordova.plugin.notification.TriggerReceiver;
/**
* The receiver activity is triggered when a notification is clicked by a user.
* The activity calls the background callback and brings the launch intent
* up to foreground.
*/
public class ClickActivity extends de.appplant.cordova.plugin.notification.ClickActivity {
/**
* Called when local notification was clicked by the user.
*
* @param notification
* Wrapper around the local notification
*/
@Override
public void onClick(Notification notification) {
LocalNotification.fireEvent("click", notification);
if (!notification.getOptions().isOngoing()) {
String event = notification.isRepeating() ? "clear" : "cancel";
LocalNotification.fireEvent(event, notification);
}
super.onClick(notification);
}
/**
* Build notification specified by options.
*
* @param builder
* Notification builder
*/
@Override
public Notification buildNotification (Builder builder) {
return builder
.setTriggerReceiver(TriggerReceiver.class)
.build();
}
}
| apache-2.0 |
liveqmock/platform-tools-idea | java/java-tests/testData/psi/formatter/java/IfElse.java | 1720 | public class Foo {
public void foo(boolean a, int x,
int y, int z) {
label1:
do {
try {
if (x > 0) {
int someVariable = a ?
x :
y;
}
else if (x < 0) {
int someVariable = (y +
z
);
someVariable = x =
x +
y;
}
else {
label2:
for (int i = 0;
i < 5;
i++)
doSomething(i);
}
switch (a) {
case 0:
doCase0();
break;
default:
doDefault();
}
}
catch (Exception e) {
processException(e.getMessage(),
x + y, z, a);
}
finally {
processFinally();
}
}
while (true);
if (2 < 3) return;
if (3 < 4)
return;
do x++ while (x < 10000);
while (x < 50000) x++;
for (int i = 0; i < 5; i++) System.out.println(i);
}
private class InnerClass implements I1,
I2 {
public void bar() throws E1,
E2 {
}
}
} | apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/refactoring/moveMembers/enumConstant/before/A.java | 37 | public enum A {
;
A(String s){}
} | apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/refactoring/inlineToAnonymousClass/NoInlineMethodUsage.java | 173 | class A {
public void f() {
Inner i = new Inner();
i.doStuff();
}
private class <caret>Inner {
public void doStuff() {
}
}
} | apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/codeInsight/completion/smartType/ExceptionTwice-out.java | 139 | class MyException extends RuntimeException{}
class MyClass {
public void foo() throws MyException {
throw new MyException();<caret>
}
} | apache-2.0 |
jodson/TextSecure | src/ws/com/google/android/mms/pdu/ReadRecInd.java | 4014 | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
public class ReadRecInd extends GenericPdu {
/**
* Constructor, used when composing a M-ReadRec.ind pdu.
*
* @param from the from value
* @param messageId the message ID value
* @param mmsVersion current viersion of mms
* @param readStatus the read status value
* @param to the to value
* @throws InvalidHeaderValueException if parameters are invalid.
* NullPointerException if messageId or to is null.
*/
public ReadRecInd(EncodedStringValue from,
byte[] messageId,
int mmsVersion,
int readStatus,
EncodedStringValue[] to) throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_READ_REC_IND);
setFrom(from);
setMessageId(messageId);
setMmsVersion(mmsVersion);
setTo(to);
setReadStatus(readStatus);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
ReadRecInd(PduHeaders headers) {
super(headers);
}
/**
* Get Date value.
*
* @return the value
*/
public long getDate() {
return mPduHeaders.getLongInteger(PduHeaders.DATE);
}
/**
* Set Date value.
*
* @param value the value
*/
public void setDate(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.DATE);
}
/**
* Get Message-ID value.
*
* @return the value
*/
public byte[] getMessageId() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID);
}
/**
* Set Message-ID value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setMessageId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID);
}
/**
* Get To value.
*
* @return the value
*/
public EncodedStringValue[] getTo() {
return mPduHeaders.getEncodedStringValues(PduHeaders.TO);
}
/**
* Set To value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTo(EncodedStringValue[] value) {
mPduHeaders.setEncodedStringValues(value, PduHeaders.TO);
}
/**
* Get X-MMS-Read-status value.
*
* @return the value
*/
public int getReadStatus() {
return mPduHeaders.getOctet(PduHeaders.READ_STATUS);
}
/**
* Set X-MMS-Read-status value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setReadStatus(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.READ_STATUS);
}
/*
* Optional, not supported header fields:
*
* public byte[] getApplicId() {return null;}
* public void setApplicId(byte[] value) {}
*
* public byte[] getAuxApplicId() {return null;}
* public void getAuxApplicId(byte[] value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*/
}
| gpl-3.0 |
mohanaraosv/camel | camel-core/src/test/java/org/apache/camel/processor/RedeliveryOnExceptionBlockedDelayTest.java | 3369 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @version
*/
public class RedeliveryOnExceptionBlockedDelayTest extends ContextTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(RedeliveryOnExceptionBlockedDelayTest.class);
private static volatile int attempt;
public void testRedelivery() throws Exception {
MockEndpoint before = getMockEndpoint("mock:result");
before.expectedBodiesReceived("Hello World", "Hello Camel");
// we use blocked redelivery delay so the messages arrive in the same order
MockEndpoint result = getMockEndpoint("mock:result");
result.expectedBodiesReceived("Hello World", "Hello Camel");
template.sendBody("seda:start", "World");
template.sendBody("seda:start", "Camel");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// will by default block
onException(IllegalArgumentException.class)
.maximumRedeliveries(5).redeliveryDelay(2000);
from("seda:start")
.to("log:before")
.to("mock:before")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
LOG.info("Processing at attempt " + attempt + " " + exchange);
String body = exchange.getIn().getBody(String.class);
if (body.contains("World")) {
if (++attempt <= 2) {
LOG.info("Processing failed will thrown an exception");
throw new IllegalArgumentException("Damn");
}
}
exchange.getIn().setBody("Hello " + body);
LOG.info("Processing at attempt " + attempt + " complete " + exchange);
}
})
.to("log:after")
.to("mock:result");
}
};
}
}
| apache-2.0 |
coderczp/camel | camel-core/src/test/java/org/apache/camel/processor/RemoveHeadersTest.java | 3108 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
public class RemoveHeadersTest extends ContextTestSupport {
public void testRemoveHeadersWildcard() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:end");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("duck", "Donald");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("dudeCool", "cool");
headers.put("dudeWicket", "wicket");
headers.put("duck", "Donald");
headers.put("foo", "bar");
template.sendBodyAndHeaders("direct:start", "Hello World", headers);
assertMockEndpointsSatisfied();
// breadcrumb is a header added as well so we expect 2
assertEquals(2, mock.getReceivedExchanges().get(0).getIn().getHeaders().size());
}
public void testRemoveHeadersRegEx() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:end");
mock.expectedBodiesReceived("Hello World");
mock.expectedHeaderReceived("duck", "Donald");
mock.expectedHeaderReceived("BeerHeineken", "Good");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("dudeCool", "cool");
headers.put("dudeWicket", "wicket");
headers.put("duck", "Donald");
headers.put("BeerCarlsberg", "Great");
headers.put("BeerTuborg", "Also Great");
headers.put("BeerHeineken", "Good");
template.sendBodyAndHeaders("direct:start", "Hello World", headers);
assertMockEndpointsSatisfied();
// breadcrumb is a header added as well so we expect 3
assertEquals(3, mock.getReceivedExchanges().get(0).getIn().getHeaders().size());
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start")
.removeHeaders("dude*")
.removeHeaders("Beer(Carlsberg|Tuborg)")
.removeHeaders("foo")
.to("mock:end");
}
};
}
} | apache-2.0 |
CandleCandle/camel | camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateControllerTest.java | 4309 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor.aggregator;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.processor.aggregate.AggregateController;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.apache.camel.processor.aggregate.DefaultAggregateController;
import org.junit.Test;
/**
*
*/
public class AggregateControllerTest extends ContextTestSupport {
private AggregateController controller;
public AggregateController getAggregateController() {
if (controller == null) {
controller = new DefaultAggregateController();
}
return controller;
}
@Test
public void testForceCompletionOfAll() throws Exception {
getMockEndpoint("mock:aggregated").expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "test1", "id", "1");
template.sendBodyAndHeader("direct:start", "test2", "id", "2");
template.sendBodyAndHeader("direct:start", "test3", "id", "1");
template.sendBodyAndHeader("direct:start", "test4", "id", "2");
assertMockEndpointsSatisfied();
getMockEndpoint("mock:aggregated").expectedMessageCount(2);
getMockEndpoint("mock:aggregated").expectedBodiesReceivedInAnyOrder("test1test3", "test2test4");
getMockEndpoint("mock:aggregated").expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, "force");
int groups = getAggregateController().forceCompletionOfAllGroups();
assertEquals(2, groups);
assertMockEndpointsSatisfied();
}
@Test
public void testForceCompletionOfGroup() throws Exception {
getMockEndpoint("mock:aggregated").expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "test1", "id", "1");
template.sendBodyAndHeader("direct:start", "test2", "id", "2");
template.sendBodyAndHeader("direct:start", "test3", "id", "1");
template.sendBodyAndHeader("direct:start", "test4", "id", "2");
assertMockEndpointsSatisfied();
getMockEndpoint("mock:aggregated").expectedMessageCount(1);
getMockEndpoint("mock:aggregated").expectedBodiesReceivedInAnyOrder("test1test3");
getMockEndpoint("mock:aggregated").expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, "force");
int groups = getAggregateController().forceCompletionOfGroup("1");
assertEquals(1, groups);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.aggregate(header("id"), new MyAggregationStrategy()).aggregateController(getAggregateController())
.completionSize(10)
.to("mock:aggregated");
}
};
}
public static class MyAggregationStrategy implements AggregationStrategy {
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
String body1 = oldExchange.getIn().getBody(String.class);
String body2 = newExchange.getIn().getBody(String.class);
oldExchange.getIn().setBody(body1 + body2);
return oldExchange;
}
}
} | apache-2.0 |
YMartsynkevych/camel | components/camel-univocity-parsers/src/test/java/org/apache/camel/dataformat/univocity/UniVocityCsvDataFormatTest.java | 8709 | /**
* 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.dataformat.univocity;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* This class tests the options of {@link org.apache.camel.dataformat.univocity.UniVocityCsvDataFormat}.
*/
public final class UniVocityCsvDataFormatTest {
@Test
public void shouldConfigureNullValue() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setNullValue("N/A");
assertEquals("N/A", dataFormat.getNullValue());
assertEquals("N/A", dataFormat.createAndConfigureWriterSettings().getNullValue());
assertEquals("N/A", dataFormat.createAndConfigureParserSettings().getNullValue());
}
@Test
public void shouldConfigureSkipEmptyLines() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setSkipEmptyLines(true);
assertTrue(dataFormat.getSkipEmptyLines());
assertTrue(dataFormat.createAndConfigureWriterSettings().getSkipEmptyLines());
assertTrue(dataFormat.createAndConfigureParserSettings().getSkipEmptyLines());
}
@Test
public void shouldConfigureIgnoreTrailingWhitespaces() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setIgnoreTrailingWhitespaces(true);
assertTrue(dataFormat.getIgnoreTrailingWhitespaces());
assertTrue(dataFormat.createAndConfigureWriterSettings().getIgnoreTrailingWhitespaces());
assertTrue(dataFormat.createAndConfigureParserSettings().getIgnoreTrailingWhitespaces());
}
@Test
public void shouldConfigureIgnoreLeadingWhitespaces() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setIgnoreLeadingWhitespaces(true);
assertTrue(dataFormat.getIgnoreLeadingWhitespaces());
assertTrue(dataFormat.createAndConfigureWriterSettings().getIgnoreLeadingWhitespaces());
assertTrue(dataFormat.createAndConfigureParserSettings().getIgnoreLeadingWhitespaces());
}
@Test
public void shouldConfigureHeadersDisabled() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setHeadersDisabled(true);
assertTrue(dataFormat.isHeadersDisabled());
assertNull(dataFormat.createAndConfigureWriterSettings().getHeaders());
assertNull(dataFormat.createAndConfigureParserSettings().getHeaders());
}
@Test
public void shouldConfigureHeaders() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setHeaders(new String[]{"A", "B", "C"});
assertArrayEquals(new String[]{"A", "B", "C"}, dataFormat.getHeaders());
assertArrayEquals(new String[]{"A", "B", "C"}, dataFormat.createAndConfigureWriterSettings().getHeaders());
assertArrayEquals(new String[]{"A", "B", "C"}, dataFormat.createAndConfigureParserSettings().getHeaders());
}
@Test
public void shouldConfigureHeaderExtractionEnabled() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setHeaderExtractionEnabled(true);
assertTrue(dataFormat.getHeaderExtractionEnabled());
assertTrue(dataFormat.createAndConfigureParserSettings().isHeaderExtractionEnabled());
}
@Test
public void shouldConfigureNumberOfRecordsToRead() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setNumberOfRecordsToRead(42);
assertEquals(Integer.valueOf(42), dataFormat.getNumberOfRecordsToRead());
assertEquals(42, dataFormat.createAndConfigureParserSettings().getNumberOfRecordsToRead());
}
@Test
public void shouldConfigureEmptyValue() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setEmptyValue("empty");
assertEquals("empty", dataFormat.getEmptyValue());
assertEquals("empty", dataFormat.createAndConfigureWriterSettings().getEmptyValue());
assertEquals("empty", dataFormat.createAndConfigureParserSettings().getEmptyValue());
}
@Test
public void shouldConfigureLineSeparator() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setLineSeparator("ls");
assertEquals("ls", dataFormat.getLineSeparator());
assertEquals("ls", dataFormat.createAndConfigureWriterSettings().getFormat().getLineSeparatorString());
assertEquals("ls", dataFormat.createAndConfigureParserSettings().getFormat().getLineSeparatorString());
}
@Test
public void shouldConfigureNormalizedLineSeparator() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setNormalizedLineSeparator('n');
assertEquals(Character.valueOf('n'), dataFormat.getNormalizedLineSeparator());
assertEquals('n', dataFormat.createAndConfigureWriterSettings().getFormat().getNormalizedNewline());
assertEquals('n', dataFormat.createAndConfigureParserSettings().getFormat().getNormalizedNewline());
}
@Test
public void shouldConfigureComment() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setComment('c');
assertEquals(Character.valueOf('c'), dataFormat.getComment());
assertEquals('c', dataFormat.createAndConfigureWriterSettings().getFormat().getComment());
assertEquals('c', dataFormat.createAndConfigureParserSettings().getFormat().getComment());
}
@Test
public void shouldConfigureLazyLoad() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setLazyLoad(true);
assertTrue(dataFormat.isLazyLoad());
}
@Test
public void shouldConfigureAsMap() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setAsMap(true);
assertTrue(dataFormat.isAsMap());
}
@Test
public void shouldConfigureQuoteAllFields() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setQuoteAllFields(true);
assertTrue(dataFormat.getQuoteAllFields());
assertTrue(dataFormat.createAndConfigureWriterSettings().getQuoteAllFields());
}
@Test
public void shouldConfigureQuote() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setQuote('q');
assertEquals(Character.valueOf('q'), dataFormat.getQuote());
assertEquals('q', dataFormat.createAndConfigureWriterSettings().getFormat().getQuote());
assertEquals('q', dataFormat.createAndConfigureParserSettings().getFormat().getQuote());
}
@Test
public void shouldConfigureQuoteEscape() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setQuoteEscape('e');
assertEquals(Character.valueOf('e'), dataFormat.getQuoteEscape());
assertEquals('e', dataFormat.createAndConfigureWriterSettings().getFormat().getQuoteEscape());
assertEquals('e', dataFormat.createAndConfigureParserSettings().getFormat().getQuoteEscape());
}
@Test
public void shouldConfigureDelimiter() {
UniVocityCsvDataFormat dataFormat = new UniVocityCsvDataFormat()
.setDelimiter('d');
assertEquals(Character.valueOf('d'), dataFormat.getDelimiter());
assertEquals('d', dataFormat.createAndConfigureWriterSettings().getFormat().getDelimiter());
assertEquals('d', dataFormat.createAndConfigureParserSettings().getFormat().getDelimiter());
}
}
| apache-2.0 |
ppamorim/fresco | fbcore/src/main/java/com/facebook/datasource/BaseDataSubscriber.java | 1838 | /*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.datasource;
/**
* Base implementation of {@link DataSubscriber} that ensures that the data source is closed when
* the subscriber has finished with it.
* <p>
* Sample usage:
* <pre>
* <code>
* dataSource.subscribe(
* new BaseDataSubscriber() {
* {@literal @}Override
* public void onNewResultImpl(DataSource dataSource) {
* // Store image ref to be released later.
* mCloseableImageRef = dataSource.getResult();
* // Use the image.
* updateImage(mCloseableImageRef);
* // No need to do any cleanup of the data source.
* }
*
* {@literal @}Override
* public void onFailureImpl(DataSource dataSource) {
* // No cleanup of the data source required here.
* }
* });
* </code>
* </pre>
*/
public abstract class BaseDataSubscriber<T> implements DataSubscriber<T> {
@Override
public void onNewResult(DataSource<T> dataSource) {
try {
onNewResultImpl(dataSource);
} finally {
if (dataSource.isFinished()) {
dataSource.close();
}
}
}
@Override
public void onFailure(DataSource<T> dataSource) {
try {
onFailureImpl(dataSource);
} finally {
dataSource.close();
}
}
@Override
public void onCancellation(DataSource<T> dataSource) {
}
@Override
public void onProgressUpdate(DataSource<T> dataSource) {
}
protected abstract void onNewResultImpl(DataSource<T> dataSource);
protected abstract void onFailureImpl(DataSource<T> dataSource);
}
| bsd-3-clause |
JanesR/javacv | src/main/java/com/googlecode/javacv/ProCamTransformer.java | 23990 | /*
* Copyright (C) 2009,2010,2011,2012 Samuel Audet
*
* This file is part of JavaCV.
*
* JavaCV 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 (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* JavaCV 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 JavaCV. If not, see <http://www.gnu.org/licenses/>.
*/
package com.googlecode.javacv;
import static com.googlecode.javacv.cpp.cvkernels.*;
import static com.googlecode.javacv.cpp.opencv_calib3d.*;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
/**
*
* @author Samuel Audet
*/
public class ProCamTransformer implements ImageTransformer {
public ProCamTransformer(double[] referencePoints,
CameraDevice camera, ProjectorDevice projector) {
this(referencePoints, camera, projector, null);
}
public ProCamTransformer(double[] referencePoints,
CameraDevice camera, ProjectorDevice projector, CvMat n) {
this.camera = camera;
this.projector = projector;
if (referencePoints != null) {
this.surfaceTransformer = new ProjectiveColorTransformer(
camera.cameraMatrix, camera.cameraMatrix, null, null, n,
referencePoints, null, null, 3, 0);
}
double[] referencePoints1 = { 0, 0, camera.imageWidth/2, camera.imageHeight, camera.imageWidth, 0 };
double[] referencePoints2 = { 0, 0, projector.imageWidth/2, projector.imageHeight, projector.imageWidth, 0 };
if (n != null) {
invCameraMatrix = CvMat.create(3, 3);
cvInvert(camera.cameraMatrix, invCameraMatrix);
JavaCV.perspectiveTransform(referencePoints2, referencePoints1,
invCameraMatrix, projector.cameraMatrix, projector.R, projector.T, n, true);
}
this.projectorTransformer = new ProjectiveColorTransformer(
camera.cameraMatrix, projector.cameraMatrix, projector.R, projector.T, null,
referencePoints1, referencePoints2, projector.colorMixingMatrix,
/*surfaceTransformer == null ? 3 : */1, 3);
// CvMat n2 = createParameters().getN();
if (referencePoints != null && n != null) {
frontoParallelH = camera.getFrontoParallelH(referencePoints, n, CvMat.create(3, 3));
invFrontoParallelH = frontoParallelH.clone();
cvInvert(frontoParallelH, invFrontoParallelH);
}
}
protected CameraDevice camera = null;
protected ProjectorDevice projector = null;
protected ProjectiveColorTransformer surfaceTransformer = null;
protected ProjectiveColorTransformer projectorTransformer = null;
protected IplImage[] projectorImage = null, surfaceImage = null;
protected CvScalar fillColor = cvScalar(0.0, 0.0, 0.0, 1.0);
protected CvRect roi = new CvRect();
protected CvMat frontoParallelH = null, invFrontoParallelH = null;
protected CvMat invCameraMatrix = null;
protected KernelData kernelData = null;
protected CvMat[] H1 = null;
protected CvMat[] H2 = null;
protected CvMat[] X = null;
public int getNumGains() {
return projectorTransformer.getNumGains();
}
public int getNumBiases() {
return projectorTransformer.getNumBiases();
}
public CvScalar getFillColor() {
return fillColor;
}
public void setFillColor(CvScalar fillColor) {
this.fillColor = fillColor;
}
public ProjectiveColorTransformer getSurfaceTransformer() {
return surfaceTransformer;
}
public ProjectiveColorTransformer getProjectorTransformer() {
return projectorTransformer;
}
public IplImage getProjectorImage(int pyramidLevel) {
return projectorImage[pyramidLevel];
}
public void setProjectorImage(IplImage projectorImage0, int minLevel, int maxLevel) {
setProjectorImage(projectorImage0, minLevel, maxLevel, true);
}
public void setProjectorImage(IplImage projectorImage0, int minLevel, int maxLevel, boolean convertToFloat) {
if (projectorImage == null || projectorImage.length != maxLevel+1) {
projectorImage = new IplImage[maxLevel+1];
}
if (projectorImage0.depth() == IPL_DEPTH_32F || !convertToFloat) {
projectorImage[minLevel] = projectorImage0;
} else {
if (projectorImage[minLevel] == null) {
projectorImage[minLevel] = IplImage.create(projectorImage0.width(), projectorImage0.height(),
IPL_DEPTH_32F, projectorImage0.nChannels(), projectorImage0.origin());
}
IplROI ir = projectorImage0.roi();
if (ir != null) {
int align = 1<<(maxLevel+1);
roi.x(Math.max(0, (int)Math.floor((double)ir.xOffset()/align)*align));
roi.y(Math.max(0, (int)Math.floor((double)ir.yOffset()/align)*align));
roi.width (Math.min(projectorImage0.width(), (int)Math.ceil((double)ir.width() /align)*align));
roi.height(Math.min(projectorImage0.height(), (int)Math.ceil((double)ir.height()/align)*align));
cvSetImageROI(projectorImage0, roi);
cvSetImageROI(projectorImage[minLevel], roi);
} else {
cvResetImageROI(projectorImage0);
cvResetImageROI(projectorImage[minLevel]);
}
cvConvertScale(projectorImage0, projectorImage[minLevel], 1.0/255.0, 0);
}
// CvScalar.ByValue average = cvAvg(projectorImage[0], null);
// cvSubS(projectorImage[0], average, projectorImage[0], null);
for (int i = minLevel+1; i <= maxLevel; i++) {
int w = projectorImage[i-1].width()/2;
int h = projectorImage[i-1].height()/2;
int d = projectorImage[i-1].depth();
int c = projectorImage[i-1].nChannels();
int o = projectorImage[i-1].origin();
if (projectorImage[i] == null) {
projectorImage[i] = IplImage.create(w, h, d, c, o);
}
IplROI ir = projectorImage[i-1].roi();
if (ir != null) {
roi.x(ir.xOffset()/2); roi.width (ir.width() /2);
roi.y(ir.yOffset()/2); roi.height(ir.height()/2);
cvSetImageROI(projectorImage[i], roi);
} else {
cvResetImageROI(projectorImage[i]);
}
cvPyrDown(projectorImage[i-1], projectorImage[i], CV_GAUSSIAN_5x5);
cvResetImageROI(projectorImage[i-1]);
}
}
public IplImage getSurfaceImage(int pyramidLevel) {
return surfaceImage[pyramidLevel];
}
public void setSurfaceImage(IplImage surfaceImage0, int pyramidLevels) {
if (surfaceImage == null || surfaceImage.length != pyramidLevels) {
surfaceImage = new IplImage[pyramidLevels];
}
surfaceImage[0] = surfaceImage0;
cvResetImageROI(surfaceImage0);
for (int i = 1; i < pyramidLevels; i++) {
int w = surfaceImage[i-1].width()/2;
int h = surfaceImage[i-1].height()/2;
int d = surfaceImage[i-1].depth();
int c = surfaceImage[i-1].nChannels();
int o = surfaceImage[i-1].origin();
if (surfaceImage[i] == null) {
surfaceImage[i] = IplImage.create(w, h, d, c, o);
} else {
cvResetImageROI(surfaceImage[i]);
}
cvPyrDown(surfaceImage[i-1], surfaceImage[i], CV_GAUSSIAN_5x5);
}
}
protected void prepareTransforms(CvMat H1, CvMat H2, CvMat X, int pyramidLevel, Parameters p) {
ProjectiveColorTransformer.Parameters cameraParameters = p.getSurfaceParameters();
ProjectiveColorTransformer.Parameters projectorParameters = p.getProjectorParameters();
if (surfaceTransformer != null) {
cvInvert(cameraParameters.getH(), H1);
}
cvInvert(projectorParameters.getH(), H2);
// adjust the scale of the transformation based on the pyramid level
if (pyramidLevel > 0) {
int scale = 1<<pyramidLevel;
if (surfaceTransformer != null) {
H1.put(2, H1.get(2)/scale);
H1.put(5, H1.get(5)/scale);
H1.put(6, H1.get(6)*scale);
H1.put(7, H1.get(7)*scale);
}
H2.put(2, H2.get(2)/scale);
H2.put(5, H2.get(5)/scale);
H2.put(6, H2.get(6)*scale);
H2.put(7, H2.get(7)*scale);
}
double[] x = projector.colorMixingMatrix.get();
double[] a = projectorParameters.getColorParameters();
double a2 = a[0];
X.put(a2*x[0], a2*x[1], a2*x[2], a[1],
a2*x[3], a2*x[4], a2*x[5], a[2],
a2*x[6], a2*x[7], a2*x[8], a[3],
0, 0, 0, 1);
}
public void transform(final IplImage srcImage, final IplImage dstImage, final CvRect roi,
final int pyramidLevel, final ImageTransformer.Parameters parameters, final boolean inverse) {
if (inverse) {
throw new UnsupportedOperationException("Inverse transform not supported.");
}
final Parameters p = ((Parameters)parameters);
final ProjectiveTransformer.Parameters cameraParameters = p.getSurfaceParameters();
final ProjectiveTransformer.Parameters projectorParameters = p.getProjectorParameters();
if (p.tempImage == null || p.tempImage.length <= pyramidLevel) {
p.tempImage = new IplImage[pyramidLevel+1];
}
p.tempImage[pyramidLevel] = IplImage.createIfNotCompatible(p.tempImage[pyramidLevel], dstImage);
if (roi == null) {
cvResetImageROI(p.tempImage[pyramidLevel]);
} else {
cvSetImageROI(p.tempImage[pyramidLevel], roi);
}
// Parallel.run(new Runnable() { public void run() {
// warp the template image
if (surfaceTransformer != null) {
surfaceTransformer.transform(srcImage, p.tempImage[pyramidLevel], roi, pyramidLevel, cameraParameters, false);
}
// }}, new Runnable() { public void run() {
// warp the projector image
projectorTransformer.transform(projectorImage[pyramidLevel], dstImage, roi, pyramidLevel, projectorParameters, false);
// }});
// multiply projector image with template image
if (surfaceTransformer != null) {
cvMul(dstImage, p.tempImage[pyramidLevel], dstImage, 1/dstImage.highValue());
} else {
cvCopy(p.tempImage[pyramidLevel], dstImage);
}
}
public void transform(CvMat srcPts, CvMat dstPts, ImageTransformer.Parameters parameters, boolean inverse) {
if (surfaceTransformer != null) {
surfaceTransformer.transform(srcPts, dstPts, ((Parameters)parameters).surfaceParameters, inverse);
} else if (dstPts != srcPts) {
dstPts.put(srcPts);
}
}
public void transform(Data[] data, CvRect roi, ImageTransformer.Parameters[] parameters, boolean[] inverses) {
assert data.length == parameters.length;
if (kernelData == null || kernelData.capacity() < data.length) {
kernelData = new KernelData(data.length);
}
if ((H1 == null || H1.length < data.length) && surfaceTransformer != null) {
H1 = new CvMat[data.length];
for (int i = 0; i < H1.length; i++) {
H1[i] = CvMat.create(3, 3);
}
}
if (H2 == null || H2.length < data.length) {
H2 = new CvMat[data.length];
for (int i = 0; i < H2.length; i++) {
H2[i] = CvMat.create(3, 3);
}
}
if (X == null || X.length < data.length) {
X = new CvMat[data.length];
for (int i = 0; i < X.length; i++) {
X[i] = CvMat.create(4, 4);
}
}
for (int i = 0; i < data.length; i++) {
kernelData.position(i);
kernelData.srcImg(projectorImage[data[i].pyramidLevel]);
kernelData.srcImg2(surfaceTransformer == null ? null : data[i].srcImg);
kernelData.subImg(data[i].subImg);
kernelData.srcDotImg(data[i].srcDotImg);
kernelData.mask(data[i].mask);
kernelData.zeroThreshold(data[i].zeroThreshold);
kernelData.outlierThreshold(data[i].outlierThreshold);
if (inverses != null && inverses[i]) {
throw new UnsupportedOperationException("Inverse transform not supported.");
}
prepareTransforms(surfaceTransformer == null ? null : H1[i],
H2[i], X[i], data[i].pyramidLevel, (Parameters)parameters[i]);
kernelData.H1(H2[i]);
kernelData.H2(surfaceTransformer == null ? null : H1[i]);
kernelData.X (X [i]);
kernelData.transImg(data[i].transImg);
kernelData.dstImg(data[i].dstImg);
kernelData.dstDstDot(data[i].dstDstDot);
}
int fullCapacity = kernelData.capacity();
kernelData.capacity(data.length);
multiWarpColorTransform(kernelData, roi, getFillColor());
kernelData.capacity(fullCapacity);
for (int i = 0; i < data.length; i++) {
kernelData.position(i);
data[i].dstCount = kernelData.dstCount();
data[i].dstCountZero = kernelData.dstCountZero();
data[i].dstCountOutlier = kernelData.dstCountOutlier();
data[i].srcDstDot = kernelData.srcDstDot();
}
// if (data[0].dstCountZero > 0) {
// System.err.println(data[0].dstCountZero + " out of " + data[0].dstCount
// + " are zero = " + 100*data[0].dstCountZero/data[0].dstCount + "%");
// }
}
public Parameters createParameters() {
return new Parameters();
}
public class Parameters implements ImageTransformer.Parameters {
protected Parameters() {
reset(false);
}
protected Parameters(ProjectiveColorTransformer.Parameters surfaceParameters,
ProjectiveColorTransformer.Parameters projectorParameters) {
reset(surfaceParameters, projectorParameters);
}
private ProjectiveColorTransformer.Parameters surfaceParameters = null;
private ProjectiveColorTransformer.Parameters projectorParameters = null;
private IplImage[] tempImage = null;
private CvMat H = CvMat.create(3, 3), R = CvMat.create(3, 3),
n = CvMat.create(3, 1), t = CvMat.create(3, 1);
public ProjectiveColorTransformer.Parameters getSurfaceParameters() {
return surfaceParameters;
}
public ProjectiveColorTransformer.Parameters getProjectorParameters() {
return projectorParameters;
}
private int getSizeForSurface() {
return surfaceTransformer == null ? 0 : surfaceParameters.size() -
surfaceTransformer.getNumGains() - surfaceTransformer.getNumBiases();
}
private int getSizeForProjector() {
return projectorParameters.size();
}
public int size() {
return getSizeForSurface() + getSizeForProjector();
}
public double[] get() {
double[] p = new double[size()];
for (int i = 0; i < p.length; i++) {
p[i] = get(i);
}
return p;
}
public double get(int i) {
if (i < getSizeForSurface()) {
return surfaceParameters.get(i);
} else {
return projectorParameters.get(i-getSizeForSurface());
}
}
public void set(double ... p) {
for (int i = 0; i < p.length; i++) {
set(i, p[i]);
}
}
public void set(int i, double p) {
if (i < getSizeForSurface()) {
surfaceParameters.set(i, p);
} else {
projectorParameters.set(i-getSizeForSurface(), p);
}
}
public void set(ImageTransformer.Parameters p) {
Parameters pcp = (Parameters)p;
if (surfaceTransformer != null) {
surfaceParameters.set(pcp.getSurfaceParameters());
surfaceParameters.resetColor(false);
}
projectorParameters.set(pcp.getProjectorParameters());
}
public void reset(boolean asIdentity) {
reset(null, null);
}
public void reset(ProjectiveColorTransformer.Parameters surfaceParameters,
ProjectiveColorTransformer.Parameters projectorParameters) {
if (surfaceParameters == null && surfaceTransformer != null) {
surfaceParameters = surfaceTransformer.createParameters();
}
if (projectorParameters == null) {
projectorParameters = projectorTransformer.createParameters();
}
this.surfaceParameters = surfaceParameters;
this.projectorParameters = projectorParameters;
setSubspace(getSubspace());
}
// public boolean addDelta(int i) {
// return addDelta(i, 1);
// }
// public boolean addDelta(int i, double scale) {
// // gradient varies linearly with intensity, so
// // the increment value is not very important, but
// // referenceCameraImage is good only for the value 1,
// // so let's use that
// if (i < getSizeForSurface()) {
// surfaceParameters.addDelta(i, scale);
// projectorParameters.setUpdateNeeded(true);
// } else {
// projectorParameters.addDelta(i-getSizeForSurface(), scale);
// }
//
// return false;
// }
public double getConstraintError() {
double error = surfaceTransformer == null ? 0 : surfaceParameters.getConstraintError();
projectorParameters.update();
return error;
}
public void compose(ImageTransformer.Parameters p1, boolean inverse1,
ImageTransformer.Parameters p2, boolean inverse2) {
throw new UnsupportedOperationException("Compose operation not supported.");
}
public boolean preoptimize() {
double[] p = setSubspaceInternal(getSubspaceInternal());
if (p != null) {
set(8, p[8]);
set(9, p[9]);
set(10, p[10]);
return true;
}
return false;
}
public void setSubspace(double ... p) {
double[] dst = setSubspaceInternal(p);
if (dst != null) {
set(dst);
}
}
public double[] getSubspace() {
return getSubspaceInternal();
}
private double[] setSubspaceInternal(double ... p) {
if (invFrontoParallelH == null) {
return null;
}
double[] dst = new double[8+3];
t.put(p[0], p[1], p[2]);
cvRodrigues2(t, R, null);
t.put(p[3], p[4], p[5]);
// compute new H
H.put(R.get(0), R.get(1), t.get(0),
R.get(3), R.get(4), t.get(1),
R.get(6), R.get(7), t.get(2));
cvMatMul(H, invFrontoParallelH, H);
cvMatMul(surfaceTransformer.getK2(), H, H);
cvMatMul(H, surfaceTransformer.getInvK1(), H);
// compute new n, rotation from the z-axis
cvGEMM(R, t, 1, null, 0, t, CV_GEMM_A_T);
double scale = 1/t.get(2);
n.put(0.0, 0.0, 1.0);
cvGEMM(R, n, scale, null, 0, n, 0);
// compute and set new three points
double[] src = projectorTransformer.getReferencePoints2();
JavaCV.perspectiveTransform(src, dst,
projectorTransformer.getInvK1(),projectorTransformer.getK2(),
projectorTransformer.getR(), projectorTransformer.getT(), n, true);
dst[8] = dst[0];
dst[9] = dst[2];
dst[10] = dst[4];
// compute and set new four points
JavaCV.perspectiveTransform(surfaceTransformer.getReferencePoints1(), dst, H);
return dst;
}
private double[] getSubspaceInternal() {
if (frontoParallelH == null) {
return null;
}
cvMatMul(surfaceTransformer.getK1(), frontoParallelH, H);
cvMatMul(surfaceParameters .getH(), H, H);
cvMatMul(surfaceTransformer.getInvK2(), H, H);
JavaCV.HtoRt(H, R, t);
cvRodrigues2(R, n, null);
double[] p = { n.get(0), n.get(1), n.get(2),
t.get(0), t.get(1), t.get(2) };
return p;
}
public CvMat getN() {
double[] src = projectorTransformer.getReferencePoints2();
double[] dst = projectorTransformer.getReferencePoints1().clone();
dst[0] = projectorParameters.get(0);
dst[2] = projectorParameters.get(1);
dst[4] = projectorParameters.get(2);
// get plane parameters n, but since we model the target to be
// the camera, we have to inverse everything before calling
// getPlaneParameters() and reframe the n it returns
cvTranspose(projectorTransformer.getR(), R);
cvGEMM(R, projectorTransformer.getT(), -1, null, 0, t, 0);
JavaCV.getPlaneParameters(src, dst, projectorTransformer.getInvK2(),
projectorTransformer.getK1(), R, t, n);
double d = 1 + cvDotProduct(n, projectorTransformer.getT());
cvGEMM(R, n, 1/d, null, 0, n, 0);
return n;
}
public CvMat getN0() {
n = getN();
if (surfaceTransformer == null) {
return n;
}
// remove projective effect of the current n,
// leaving only the effect of n0
camera.getFrontoParallelH(surfaceParameters.get(), n, R);
cvInvert(surfaceParameters.getH(), H);
cvMatMul(H, surfaceTransformer.getK2(), H);
cvMatMul(H, R, H);
cvMatMul(surfaceTransformer.getInvK1(), H, H);
JavaCV.HtoRt(H, R, t);
// compute n0, as a rotation from the z-axis
cvGEMM(R, t, 1, null, 0, t, CV_GEMM_A_T);
double scale = 1/t.get(2);
n.put(0.0, 0.0, 1.0);
cvGEMM(R, n, scale, null, 0, n, 0);
return n;
}
@Override public Parameters clone() {
Parameters p = new Parameters();
p.surfaceParameters = surfaceParameters == null ? null : surfaceParameters.clone();
p.projectorParameters = projectorParameters.clone();
return p;
}
@Override public String toString() {
if (surfaceParameters != null) {
return surfaceParameters.toString() + projectorParameters.toString();
} else {
return projectorParameters.toString();
}
}
}
}
| gpl-2.0 |
CandleCandle/camel | components/camel-jaxb/src/test/java/org/apache/camel/example/Bar.java | 1514 | /**
* 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.example;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Bar {
@XmlAttribute
private String name;
@XmlAttribute
private String value;
public Bar() {
}
public void setName(String name) {
this.name = name;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
| apache-2.0 |
nelsonsilva/libgdx | backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteFloatBufferAdapter.java | 4412 | /* 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 java.nio;
import com.google.gwt.typedarrays.shared.ArrayBufferView;
import com.google.gwt.typedarrays.shared.Float32Array;
import com.google.gwt.typedarrays.shared.TypedArrays;
/** This class wraps a byte buffer to be a float buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the
* adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position
* and limit.</li>
* </ul>
* </p> */
final class DirectReadWriteFloatBufferAdapter extends FloatBuffer implements HasArrayBufferView {
// implements DirectBuffer {
static FloatBuffer wrap (DirectReadWriteByteBuffer byteBuffer) {
return new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice());
}
private final DirectReadWriteByteBuffer byteBuffer;
private final Float32Array floatArray;
DirectReadWriteFloatBufferAdapter (DirectReadWriteByteBuffer byteBuffer) {
super((byteBuffer.capacity() >> 2));
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
this.floatArray = TypedArrays.createFloat32Array(byteBuffer.byteArray.buffer(), byteBuffer.byteArray.byteOffset(), capacity);
}
// TODO(haustein) This will be slow
@Override
public FloatBuffer asReadOnlyBuffer () {
DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter(byteBuffer);
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public FloatBuffer compact () {
byteBuffer.limit(limit << 2);
byteBuffer.position(position << 2);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
@Override
public FloatBuffer duplicate () {
DirectReadWriteFloatBufferAdapter buf = new DirectReadWriteFloatBufferAdapter(
(DirectReadWriteByteBuffer)byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public float get () {
// if (position == limit) {
// throw new BufferUnderflowException();
// }
return floatArray.get(position++);
}
@Override
public float get (int index) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
return floatArray.get(index);
}
@Override
public boolean isDirect () {
return true;
}
@Override
public boolean isReadOnly () {
return false;
}
@Override
public ByteOrder order () {
return byteBuffer.order();
}
@Override
protected float[] protectedArray () {
throw new UnsupportedOperationException();
}
@Override
protected int protectedArrayOffset () {
throw new UnsupportedOperationException();
}
@Override
protected boolean protectedHasArray () {
return false;
}
@Override
public FloatBuffer put (float c) {
// if (position == limit) {
// throw new BufferOverflowException();
// }
floatArray.set(position++, c);
return this;
}
@Override
public FloatBuffer put (int index, float c) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
floatArray.set(index, c);
return this;
}
@Override
public FloatBuffer slice () {
byteBuffer.limit(limit << 2);
byteBuffer.position(position << 2);
FloatBuffer result = new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice());
byteBuffer.clear();
return result;
}
public ArrayBufferView getTypedArray () {
return floatArray;
}
public int getElementSize () {
return 4;
}
}
| apache-2.0 |
esi-mineset/spark | sql/core/src/main/java/org/apache/spark/sql/api/java/package-info.java | 942 | /*
* 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.
*/
/**
* Allows the execution of relational queries, including those expressed in SQL using Spark.
*/
package org.apache.spark.sql.api.java;
| apache-2.0 |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/oncrpc/RpcMessage.java | 2009 | /**
* 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.oncrpc;
/**
* Represent an RPC message as defined in RFC 1831.
*/
public abstract class RpcMessage {
/** Message type */
public static enum Type {
// the order of the values below are significant.
RPC_CALL,
RPC_REPLY;
public int getValue() {
return ordinal();
}
public static Type fromValue(int value) {
if (value < 0 || value >= values().length) {
return null;
}
return values()[value];
}
}
protected final int xid;
protected final Type messageType;
RpcMessage(int xid, Type messageType) {
if (messageType != Type.RPC_CALL && messageType != Type.RPC_REPLY) {
throw new IllegalArgumentException("Invalid message type " + messageType);
}
this.xid = xid;
this.messageType = messageType;
}
public abstract XDR write(XDR xdr);
public int getXid() {
return xid;
}
public Type getMessageType() {
return messageType;
}
protected void validateMessageType(Type expected) {
if (expected != messageType) {
throw new IllegalArgumentException("Message type is expected to be "
+ expected + " but got " + messageType);
}
}
}
| apache-2.0 |
mkis-/elasticsearch | src/main/java/org/elasticsearch/index/analysis/DelimitedPayloadTokenFilterFactory.java | 2762 | /*
* 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.index.analysis;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.payloads.*;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.assistedinject.Assisted;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.settings.IndexSettings;
/**
*
*/
public class DelimitedPayloadTokenFilterFactory extends AbstractTokenFilterFactory {
public static final char DEFAULT_DELIMITER = '|';
public static final PayloadEncoder DEFAULT_ENCODER = new FloatEncoder();
static final String ENCODING = "encoding";
static final String DELIMITER = "delimiter";
char delimiter;
PayloadEncoder encoder;
@Inject
public DelimitedPayloadTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name,
@Assisted Settings settings) {
super(index, indexSettings, name, settings);
String delimiterConf = settings.get(DELIMITER);
if (delimiterConf != null) {
delimiter = delimiterConf.charAt(0);
} else {
delimiter = DEFAULT_DELIMITER;
}
if (settings.get(ENCODING) != null) {
if (settings.get(ENCODING).equals("float")) {
encoder = new FloatEncoder();
} else if (settings.get(ENCODING).equals("int")) {
encoder = new IntegerEncoder();
} else if (settings.get(ENCODING).equals("identity")) {
encoder = new IdentityEncoder();
}
} else {
encoder = DEFAULT_ENCODER;
}
}
@Override
public TokenStream create(TokenStream tokenStream) {
DelimitedPayloadTokenFilter filter = new DelimitedPayloadTokenFilter(tokenStream, delimiter, encoder);
return filter;
}
}
| apache-2.0 |
TealCube/loot | src/main/java/info/faceland/loot/data/PriceData.java | 435 | package info.faceland.loot.data;
public class PriceData {
private int price;
private boolean rare;
public PriceData (int price, boolean rare) {
this.price = price;
this.rare = rare;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public boolean isRare() {
return rare;
}
public void setRare(boolean rare) {
this.rare = rare;
}
}
| isc |
Tetr4/Spacecurl | app/src/main/java/de/klimek/spacecurl/activities/BasicTrainingActivity.java | 14055 |
package de.klimek.spacecurl.activities;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelSlideListener;
import java.util.ArrayList;
import java.util.List;
import de.klimek.spacecurl.Database;
import de.klimek.spacecurl.R;
import de.klimek.spacecurl.game.GameCallBackListener;
import de.klimek.spacecurl.game.GameDescription;
import de.klimek.spacecurl.game.GameFragment;
import de.klimek.spacecurl.util.ColorGradient;
import de.klimek.spacecurl.util.cards.StatusCard;
import de.klimek.spacecurl.util.collection.GameStatus;
import de.klimek.spacecurl.util.collection.Training;
import de.klimek.spacecurl.util.collection.TrainingStatus;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;
import it.gmariotti.cardslib.library.view.CardView;
/**
* This abstract class loads a training and provides functionality to
* subclasses, e. g. usage of the status panel, switching games, and showing a
* pause screen. <br/>
* A Training must be loaded with {@link #loadTraining(Training)}. In order to
* use the status-panel {@link #useStatusPanel()} has to be called.
*
* @author Mike Klimek
* @see <a href="http://developer.android.com/reference/packages.html">Android
* API</a>
*/
public abstract class BasicTrainingActivity extends FragmentActivity implements OnClickListener,
GameCallBackListener {
public static final String TAG = BasicTrainingActivity.class.getName();
// Status panel
private boolean mUsesStatus = false;
private TrainingStatus mTrainingStatus;
private GameStatus mCurGameStatus;
private int mStatusColor;
private ColorGradient mStatusGradient = new ColorGradient(Color.RED, Color.YELLOW, Color.GREEN);
private FrameLayout mStatusIndicator;
private ImageButton mSlidingToggleButton;
private boolean mButtonImageIsExpand = true;
private SlidingUpPanelLayout mSlidingUpPanel;
private CardListView mCardListView;
private CardArrayAdapter mCardArrayAdapter;
private List<Card> mCards = new ArrayList<Card>();
private GameFragment mGameFragment;
private FrameLayout mGameFrame;
private Training mTraining;
private Database mDatabase;
// Pause Frame
private FrameLayout mPauseFrame;
private LinearLayout mInstructionLayout;
private ImageView mResumeButton;
private TextView mInstructionsTextView;
private String mInstructions = "";
private int mShortAnimationDuration;
private State mState = State.Paused;
public static enum State {
Paused, Pausing, Running
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabase = Database.getInstance(this);
setContentView(R.layout.activity_base);
setupPauseView();
}
/**
* Dialog with instructions for the current game or pause/play icon. Shows
* when the user interacts with the App.
*/
private void setupPauseView() {
mGameFrame = (FrameLayout) findViewById(R.id.game_frame);
mGameFrame.setOnClickListener(this);
// hide initially
mPauseFrame = (FrameLayout) findViewById(R.id.pause_layout);
mPauseFrame.setAlpha(0.0f);
mPauseFrame.setVisibility(View.GONE);
mInstructionLayout = (LinearLayout) findViewById(R.id.instruction_layout);
mResumeButton = (ImageView) findViewById(R.id.resume_button);
mInstructionsTextView = (TextView) findViewById(R.id.instructions_textview);
mShortAnimationDuration = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
@Override
protected void onResume() {
super.onResume();
if (mDatabase.isOrientationLandscape()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
/**
* Subclasses must load a Training with this method.
*
* @param training
*/
protected final void loadTraining(Training training) {
mTraining = training;
}
/**
* Subclasses can use this method to enable the status-panel.
*/
protected final void useStatusPanel() {
mTrainingStatus = mTraining.createTrainingStatus();
mUsesStatus = true;
mStatusIndicator = (FrameLayout) findViewById(R.id.status_indicator);
mSlidingToggleButton = (ImageButton) findViewById(R.id.panel_button);
mSlidingUpPanel = (SlidingUpPanelLayout) findViewById(R.id.content_frame);
mSlidingUpPanel.setPanelSlideListener(new PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
if (slideOffset > 0.5f && mButtonImageIsExpand) {
mSlidingToggleButton.setImageResource(R.drawable.ic_collapse);
mButtonImageIsExpand = false;
} else if (slideOffset < 0.5f && !mButtonImageIsExpand) {
mSlidingToggleButton.setImageResource(R.drawable.ic_expand);
mButtonImageIsExpand = true;
}
}
@Override
public void onPanelCollapsed(View panel) {
}
@Override
public void onPanelExpanded(View panel) {
}
@Override
public void onPanelAnchored(View panel) {
}
@Override
public void onPanelHidden(View panel) {
}
});
int statusIndicatorHeight = (int) (getResources()
.getDimension(R.dimen.status_indicator_height));
mSlidingUpPanel.setPanelHeight(statusIndicatorHeight);
// delegate clicks to underlying panel
mSlidingToggleButton.setClickable(false);
mSlidingUpPanel.setEnabled(true);
// setup cardlist
mCardArrayAdapter = new FixedCardArrayAdapter(this, mCards);
mCardListView = (CardListView) findViewById(R.id.card_list);
mCardListView.setAdapter(mCardArrayAdapter);
}
protected final void updateCurGameStatus(final float status) {
// graph
mCurGameStatus.addStatus(status);
// indicator color
mStatusColor = mStatusGradient.getColorForFraction(status);
mStatusIndicator.setBackgroundColor(mStatusColor);
}
protected final void expandSlidingPane() {
if (mState == State.Running) {
pause();
mState = State.Paused;
}
mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
}
protected final void collapseSlidingPane() {
mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
protected final void showStatusIndicator() {
mStatusIndicator.setVisibility(View.VISIBLE);
}
protected final void hideStatusIndicator() {
mStatusIndicator.setVisibility(View.GONE);
}
protected final void lockSlidingPane() {
mSlidingToggleButton.setVisibility(View.GONE);
}
protected final void unlockSlidingPane() {
mSlidingToggleButton.setVisibility(View.VISIBLE);
}
/**
* Creates a new GameFragment from a gameDescriptionIndex and displays it.
* Switches to the associated gameStatus from a previous game (overwriting
* it) or creates a new one.
*
* @param gameDescriptionIndex the game to start
* @param enterAnimation how the fragment should enter
* @param exitAnimation how the previous fragment should be removed
*/
protected final void switchToGame(int gameDescriptionIndex, int enterAnimation,
int exitAnimation) {
mState = State.Paused;
pause();
// get Fragment
GameDescription newGameDescription = mTraining.get(gameDescriptionIndex);
mGameFragment = newGameDescription.createFragment();
// Transaction
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(enterAnimation, exitAnimation)
.replace(R.id.game_frame, mGameFragment)
.commit();
// enable callback
mGameFragment.registerGameCallBackListener(this);
// update pause view
mInstructions = newGameDescription.getInstructions();
if (mInstructions == null || mInstructions.isEmpty()) {
// only show pause/play icon
mInstructionLayout.setVisibility(View.GONE);
mResumeButton.setVisibility(View.VISIBLE);
} else {
// only show instructions
mResumeButton.setVisibility(View.GONE);
mInstructionLayout.setVisibility(View.VISIBLE);
mInstructionsTextView.setText(mInstructions);
}
if (mUsesStatus) {
// switch to status associated with current game
mCurGameStatus = mTrainingStatus.get(gameDescriptionIndex);
if (mCurGameStatus == null) {
// create new
mCurGameStatus = new GameStatus(newGameDescription.getTitle());
mTrainingStatus.append(gameDescriptionIndex, mCurGameStatus);
mCards.add(gameDescriptionIndex, new StatusCard(this, mCurGameStatus));
mCardArrayAdapter.notifyDataSetChanged();
} else {
// reset existing
mCurGameStatus.reset();
mCardArrayAdapter.notifyDataSetChanged();
}
}
}
/**
* Convenience method. Same as
* {@link #switchToGame(int gameDescriptionIndex, int enterAnimation, int exitAnimation)}
* but uses standard fade_in/fade_out animations.
*
* @param gameDescriptionIndex the game to start
*/
protected final void switchToGame(int gameDescriptionIndex) {
switchToGame(gameDescriptionIndex, android.R.anim.fade_in, android.R.anim.fade_out);
}
@Override
protected void onPause() {
super.onPause();
if (mState == State.Running) {
pause();
}
mState = State.Paused;
}
@Override
public void onUserInteraction() {
// Pause on every user interaction
if (mState == State.Running) {
mState = State.Pausing;
pause();
} else if (mState == State.Pausing) {
// Previously clicked outside of gameframe and now possibly on
// gameframe again to resume
mState = State.Paused;
}
super.onUserInteraction();
}
/**
* Called when clicking inside the game frame (after onUserInteraction)
*/
@Override
public void onClick(View v) {
if (mState == State.Paused) {
// Resume when paused
resume();
mState = State.Running;
} else if (mState == State.Pausing) {
// We have just paused in onUserInteraction -> don't resume
mState = State.Paused;
}
}
private void pause() {
Log.v(TAG, "Paused");
// pause game
if (mGameFragment != null) {
mGameFragment.onPauseGame();
}
// Show pause view and grey out screen
mPauseFrame.setVisibility(View.VISIBLE);
mPauseFrame.animate()
.alpha(1f)
.setDuration(mShortAnimationDuration)
.setListener(null);
// Show navigation bar
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
private void resume() {
Log.v(TAG, "Resumed");
// hide pause view
mPauseFrame.animate()
.alpha(0f)
.setDuration(mShortAnimationDuration)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mPauseFrame.setVisibility(View.GONE);
}
});
// resume game
if (mGameFragment != null) {
mGameFragment.onResumeGame();
}
// Grey out navigation bar
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
/**
* Fixes bug in {@link CardArrayAdapter CardArrayAdapter's} Viewholder
* pattern. Otherwise the cards innerViewElements would not be replaced
* (Title and Graph from previous Graph is shown).
*
* @author Mike Klimek
*/
private class FixedCardArrayAdapter extends CardArrayAdapter {
public FixedCardArrayAdapter(Context context, List<Card> cards) {
super(context, cards);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Card card = (Card) getItem(position);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(R.layout.list_card_layout, parent, false);
}
CardView view = (CardView) convertView.findViewById(R.id.list_cardId);
view.setForceReplaceInnerLayout(true);
view.setCard(card);
return convertView;
}
}
}
| isc |
evantbyrne/vending-machine-kata | src/main/java/com/evanbyrne/vending_machine_kata/ui/Console.java | 4553 | package com.evanbyrne.vending_machine_kata.ui;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.SortedMap;
import org.jooq.lambda.tuple.Tuple2;
import com.evanbyrne.vending_machine_kata.coin.Cents;
import com.evanbyrne.vending_machine_kata.coin.Coin;
import com.evanbyrne.vending_machine_kata.coin.CoinCollection;
import com.evanbyrne.vending_machine_kata.coin.CoinFactory;
import com.evanbyrne.vending_machine_kata.inventory.IInventoryService;
import com.evanbyrne.vending_machine_kata.inventory.InventoryProduct;
/**
* Manages console input and output.
*/
public class Console {
/**
* Get change display for terminal output.
*
* @param Change.
* @return Formatted message.
*/
public String getChangeDisplay(final CoinCollection change) {
final ArrayList<String> display = new ArrayList<String>();
final LinkedHashMap<Coin, Integer> coinMap = new LinkedHashMap<Coin, Integer>();
display.add("THANK YOU");
for(final Coin coin : change.getList()) {
if(coinMap.containsKey(coin)) {
coinMap.put(coin, coinMap.get(coin) + 1);
} else {
coinMap.put(coin, 1);
}
}
if(!coinMap.isEmpty()) {
final ArrayList<String> displayReturn = new ArrayList<String>();
for(final Map.Entry<Coin, Integer> entry : coinMap.entrySet()) {
final String name = entry.getKey().name().toLowerCase();
final int count = entry.getValue();
displayReturn.add(String.format("%s (x%d)", name, count));
}
display.add("RETURN: " + String.join(", ", displayReturn));
}
return String.join("\n", display);
}
/**
* Get product listing display for terminal output.
*
* @param Sorted map of all inventory.
* @return Formatted message.
*/
public String getProductDisplay(final SortedMap<String, InventoryProduct> inventory) {
if(!inventory.isEmpty()) {
final ArrayList<String> display = new ArrayList<String>();
for(final Map.Entry<String, InventoryProduct> entry : inventory.entrySet()) {
final String centsString = Cents.toString(entry.getValue().getCents());
final String name = entry.getValue().getName();
final String key = entry.getKey();
display.add(String.format("%s\t%s\t%s", key, centsString, name));
}
return String.join("\n", display);
}
return "No items in vending machine.";
}
/**
* Prompt user for payment.
*
* Loops until payment >= selected product cost.
*
* @param Scanner.
* @param A product representing their selection.
* @return Payment.
*/
public CoinCollection promptForPayment(final Scanner scanner, final InventoryProduct selection) {
final CoinCollection paid = new CoinCollection();
Coin insert;
String input;
do {
System.out.println("PRICE: " + Cents.toString(selection.getCents()));
do {
System.out.print(String.format("INSERT COIN (%s): ", Cents.toString(paid.getTotal())));
input = scanner.nextLine();
insert = CoinFactory.getByName(input);
if(insert == null) {
System.out.println("Invalid coin. This machine accepts: quarter, dime, nickel.");
}
} while(insert == null);
paid.addCoin(insert);
} while(paid.getTotal() < selection.getCents());
return paid;
}
/**
* Prompt for product selection.
*
* Loops until a valid product has been selected.
*
* @param Scanner
* @param An implementation of IInventoryService.
* @return A tuple with the product key and product.
*/
public Tuple2<String, InventoryProduct> promptForSelection(final Scanner scanner, final IInventoryService inventoryService) {
InventoryProduct selection;
String input;
do {
System.out.print("SELECT: ");
input = scanner.nextLine();
selection = inventoryService.getProduct(input);
if( selection == null ) {
System.out.println("Invalid selection.");
}
} while(selection == null);
return new Tuple2<String, InventoryProduct>(input, selection);
}
}
| isc |
io7m/jcanephora | com.io7m.jcanephora.tests.lwjgl3/src/test/java/com/io7m/jcanephora/tests/lwjgl3/LWJGL3FramebuffersTestGL33.java | 1726 | /*
* Copyright © 2016 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jcanephora.tests.lwjgl3;
import com.io7m.jcanephora.core.api.JCGLContextType;
import com.io7m.jcanephora.core.api.JCGLInterfaceGL33Type;
import com.io7m.jcanephora.tests.contracts.JCGLFramebuffersContract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class LWJGL3FramebuffersTestGL33 extends JCGLFramebuffersContract
{
private static final Logger LOG;
static {
LOG = LoggerFactory.getLogger(LWJGL3FramebuffersTestGL33.class);
}
@Override
public void onTestCompleted()
{
LWJGL3TestContexts.closeAllContexts();
}
@Override
protected Interfaces getInterfaces(final String name)
{
final JCGLContextType c = LWJGL3TestContexts.newGL33Context(name, 24, 8);
final JCGLInterfaceGL33Type cg = c.contextGetGL33();
return new Interfaces(c, cg.framebuffers(), cg.textures());
}
@Override
protected boolean hasRealBlitting()
{
return true;
}
}
| isc |
DealerNextDoor/ApolloDev | src/org/apollo/game/event/handler/impl/ItemOnItemVerificationHandler.java | 1001 | package org.apollo.game.event.handler.impl;
import org.apollo.game.event.handler.EventHandler;
import org.apollo.game.event.handler.EventHandlerContext;
import org.apollo.game.event.impl.ItemOnItemEvent;
import org.apollo.game.model.Inventory;
import org.apollo.game.model.Item;
import org.apollo.game.model.Player;
/**
* An {@link EventHandler} which verifies the target item in {@link ItemOnItemEvent}s.
*
* @author Chris Fletcher
*/
public final class ItemOnItemVerificationHandler extends EventHandler<ItemOnItemEvent> {
@Override
public void handle(EventHandlerContext ctx, Player player, ItemOnItemEvent event) {
Inventory inventory = ItemVerificationHandler.interfaceToInventory(player, event.getTargetInterfaceId());
int slot = event.getTargetSlot();
if (slot < 0 || slot >= inventory.capacity()) {
ctx.breakHandlerChain();
return;
}
Item item = inventory.get(slot);
if (item == null || item.getId() != event.getTargetId()) {
ctx.breakHandlerChain();
}
}
} | isc |
yuandunlong/leychina-android | app/src/main/java/com/leychina/activity/ArtistDetailActivity.java | 2114 | package com.leychina.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.widget.ImageView;
import android.widget.TextView;
import com.leychina.R;
import com.leychina.model.Artist;
import com.leychina.value.Constant;
import com.leychina.widget.tabindicator.TouchyWebView;
import com.squareup.picasso.Picasso;
/**
* Created by yuandunlong on 11/21/15.
*/
public class ArtistDetailActivity extends AppCompatActivity {
TouchyWebView webview;
Artist artist;
ImageView imageView;
TextView weight, height, name, birthday;
public static void start(Context from, Artist artist) {
Intent intent = new Intent(from, ArtistDetailActivity.class);
intent.putExtra("artist", artist);
from.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
this.artist = (Artist) intent.getSerializableExtra("artist");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artist_detail);
webview = (TouchyWebView) findViewById(R.id.artist_webview);
imageView = (ImageView) findViewById(R.id.image_view_artist_cover);
Picasso.with(this).load(Constant.DOMAIN+"/static/upload/"+artist.getPhoto()).into(imageView);
name = (TextView) findViewById(R.id.text_view_name);
height = (TextView) findViewById(R.id.text_view_height);
weight = (TextView) findViewById(R.id.text_view_weight);
birthday= (TextView) findViewById(R.id.text_view_birthday);
// name.setText(artist.get);
weight.setText(artist.getWeight() + "");
height.setText(artist.getHeight() + "");
birthday.setText(artist.getBlood());
webview.setWebChromeClient(new WebChromeClient());
webview.getSettings().setDefaultTextEncodingName("utf-8");
webview.loadDataWithBaseURL(Constant.DOMAIN, artist.getDescription(), "text/html", "utf-8","");
}
}
| isc |