repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
quarkusio/quarkus | integration-tests/hibernate-reactive-postgresql/src/test/java/io/quarkus/it/hibernate/reactive/postgresql/HibernateReactiveFetchLazyInGraalIT.java | 224 | package io.quarkus.it.hibernate.reactive.postgresql;
import io.quarkus.test.junit.QuarkusIntegrationTest;
@QuarkusIntegrationTest
public class HibernateReactiveFetchLazyInGraalIT extends HibernateReactiveFetchLazyTest {
}
| apache-2.0 |
CheRut/chedmitry | chapter_006/src/main/java/ru/chedmitriy/waitnotify/ex1100/package-info.java | 1128 | /**
* junior
*
* @author CheDmitry
* @version 1.0
* @since 09.11.17
*
* В пакете продемонстрирована работа блокировки
* выполнения потоков.
* В качетве примере используется две емкости,
* которые расположены одна в другой,например
* банка в тазу.
* Если начать наполнять первый сосуд,второй не будет наполняться
* пока не начнет переливаться первый сосуд.
* Далее, с первого сосуда начнет выливаться некоторое количество воды,
* это же количество наполнит вторую емкость.
* В первой емкости воды станет немного меньше,
* опять доливаем воду в первую емкость,пока та не начнет
* переливаться и наполнять вторую емкость
*
*
*/
package ru.chedmitriy.waitnotify.ex1100; | apache-2.0 |
liminghuanghengtian/data_structure | src/main/java/com/liminghuang/thread/vl/VolatileTest.java | 2069 | package com.liminghuang.thread.vl;
/**
* ProjectName: example
* PackageName: com.liminghuang.thread.vl
* Description: 1. volatile保证可见性 2. volatile禁止指令重排
* <p>原理和实现:观察加入volatile关键字和没有加入volatile关键字时所生成的汇编代码发现,加入volatile关键字时,会多出一个lock前缀指令</p>
* <p>lock前缀指令实际上相当于一个内存屏障(也成内存栅栏),内存屏障会提供3个功能:</p>
* <p> 1)它确保指令重排序时不会把其后面的指令排到内存屏障之前的位置,也不会把前面的指令排到内存屏障的后面;即在执行到内存屏障这句指令时,在它前面的操作已经全部完成;</p>
* <p> 2)它会强制将对缓存的修改操作立即写入主存;</p>
* <p> 3)如果是写操作,它会导致其他CPU中对应的缓存行无效。</p>
* <p>
* CreateTime: 2020/5/8 11:13
* Modifier: Adaministrator
* ModifyTime: 2020/5/8 11:13
* Comment:
*
* @author Adaministrator
*/
public class VolatileTest {
public volatile int inc = 0;
public void increase() {
inc++;
}
public static void main(String[] args) {
final VolatileTest test = new VolatileTest();
for (int i = 0; i < 10; i++) {
Thread t = new Thread() {
public void run() {
for (int j = 0; j < 1000; j++)
test.increase();
}
};
t.start();
// // 每个线程按序执行
// try {
// t.join();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
int count;
// 这个条件没用,总是返回2,无法测试
while ((count = Thread.activeCount()) > 1) {//保证前面的线程都执行完
System.out.println("count: " + count);
Thread.yield();
}
System.out.println(test.inc);
}
}
| apache-2.0 |
blackberry/BB-BigData-Log-Tools | src/com/blackberry/logdriver/mapred/boom/ReBoomOutputFormat.java | 1295 | /** Copyright (c) 2014 BlackBerry Limited
*
* 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.blackberry.logdriver.mapred.boom;
import java.io.IOException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.util.Progressable;
import com.blackberry.logdriver.boom.LogLineData;
public class ReBoomOutputFormat extends FileOutputFormat<LogLineData, Text> {
@Override
public RecordWriter<LogLineData, Text> getRecordWriter(FileSystem ignored,
JobConf job, String name, Progressable progress) throws IOException {
return new ReBoomRecordWriter(this, job);
}
}
| apache-2.0 |
watson-developer-cloud/java-sdk | assistant/src/test/java/com/ibm/watson/assistant/v1/model/EntityMentionCollectionTest.java | 1494 | /*
* (C) Copyright IBM Corp. 2020.
*
* 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.ibm.watson.assistant.v1.model;
import static org.testng.Assert.*;
import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import com.ibm.watson.assistant.v1.utils.TestUtilities;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;
/** Unit test class for the EntityMentionCollection model. */
public class EntityMentionCollectionTest {
final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
final List<FileWithMetadata> mockListFileWithMetadata =
TestUtilities.creatMockListFileWithMetadata();
@Test
public void testEntityMentionCollection() throws Throwable {
EntityMentionCollection entityMentionCollectionModel = new EntityMentionCollection();
assertNull(entityMentionCollectionModel.getExamples());
assertNull(entityMentionCollectionModel.getPagination());
}
}
| apache-2.0 |
ashigeru/asakusafw-compiler | dag/compiler/flow/src/main/java/com/asakusafw/dag/compiler/flow/DataFlowGenerator.java | 35354 | /**
* Copyright 2011-2019 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.dag.compiler.flow;
import static com.asakusafw.dag.compiler.flow.DataFlowUtil.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asakusafw.dag.api.model.GraphInfo;
import com.asakusafw.dag.compiler.codegen.BufferOperatorGenerator;
import com.asakusafw.dag.compiler.codegen.ClassGeneratorContext;
import com.asakusafw.dag.compiler.codegen.CoGroupInputAdapterGenerator;
import com.asakusafw.dag.compiler.codegen.CompositeOperatorNodeGenerator;
import com.asakusafw.dag.compiler.codegen.EdgeDataTableAdapterGenerator;
import com.asakusafw.dag.compiler.codegen.EdgeOutputAdapterGenerator;
import com.asakusafw.dag.compiler.codegen.ExtractAdapterGenerator;
import com.asakusafw.dag.compiler.codegen.ExtractInputAdapterGenerator;
import com.asakusafw.dag.compiler.codegen.OperationAdapterGenerator;
import com.asakusafw.dag.compiler.codegen.OperatorNodeGenerator.AggregateNodeInfo;
import com.asakusafw.dag.compiler.codegen.OperatorNodeGenerator.NodeInfo;
import com.asakusafw.dag.compiler.codegen.OperatorNodeGenerator.OperatorNodeInfo;
import com.asakusafw.dag.compiler.codegen.VertexAdapterGenerator;
import com.asakusafw.dag.compiler.flow.adapter.OperatorNodeGeneratorContextAdapter;
import com.asakusafw.dag.compiler.model.ClassData;
import com.asakusafw.dag.compiler.model.build.GraphInfoBuilder;
import com.asakusafw.dag.compiler.model.build.ResolvedEdgeInfo;
import com.asakusafw.dag.compiler.model.build.ResolvedEdgeInfo.Movement;
import com.asakusafw.dag.compiler.model.build.ResolvedInputInfo;
import com.asakusafw.dag.compiler.model.build.ResolvedOutputInfo;
import com.asakusafw.dag.compiler.model.build.ResolvedVertexInfo;
import com.asakusafw.dag.compiler.model.graph.AggregateNode;
import com.asakusafw.dag.compiler.model.graph.DataTableNode;
import com.asakusafw.dag.compiler.model.graph.InputNode;
import com.asakusafw.dag.compiler.model.graph.OperationSpec;
import com.asakusafw.dag.compiler.model.graph.OperatorNode;
import com.asakusafw.dag.compiler.model.graph.OutputNode;
import com.asakusafw.dag.compiler.model.graph.SpecialElement;
import com.asakusafw.dag.compiler.model.graph.ValueElement;
import com.asakusafw.dag.compiler.model.graph.VertexElement;
import com.asakusafw.dag.compiler.model.graph.VertexElement.ElementKind;
import com.asakusafw.dag.compiler.model.plan.InputSpec;
import com.asakusafw.dag.compiler.model.plan.InputSpec.InputType;
import com.asakusafw.dag.compiler.model.plan.OutputSpec;
import com.asakusafw.dag.compiler.model.plan.OutputSpec.OutputType;
import com.asakusafw.dag.compiler.model.plan.VertexSpec;
import com.asakusafw.dag.compiler.model.plan.VertexSpec.OperationOption;
import com.asakusafw.dag.compiler.model.plan.VertexSpec.OperationType;
import com.asakusafw.dag.runtime.adapter.DataTable;
import com.asakusafw.dag.runtime.skeleton.CoGroupInputAdapter;
import com.asakusafw.dag.runtime.skeleton.CoGroupInputAdapter.BufferType;
import com.asakusafw.info.graph.Input;
import com.asakusafw.info.graph.Node;
import com.asakusafw.info.graph.Output;
import com.asakusafw.info.operator.InputAttribute;
import com.asakusafw.info.operator.OperatorAttribute;
import com.asakusafw.info.operator.OperatorSpec;
import com.asakusafw.info.operator.OutputAttribute;
import com.asakusafw.info.plan.DataExchange;
import com.asakusafw.info.plan.PlanAttribute;
import com.asakusafw.info.plan.PlanInputSpec;
import com.asakusafw.info.plan.PlanOutputSpec;
import com.asakusafw.info.plan.PlanVertexSpec;
import com.asakusafw.lang.compiler.api.CompilerOptions;
import com.asakusafw.lang.compiler.api.JobflowProcessor;
import com.asakusafw.lang.compiler.api.reference.ExternalInputReference;
import com.asakusafw.lang.compiler.extension.operator.info.OperatorGraphConverter;
import com.asakusafw.lang.compiler.extension.operator.info.PlanAttributeStore;
import com.asakusafw.lang.compiler.model.description.ClassDescription;
import com.asakusafw.lang.compiler.model.description.Descriptions;
import com.asakusafw.lang.compiler.model.description.TypeDescription;
import com.asakusafw.lang.compiler.model.graph.ExternalInput;
import com.asakusafw.lang.compiler.model.graph.ExternalOutput;
import com.asakusafw.lang.compiler.model.graph.Group;
import com.asakusafw.lang.compiler.model.graph.MarkerOperator;
import com.asakusafw.lang.compiler.model.graph.Operator;
import com.asakusafw.lang.compiler.model.graph.Operator.OperatorKind;
import com.asakusafw.lang.compiler.model.graph.OperatorArgument;
import com.asakusafw.lang.compiler.model.graph.OperatorGraph;
import com.asakusafw.lang.compiler.model.graph.OperatorInput;
import com.asakusafw.lang.compiler.model.graph.OperatorInput.InputUnit;
import com.asakusafw.lang.compiler.model.graph.OperatorOutput;
import com.asakusafw.lang.compiler.model.graph.OperatorPort;
import com.asakusafw.lang.compiler.model.graph.OperatorProperty;
import com.asakusafw.lang.compiler.model.graph.Operators;
import com.asakusafw.lang.compiler.model.graph.UserOperator;
import com.asakusafw.lang.compiler.model.info.JobflowInfo;
import com.asakusafw.lang.compiler.planning.Plan;
import com.asakusafw.lang.compiler.planning.Planning;
import com.asakusafw.lang.compiler.planning.SubPlan;
import com.asakusafw.lang.utils.common.Invariants;
import com.asakusafw.runtime.core.Result;
import com.asakusafw.runtime.flow.VoidResult;
import com.asakusafw.utils.graph.Graph;
import com.asakusafw.utils.graph.Graphs;
/**
* Generates data flow classes.
* @since 0.4.0
* @version 0.4.1
*/
public final class DataFlowGenerator {
static final Logger LOG = LoggerFactory.getLogger(DataFlowGenerator.class);
private static final TypeDescription TYPE_RESULT = Descriptions.typeOf(Result.class);
private static final TypeDescription TYPE_DATATABLE = Descriptions.typeOf(DataTable.class);
private static final ClassDescription TYPE_VOID_RESULT = Descriptions.classOf(VoidResult.class);
private static final VertexElement ELEMENT_EMPTY_DATATABLE =
new SpecialElement(VertexElement.ElementKind.EMPTY_DATA_TABLE, TYPE_DATATABLE);
private final Plan plan;
private final GraphInfoBuilder builder = new GraphInfoBuilder();
private final JobflowProcessor.Context processorContext;
private final ClassGeneratorContext generatorContext;
private final DagDescriptorFactory descriptors;
private final CompositeOperatorNodeGenerator genericOperators;
private final ExternalPortDriver externalPortDriver;
private DataFlowGenerator(
JobflowProcessor.Context processorContext,
ClassGeneratorContext generatorContext,
DagDescriptorFactory descriptors,
Plan plan) {
this.plan = plan;
this.processorContext = processorContext;
this.generatorContext = generatorContext;
this.descriptors = descriptors;
JobflowProcessor.Context root = processorContext;
this.genericOperators = CompositeOperatorNodeGenerator.load(root.getClassLoader());
this.externalPortDriver = CompositeExternalPortDriver.load(
new ExternalPortDriverProvider.Context(root.getOptions(), generatorContext, descriptors, plan));
}
/**
* Generates {@link GraphInfo} and its related classes.
* @param processorContext the current jobflow processor context
* @param generatorContext the current class generator context
* @param descriptors the DAG descriptor factory
* @param info the target jobflow info
* @param plan the target plan
* @return the generated {@link GraphInfo}
*/
public static GraphInfo generate(
JobflowProcessor.Context processorContext,
ClassGeneratorContext generatorContext,
DagDescriptorFactory descriptors,
JobflowInfo info,
Plan plan) {
return new DataFlowGenerator(processorContext, generatorContext, descriptors, plan).generate();
}
private GraphInfo generate() {
GraphInfo graph = generateGraph();
return graph;
}
private GraphInfo generateGraph() {
resolveOutputs();
resolveOperations();
resolvePlan();
savePlanInfo();
return builder.build(descriptors::newVoidEdge);
}
private void resolveOperations() {
Graph<SubPlan> graph = Planning.toDependencyGraph(plan);
Graph<SubPlan> rev = Graphs.transpose(graph);
for (SubPlan sub : Graphs.sortPostOrder(rev)) {
VertexSpec spec = VertexSpec.get(sub);
if (sub.getOperators().stream().anyMatch(o -> o.getOperatorKind() == OperatorKind.OUTPUT)) {
continue;
}
resolveOperation(spec);
}
}
private void resolveOperation(VertexSpec vertex) {
LOG.debug("compiling operation vertex: {} ({})", vertex.getId(), vertex.getLabel()); //$NON-NLS-1$
Map<Operator, VertexElement> resolved = resolveVertexElements(vertex);
ClassDescription inputAdapter = resolveInputAdapter(resolved, vertex);
List<ClassDescription> dataTableAdapters = resolveDataTableAdapters(resolved, vertex);
ClassDescription operationAdapter = resolveOperationAdapter(resolved, vertex);
ClassDescription outputAdapter = resolveOutputAdapter(resolved, vertex);
ClassDescription vertexClass = generate(vertex, "vertex", c -> {
return new VertexAdapterGenerator().generate(
generatorContext,
inputAdapter,
dataTableAdapters,
operationAdapter,
Collections.singletonList(outputAdapter),
vertex.getLabel(),
c);
});
Map<SubPlan.Input, ResolvedInputInfo> inputs = collectInputs(resolved, vertex);
Map<SubPlan.Output, ResolvedOutputInfo> outputs = collectOutputs(vertex);
ResolvedVertexInfo info = new ResolvedVertexInfo(
vertex.getId(),
descriptors.newVertex(vertexClass),
vertex.getLabel(),
inputs,
outputs);
register(builder, vertex, info, vertexClass);
}
private Map<Operator, VertexElement> resolveVertexElements(VertexSpec vertex) {
Map<Operator, VertexElement> resolved = new HashMap<>();
for (SubPlan.Input port : vertex.getOrigin().getInputs()) {
InputSpec spec = InputSpec.get(port);
if (spec.getInputType() != InputType.BROADCAST) {
continue;
}
resolved.put(port.getOperator(), new DataTableNode(spec.getId(), TYPE_DATATABLE, spec.getDataType()));
}
Graph<Operator> graph = Graphs.transpose(Planning.toDependencyGraph(vertex.getOrigin()));
for (Operator operator : Graphs.sortPostOrder(graph)) {
resolveBodyOperator(resolved, vertex, operator);
}
return resolved;
}
private ClassDescription resolveInputAdapter(Map<Operator, VertexElement> resolved, VertexSpec vertex) {
Operator primary = vertex.getPrimaryOperator();
if (vertex.getOperationOptions().contains(OperationOption.EXTERNAL_INPUT)) {
Invariants.require(primary instanceof ExternalInput);
ExternalInput input = (ExternalInput) primary;
VertexElement driver = resolveExtractDriver(resolved, vertex, input.getOperatorPort());
resolved.put(input, new InputNode(driver));
return resolveExternalInput(vertex, input);
} else if (vertex.getOperationType() == OperationType.CO_GROUP) {
Invariants.requireNonNull(primary);
VertexElement element = resolved.get(primary);
Invariants.requireNonNull(element);
List<InputSpec> inputs = new ArrayList<>();
for (OperatorInput input : primary.getInputs()) {
Collection<OperatorOutput> opposites = input.getOpposites();
if (opposites.isEmpty()) {
continue;
}
Invariants.require(opposites.size() == 1);
opposites.stream()
.map(OperatorPort::getOwner)
.map(p -> Invariants.requireNonNull(vertex.getOrigin().findInput(p)))
.map(InputSpec::get)
.filter(s -> s.getInputType() == InputType.CO_GROUP)
.forEach(inputs::add);
}
Invariants.require(inputs.size() >= 1);
// Note: only add the first input
resolved.put(inputs.get(0).getOrigin().getOperator(), new InputNode(element));
return resolveCoGroupInput(vertex, inputs);
} else {
List<InputSpec> inputs = vertex.getOrigin().getInputs().stream()
.map(InputSpec::get)
.filter(s -> s.getInputType() == InputType.EXTRACT)
.collect(Collectors.toList());
Invariants.require(inputs.size() == 1);
MarkerOperator edge = inputs.get(0).getOrigin().getOperator();
VertexElement driver = resolveExtractDriver(resolved, vertex, edge.getOutput());
resolved.put(edge, new InputNode(driver));
return resolveExtractInput(vertex, inputs.get(0));
}
}
private VertexElement resolveExtractDriver(
Map<Operator, VertexElement> resolved, VertexSpec vertex, OperatorOutput output) {
VertexElement succ = resolveSuccessors(resolved, vertex, output);
ClassDescription gen = generate(vertex, "operator", c -> {
return new ExtractAdapterGenerator().generate(succ, c);
});
return new OperatorNode(gen, TYPE_RESULT, output.getDataType(), succ);
}
private ClassDescription resolveExtractInput(VertexSpec vertex, InputSpec spec) {
ExtractInputAdapterGenerator.Spec s = new ExtractInputAdapterGenerator.Spec(spec.getId(), spec.getDataType());
return generate(vertex, "adapter.input", c -> {
return new ExtractInputAdapterGenerator().generate(generatorContext, s, c);
});
}
private ClassDescription resolveCoGroupInput(VertexSpec vertex, List<InputSpec> inputs) {
List<CoGroupInputAdapterGenerator.Spec> specs = inputs.stream()
.map(s -> new CoGroupInputAdapterGenerator.Spec(s.getId(), s.getDataType(), toBufferType(s)))
.collect(Collectors.toList());
return generate(vertex, "adapter.input", c -> {
return new CoGroupInputAdapterGenerator().generate(generatorContext, specs, c);
});
}
private static BufferType toBufferType(InputSpec spec) {
if (spec.getInputOptions().contains(InputSpec.InputOption.SPILL_OUT)) {
return CoGroupInputAdapter.BufferType.FILE;
}
return CoGroupInputAdapter.BufferType.HEAP;
}
private ClassDescription resolveExternalInput(VertexSpec vertex, ExternalInput input) {
if (externalPortDriver.accepts(input)) {
return externalPortDriver.processInput(input);
}
return resolveGenericInput(vertex, input);
}
private ClassDescription resolveGenericInput(VertexSpec vertex, ExternalInput input) {
ExternalInputReference ref = processorContext.addExternalInput(vertex.getId(), input.getInfo());
return generateInternalInput(generatorContext, vertex, input, ref.getPaths());
}
private ClassDescription resolveOutputAdapter(Map<Operator, VertexElement> resolved, VertexSpec vertex) {
List<EdgeOutputAdapterGenerator.Spec> specs = new ArrayList<>();
for (SubPlan.Output port : vertex.getOrigin().getOutputs()) {
if (resolved.containsKey(port.getOperator()) == false) {
continue;
}
OutputSpec spec = OutputSpec.get(port);
if (spec.getOutputType() == OutputType.DISCARD) {
continue;
}
ClassDescription mapperClass = null;
ClassDescription copierClass = null;
ClassDescription combinerClass = null;
Set<? extends SubPlan.Input> opposites = port.getOpposites();
if (opposites.isEmpty() == false) {
SubPlan.Input first = opposites.stream().findFirst().get();
ResolvedInputInfo downstream = builder.get(first);
mapperClass = downstream.getMapperType();
copierClass = downstream.getCopierType();
combinerClass = downstream.getCombinerType();
}
specs.add(new EdgeOutputAdapterGenerator.Spec(
spec.getId(), spec.getDataType(),
mapperClass, copierClass, combinerClass));
}
return generate(vertex, "adapter.output", c -> {
return new EdgeOutputAdapterGenerator().generate(generatorContext, specs, c);
});
}
private List<ClassDescription> resolveDataTableAdapters(Map<Operator, VertexElement> resolved, VertexSpec vertex) {
List<EdgeDataTableAdapterGenerator.Spec> specs = new ArrayList<>();
for (SubPlan.Input port : vertex.getOrigin().getInputs()) {
if (resolved.containsKey(port.getOperator()) == false) {
continue;
}
InputSpec spec = InputSpec.get(port);
if (spec.getInputType() != InputType.BROADCAST) {
continue;
}
Group group = Invariants.requireNonNull(spec.getPartitionInfo());
specs.add(new EdgeDataTableAdapterGenerator.Spec(spec.getId(), spec.getId(), spec.getDataType(), group));
}
if (specs.isEmpty()) {
return Collections.emptyList();
}
ClassDescription generated = generate(vertex, "adapter.table", c -> {
return new EdgeDataTableAdapterGenerator().generate(generatorContext, specs, c);
});
return Collections.singletonList(generated);
}
private ClassDescription resolveOperationAdapter(Map<Operator, VertexElement> resolved, VertexSpec vertex) {
return generate(vertex, "adapter.operation", c -> {
OperationSpec operation = null;
for (VertexElement element : resolved.values()) {
if (element instanceof InputNode) {
Invariants.require(operation == null);
operation = new OperationSpec((InputNode) element);
}
}
Invariants.requireNonNull(operation);
return new OperationAdapterGenerator().generate(generatorContext, operation, c);
});
}
private void resolveBodyOperator(Map<Operator, VertexElement> resolved, VertexSpec vertex, Operator operator) {
switch (operator.getOperatorKind()) {
case CORE:
case USER:
resolveGeneralOperator(resolved, vertex, operator);
break;
case MARKER:
if (vertex.getOrigin().findOutput(operator) != null) {
resolveEdgeOutput(resolved, vertex, vertex.getOrigin().findOutput(operator));
}
break;
default:
break;
}
}
private void resolveGeneralOperator(Map<Operator, VertexElement> resolved, VertexSpec vertex, Operator operator) {
Map<OperatorProperty, VertexElement> dependencies = new LinkedHashMap<>();
// add broadcast inputs as data tables
for (OperatorInput port : operator.getInputs()) {
if (port.getInputUnit() != InputUnit.WHOLE) {
continue;
}
VertexElement upstream = port.getOpposites().stream()
.map(OperatorPort::getOwner)
.map(resolved::get)
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
if (upstream != null && upstream.getElementKind() == ElementKind.DATA_TABLE) {
Invariants.require(port.getOpposites().size() == 1);
dependencies.put(port, upstream);
} else {
dependencies.put(port, ELEMENT_EMPTY_DATATABLE);
}
}
// add outputs as succeeding result sinks
for (OperatorOutput port : operator.getOutputs()) {
VertexElement successor = resolveSuccessors(resolved, vertex, port);
dependencies.put(port, successor);
}
// add arguments as constant values
for (OperatorArgument arg : operator.getArguments()) {
VertexElement value = new ValueElement(arg.getValue());
dependencies.put(arg, value);
}
OperatorNodeGeneratorContextAdapter adapter =
new OperatorNodeGeneratorContextAdapter(generatorContext, vertex.getOrigin(), dependencies);
NodeInfo info = genericOperators.generate(adapter, operator);
VertexElement element = resolveNodeInfo(vertex, operator, info);
resolved.put(operator, element);
generatorContext.addClassFile(info.getClassData());
}
private VertexElement resolveNodeInfo(VertexSpec vertex, Operator operator, NodeInfo info) {
if (info instanceof OperatorNodeInfo) {
return new OperatorNode(
info.getClassData().getDescription(),
TYPE_RESULT,
info.getDataType(),
info.getDependencies());
} else if (info instanceof AggregateNodeInfo) {
AggregateNodeInfo aggregate = (AggregateNodeInfo) info;
boolean combine = vertex.getOperationOptions().contains(OperationOption.PRE_AGGREGATION);
return new AggregateNode(
info.getClassData().getDescription(),
TYPE_RESULT,
aggregate.getMapperType(),
combine ? aggregate.getCopierType() : null,
combine ? aggregate.getCombinerType() : null,
aggregate.getInputType(),
aggregate.getOutputType(),
info.getDependencies());
} else {
throw new AssertionError(info);
}
}
private VertexElement resolveSuccessors(
Map<Operator, VertexElement> resolved, VertexSpec vertex, OperatorOutput port) {
List<VertexElement> succs = Operators.getSuccessors(Collections.singleton(port)).stream()
.map(o -> Invariants.requireNonNull(resolved.get(o)))
.collect(Collectors.toList());
if (succs.size() == 0) {
return new OperatorNode(TYPE_VOID_RESULT, TYPE_RESULT, port.getDataType(), Collections.emptyList());
} else if (succs.size() == 1) {
return succs.get(0);
} else {
ClassDescription buffer = BufferOperatorGenerator.get(generatorContext, succs);
return new OperatorNode(buffer, TYPE_RESULT, port.getDataType(), succs);
}
}
private void resolveEdgeOutput(Map<Operator, VertexElement> resolved, VertexSpec vertex, SubPlan.Output port) {
OutputSpec spec = OutputSpec.get(port);
VertexElement element;
if (spec.getOutputType() == OutputType.DISCARD) {
element = new OperatorNode(TYPE_VOID_RESULT, TYPE_RESULT, spec.getSourceType(), Collections.emptyList());
} else {
element = new OutputNode(spec.getId(), TYPE_RESULT, spec.getSourceType());
}
MarkerOperator operator = port.getOperator();
resolved.put(operator, element);
}
private Map<SubPlan.Input, ResolvedInputInfo> collectInputs(
Map<Operator, VertexElement> resolved, VertexSpec vertex) {
Map<SubPlan.Input, ResolvedInputInfo> results = new LinkedHashMap<>();
for (SubPlan.Input port : vertex.getOrigin().getInputs()) {
InputSpec spec = InputSpec.get(port);
InputType type = spec.getInputType();
if (type == InputType.EXTRACT) {
ResolvedInputInfo info = new ResolvedInputInfo(
spec.getId(),
new ResolvedEdgeInfo(
descriptors.newOneToOneEdge(spec.getDataType()),
ResolvedEdgeInfo.Movement.ONE_TO_ONE,
spec.getDataType(),
null));
results.put(port, info);
} else if (type == InputType.BROADCAST) {
ResolvedInputInfo info = new ResolvedInputInfo(
spec.getId(),
new ResolvedEdgeInfo(
descriptors.newBroadcastEdge(spec.getDataType()),
ResolvedEdgeInfo.Movement.BROADCAST,
spec.getDataType(),
null));
results.put(port, info);
} else if (type == InputType.CO_GROUP) {
ClassDescription mapperType = null;
ClassDescription copierType = null;
ClassDescription combinerType = null;
Operator operator = Invariants.requireNonNull(vertex.getPrimaryOperator());
VertexElement element = Invariants.requireNonNull(resolved.get(operator));
if (element instanceof AggregateNode) {
AggregateNode aggregate = (AggregateNode) element;
mapperType = aggregate.getMapperType();
copierType = aggregate.getCopierType();
combinerType = aggregate.getCombinerType();
}
ResolvedInputInfo info = new ResolvedInputInfo(
spec.getId(),
new ResolvedEdgeInfo(
descriptors.newScatterGatherEdge(spec.getDataType(), spec.getPartitionInfo()),
combinerType == null
? ResolvedEdgeInfo.Movement.SCATTER_GATHER
: ResolvedEdgeInfo.Movement.AGGREGATE,
spec.getDataType(),
spec.getPartitionInfo()),
mapperType, copierType, combinerType);
results.put(port, info);
}
}
return results;
}
private Map<SubPlan.Output, ResolvedOutputInfo> collectOutputs(VertexSpec vertex) {
Map<SubPlan.Output, ResolvedOutputInfo> results = new LinkedHashMap<>();
for (SubPlan.Output port : vertex.getOrigin().getOutputs()) {
OutputSpec spec = OutputSpec.get(port);
if (spec.getOutputType() == OutputType.DISCARD) {
continue;
}
Set<ResolvedInputInfo> downstreams = port.getOpposites().stream()
.map(p -> Invariants.requireNonNull(builder.get(p)))
.collect(Collectors.toSet());
String tag = getPortTag(port);
ResolvedOutputInfo info = new ResolvedOutputInfo(spec.getId(), tag, downstreams);
results.put(port, info);
}
return results;
}
private void resolveOutputs() {
externalPortDriver.processOutputs(builder);
Map<ExternalOutput, VertexSpec> generic = collectOperators(plan, ExternalOutput.class).stream()
.filter(port -> externalPortDriver.accepts(port) == false)
.collect(Collectors.collectingAndThen(
Collectors.toList(),
operators -> collectOwners(plan, operators)));
for (Map.Entry<ExternalOutput, VertexSpec> entry : generic.entrySet()) {
ExternalOutput port = entry.getKey();
VertexSpec vertex = entry.getValue();
resolveGenericOutput(vertex, port);
}
}
private void resolveGenericOutput(VertexSpec vertex, ExternalOutput port) {
LOG.debug("resolving generic output vertex: {} ({})", vertex.getId(), vertex.getLabel()); //$NON-NLS-1$
if (isEmptyOutput(vertex)) {
processorContext.addExternalOutput(port.getName(), port.getInfo(), Collections.emptyList());
} else {
CompilerOptions options = processorContext.getOptions();
String path = options.getRuntimeWorkingPath(String.format("%s/part-*", port.getName())); //$NON-NLS-1$
processorContext.addExternalOutput(port.getName(), port.getInfo(), Collections.singletonList(path));
registerInternalOutput(generatorContext, descriptors, builder, vertex, port, path);
}
}
private void resolvePlan() {
externalPortDriver.processPlan(builder);
}
private ClassDescription generate(
VertexSpec vertex, String name, Function<ClassDescription, ClassData> generator) {
return DataFlowUtil.generate(generatorContext, vertex, name, generator);
}
private void savePlanInfo() {
try {
Node root = new Node();
Map<ResolvedInputInfo, Input> inputs = new HashMap<>();
Map<ResolvedOutputInfo, Output> outputs = new HashMap<>();
for (ResolvedVertexInfo vertex : builder.getVertices()) {
Node node = root.newElement();
buildPlanVertex(vertex, node, inputs, outputs);
}
outputs.forEach((upstream, output) -> {
upstream.getDownstreams().forEach(downstream -> {
Input input = inputs.get(downstream);
output.connect(input);
});
});
PlanAttributeStore.save(processorContext, new PlanAttribute(root));
} catch (RuntimeException e) {
LOG.warn("error occurred while saving execution plan", e);
}
}
private static void buildPlanVertex(
ResolvedVertexInfo vertex,
Node node,
Map<ResolvedInputInfo, Input> inputs,
Map<ResolvedOutputInfo, Output> outputs) {
node.withAttribute(new OperatorAttribute(PlanVertexSpec.of(
vertex.getId(),
vertex.getLabel(),
vertex.getImplicitDependencies().stream()
.map(ResolvedVertexInfo::getId)
.collect(Collectors.toList()))));
vertex.getInputs().forEach((s, r) -> inputs.put(r, node.newInput().withAttribute(new InputAttribute(
r.getId(),
OperatorGraphConverter.convert(s.getOperator().getDataType()),
null, null))));
vertex.getOutputs().forEach((s, r) -> outputs.put(r, node.newOutput().withAttribute(new OutputAttribute(
r.getId(),
OperatorGraphConverter.convert(s.getOperator().getDataType())))));
List<SubPlan> candidates = Stream.concat(
vertex.getInputs().keySet().stream(),
vertex.getOutputs().keySet().stream())
.map(SubPlan.Port::getOwner)
.distinct()
.collect(Collectors.toList());
if (candidates.size() == 1) {
SubPlan sub = candidates.get(0);
OperatorGraphConverter converter = buildConverter(vertex, sub);
OperatorGraph graph = new OperatorGraph(sub.getOperators());
converter.process(graph, node);
}
}
private static OperatorGraphConverter buildConverter(ResolvedVertexInfo vertex, SubPlan sub) {
Map<MarkerOperator, OperatorSpec> mapper = new HashMap<>();
vertex.getInputs().forEach((s, r) -> mapper.put(s.getOperator(), PlanInputSpec.of(
r.getId(),
translate(r.getEdgeInfo().getMovement()),
OperatorGraphConverter.convert(r.getEdgeInfo().getGroup()))));
vertex.getOutputs().forEach((s, r) -> mapper.put(s.getOperator(), r.getDownstreams().stream()
.map(ResolvedInputInfo::getEdgeInfo)
.map(edge -> PlanOutputSpec.of(
r.getId(),
translate(edge.getMovement()),
OperatorGraphConverter.convert(edge.getGroup()),
computeAggregation(s, edge)))
.findFirst()
.orElseGet(() -> PlanOutputSpec.of(r.getId(), DataExchange.UNKNOWN, null))));
sub.getInputs().stream()
.filter(it -> vertex.getInputs().containsKey(it) == false)
.map(InputSpec::get)
.forEach(spec -> mapper.put(spec.getOrigin().getOperator(), PlanInputSpec.of(
spec.getId(),
spec.getInputType() == InputType.NO_DATA ? DataExchange.NOTHING : DataExchange.UNKNOWN,
null)));
sub.getOutputs().stream()
.filter(it -> vertex.getOutputs().containsKey(it) == false)
.map(OutputSpec::get)
.forEach(spec -> mapper.put(spec.getOrigin().getOperator(), PlanOutputSpec.of(
spec.getId(),
spec.getOutputType() == OutputType.DISCARD ? DataExchange.NOTHING : DataExchange.UNKNOWN,
null)));
OperatorGraphConverter converter = new OperatorGraphConverter(mapper::get);
return converter;
}
private static DataExchange translate(ResolvedEdgeInfo.Movement movement) {
switch (movement) {
case NOTHING:
return DataExchange.NOTHING;
case ONE_TO_ONE:
return DataExchange.MOVE;
case BROADCAST:
return DataExchange.BROADCAST;
case SCATTER_GATHER:
return DataExchange.SCATTER_GATHER;
case AGGREGATE:
return DataExchange.AGGREGATE;
default:
return DataExchange.UNKNOWN;
}
}
private static List<String> computeAggregation(SubPlan.Output output, ResolvedEdgeInfo edge) {
if (edge.getMovement() != Movement.AGGREGATE) {
return Collections.emptyList();
}
return Optional.ofNullable(OutputSpec.get(output).getAggregationInfo())
.filter(it -> it instanceof UserOperator)
.map(it -> (UserOperator) it)
.map(o -> Arrays.asList(
o.getMethod().getDeclaringClass().getSimpleName(),
o.getMethod().getName()))
.orElse(Collections.emptyList());
}
}
| apache-2.0 |
mifos/1.4.x | application/src/test/java/org/mifos/application/accounts/financial/business/FinancialBOIntegrationTest.java | 3166 | /*
* Copyright (c) 2005-2009 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.application.accounts.financial.business;
import java.util.Iterator;
import java.util.Set;
import junit.framework.Assert;
import org.mifos.application.accounts.financial.exceptions.FinancialException;
import org.mifos.application.accounts.financial.util.helpers.FinancialActionCache;
import org.mifos.application.accounts.financial.util.helpers.FinancialActionConstants;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.util.helpers.TestConstants;
public class FinancialBOIntegrationTest extends MifosIntegrationTestCase {
public FinancialBOIntegrationTest() throws SystemException, ApplicationException {
super();
}
public void testGetApplicableDebit() throws FinancialException {
FinancialActionBO finActionPrincipal = FinancialActionCache
.getFinancialAction(FinancialActionConstants.PRINCIPALPOSTING);
Set<COABO> applicableDebitCategory = finActionPrincipal.getApplicableDebitCharts();
Assert.assertEquals(applicableDebitCategory.size(), 1);
Iterator<COABO> iterSubCategory = applicableDebitCategory.iterator();
while (iterSubCategory.hasNext()) {
COABO subCategoryCOA = iterSubCategory.next();
Assert.assertEquals("Bank Account 1", subCategoryCOA.getAccountName());
}
}
public void testGetApplicableCredit() throws FinancialException {
FinancialActionBO finActionPrincipal = FinancialActionCache
.getFinancialAction(FinancialActionConstants.PRINCIPALPOSTING);
Set<COABO> applicableCreditCategory = finActionPrincipal.getApplicableCreditCharts();
Assert.assertEquals(TestConstants.FINANCIAL_PRINCIPALPOSTING_SIZE, applicableCreditCategory.size());
}
public void testRoundingCredit() throws FinancialException {
FinancialActionBO finActionRounding = FinancialActionCache
.getFinancialAction(FinancialActionConstants.ROUNDING);
Set<COABO> applicableCreditCategory = finActionRounding.getApplicableCreditCharts();
Assert.assertEquals(applicableCreditCategory.size(), 1);
for (COABO coa : applicableCreditCategory) {
Assert.assertEquals("Income from 999 Account", coa.getAccountName());
}
}
}
| apache-2.0 |
ggupta2005/Programming-and-Algorithm-Questions | nearest_sqrt_of_number/nearest_sqrt_of_number.java | 4618 | /*
* This porgram is based of the post :-
* http://www.geeksforgeeks.org/square-root-of-an-integer/
*/
import java.io.*;
public class nearest_sqrt_of_number
{
/*
* Constant to capture the return value in case
* user attempts to find the square root of a
* negative number.
*/
public static final long ILLEGAL = -1;
/*
* The time complexity of finding the square root
* of a positive number using this function is
* O(sqrt(n)). In this function we linearly increase
* the value of intended square root unless the
* value of square of square root exceeds the number.
* If a negative value is passed to this function, then
* this function will return 'ILLEGAL' value.
*/
public static long sqrt_v1 (long num)
{
long sqrt;
/*
* If num is less than zero, then return an
* illegal value
*/
if (num < 0) {
return(ILLEGAL);
}
/*
* If the number is zero, then return zero
*/
if (num == 0) {
return(0);
}
/*
* Start with square as 1 and increment unless
* square of the square root exceeds the number
* itself.
*/
sqrt = 1;
while ((sqrt * sqrt) <= num) {
++sqrt;
}
/*
* If the square of the square root is greater than
* the number, return one less than the square root.
*/
if ((sqrt * sqrt) > num) {
return(sqrt - 1);
}
return(sqrt);
}
/*
* The time complexity of finding the square root
* of a positive number using this function is
* O(log(n)). This uses binary search to find the
* square root of the number. If a negative value is
* passed to this function, then this function will
* return 'ILLEGAL' value.
*/
public static long sqrt_v2 (long num)
{
long sqrt, low, high;
long square;
/*
* If num is less than zero, then return an
* illegal value
*/
if (num < 0) {
return(ILLEGAL);
}
/*
* If the number is zero, then return zero
*/
if (num == 0) {
return(0);
}
/*
* Initialize 'low' at one and 'high' at
* num
*/
low = 1;
high = num;
/*
* Continue the while loop as long as low is
* less than or equal to high
*/
while (low <= high) {
/*
* The intended square root lies at the
* mid point value of low and high.
*/
sqrt = (low + high)/2;
/*
* Compute the square of the square root
*/
square = sqrt * sqrt;
/*
* If the square of the square is:-
* 1. Equal to the number, then we have found
* the square root so break from the while
* loop.
* 2. Greater than the number, then square
* root lies between 'low' and 'sqrt - 1'
* 3. Less than the number, then the square
* root lies between 'sqrt + 1' and 'high'
*/
if (square == num) {
break;
} else if (square > num) {
high = sqrt - 1;
} else {
low = sqrt + 1;
}
}
/*
* Return the converged value of square root,
* which is the average of 'low' and 'high'
*/
sqrt = (low + high)/2;
return(sqrt);
}
public static void main(String[] args)
{
/*
* Test cases for finding the square root,
* the first approach.
*/
assert(0 == sqrt_v1(0));
assert(ILLEGAL == sqrt_v1(-1));
assert(ILLEGAL == sqrt_v1(-32));
assert(1 == sqrt_v1(1));
assert(2 == sqrt_v1(5));
assert(3 == sqrt_v1(9));
assert(3 == sqrt_v1(11));
assert(32 == sqrt_v1(1025));
assert(11 == sqrt_v1(121));
/*
* Test cases for finding the square root,
* the second approach.
*/
assert(0 == sqrt_v2(0));
assert(ILLEGAL == sqrt_v1(-1));
assert(ILLEGAL == sqrt_v1(-32));
assert(1 == sqrt_v2(1));
assert(2 == sqrt_v2(5));
assert(3 == sqrt_v2(9));
assert(3 == sqrt_v2(11));
assert(32 == sqrt_v2(1025));
assert(11 == sqrt_v2(121));
}
}
| apache-2.0 |
openpreserve/scape-simulator | simulation-engine/src/main/java/eu/scape_project/pw/simulator/engine/model/IEvent.java | 310 | package eu.scape_project.pw.simulator.engine.model;
import eu.scape_project.pw.simulator.engine.model.state.ISimulationState;
public interface IEvent extends Comparable<IEvent> {
boolean execute(ISimulationState state);
long getScheduleTime();
void setScheduleTime(long time);
String getName();
}
| apache-2.0 |
CrocusJava/battleofrotterdam | back/battleWEB/src/com/battleweb/controller/commands/CommandViewPhotoComments.java | 2486 | package com.battleweb.controller.commands;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ejb.Stateless;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import com.battleejb.ejbbeans.CommentBean;
import com.battleejb.entities.Comment;
import com.battleejb.entities.User;
import com.battleweb.controller.Constants;
import com.battleweb.tools.ToolJSON;
/**
* @author Lukashchuk Ivan
*
*/
@Stateless
@LocalBean
public class CommandViewPhotoComments implements Command {
@EJB
private ToolJSON toolJSON;
@EJB
private CommentBean commentBean;
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd MMMM yyyy HH:mm", Locale.ENGLISH);
JsonObject jsonObjectRequest = toolJSON.getJsonObjectRequest(request);
int photoId = jsonObjectRequest.getInt(Constants.PARAMETER_PHOTO_ID);
int firstPosition = jsonObjectRequest
.getInt(Constants.PARAMETER_FIRST_POSITION);
int size = jsonObjectRequest.getInt(Constants.PARAMETER_SIZE);
List<Comment> comments = commentBean.findLimitByPhotoId(photoId,
firstPosition, size);
JsonArrayBuilder jsonPhotos = Json.createArrayBuilder();
for (Comment comment : comments) {
User user = comment.getUser();
if (user.getCommentAble() && user.getActive()) {
JsonObject jsonUser = Json
.createObjectBuilder()
.add(Constants.PARAMETER_ID, user.getId())
.add(Constants.PARAMETER_LOGIN, user.getLogin())
.add(Constants.PARAMETER_AVATAR_PATH,
user.getPhotoPath()).build();
JsonObject jsonPhoto = Json
.createObjectBuilder()
.add(Constants.PARAMETER_ID, comment.getId())
.add(Constants.PARAMETER_TEXT, comment.getCommentText())
.add(Constants.PARAMETER_DATE,
dateFormat.format(comment.getCommentDate()))
.add(Constants.PARAMETER_USER, jsonUser).build();
jsonPhotos.add(jsonPhoto);
}
}
JsonObject jsonObjectResponse = Json.createObjectBuilder()
.add(Constants.PARAMETER_COMMENTS, jsonPhotos.build()).build();
toolJSON.setJsonObjectResponse(response, jsonObjectResponse);
return null;
}
}
| apache-2.0 |
cement/AndroidWebServer | TinyHttpServer/src/com/coment/simple/SimpleTest.java | 580 | package com.coment.simple;
import java.io.IOException;
import com.cement.constants.Settings.MODE;
import com.cement.server.EmbedHttpServer;
public class SimpleTest {
public static void main(String[] args) throws IOException {
EmbedHttpServer server = new EmbedHttpServer(9999);
// server.addHandler(new PostSessionHandler("POST"));
// server.addHandler(new GetSessionHandler2("GET"));
server.setWebRoot("W:\\WebRoot\\static");
server.setNotFindPage("W:\\WebRoot\\static\\page404.html");
server.setVisitMode(MODE.FILE);
server.start();
}
}
| apache-2.0 |
msgilligan/bitcoinj-addons | cj-btc-services/src/main/java/org/consensusj/bitcoin/services/WalletAppKitService.java | 3449 | package org.consensusj.bitcoin.services;
import com.msgilligan.bitcoinj.json.pojo.ServerInfo;
import com.msgilligan.bitcoinj.rpcserver.BitcoinJsonRpc;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Context;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.PeerGroup;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.kits.WalletAppKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import java.math.BigDecimal;
/**
* Implement a subset of Bitcoin JSON RPC using a WalletAppKit
*/
@Named
public class WalletAppKitService implements BitcoinJsonRpc {
private static Logger log = LoggerFactory.getLogger(WalletAppKitService.class);
private static final String userAgentName = "PeerList";
private static final String appVersion = "0.1";
private static final int version = 1;
private static final int protocolVersion = 1;
private static final int walletVersion = 0;
protected NetworkParameters netParams;
protected Context context;
protected WalletAppKit kit;
private int timeOffset = 0;
private BigDecimal difficulty = new BigDecimal(0);
@Inject
public WalletAppKitService(NetworkParameters params,
Context context,
WalletAppKit kit) {
this.netParams = params;
this.context = context;
this.kit = kit;
}
@PostConstruct
public void start() {
log.info("WalletAppKitService.start()");
kit.setUserAgent(userAgentName, appVersion);
kit.setBlockingStartup(false);
kit.startAsync();
//kit.awaitRunning();
}
public NetworkParameters getNetworkParameters() {
return this.netParams;
}
public PeerGroup getPeerGroup() {
kit.awaitRunning();
return kit.peerGroup();
}
@Override
public Integer getblockcount() {
log.info("getblockcount");
if(!kit.isRunning()) {
log.warn("kit not running, returning null");
return null;
}
return kit.chain().getChainHead().getHeight();
}
@Override
public Integer getconnectioncount() {
if(!kit.isRunning()) {
return null;
}
try {
return kit.peerGroup().numConnectedPeers();
} catch (IllegalStateException ex) {
return null;
}
}
@Override
public ServerInfo getinfo() {
// Dummy up a response for now.
// Since ServerInfo is immutable, we have to build it entirely with the constructor.
Coin balance = Coin.valueOf(0);
boolean testNet = !netParams.getId().equals(NetworkParameters.ID_MAINNET);
int keyPoolOldest = 0;
int keyPoolSize = 0;
return new ServerInfo(
version,
protocolVersion,
walletVersion,
balance,
getblockcount(),
timeOffset,
getconnectioncount(),
"proxy",
difficulty,
testNet,
keyPoolOldest,
keyPoolSize,
Transaction.REFERENCE_DEFAULT_MIN_TX_FEE,
Transaction.REFERENCE_DEFAULT_MIN_TX_FEE, // relayfee
"no errors" // errors
);
}
}
| apache-2.0 |
nstdio/libpgn | core/src/main/java/com/github/nstdio/libpgn/core/GameFilter.java | 2053 | package com.github.nstdio.libpgn.core;
import com.github.nstdio.libpgn.entity.MoveText;
import com.github.nstdio.libpgn.entity.TagPair;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
public final class GameFilter {
private final Predicate<List<TagPair>> tagPairFilter;
private final Predicate<List<MoveText>> movetextFilter;
GameFilter(final Predicate<List<TagPair>> filters, final Predicate<List<MoveText>> movetextFilter) {
tagPairFilter = filters;
this.movetextFilter = movetextFilter;
}
static GameFilterBuilder builder() {
return new GameFilterBuilder();
}
public boolean test(final List<TagPair> tagPairs) {
return testImpl(tagPairFilter, Objects.requireNonNull(tagPairs));
}
public boolean testMoveText(final List<MoveText> moveTextList) {
return testImpl(movetextFilter, Objects.requireNonNull(moveTextList));
}
private <T> boolean testImpl(final Predicate<T> filters, final T input) {
return filters == null || filters.test(input);
}
static final class GameFilterBuilder {
private Predicate<List<TagPair>> tagPairFilter;
private Predicate<List<MoveText>> moveTextFilter;
GameFilterBuilder() {
}
void tagPairFilter(final Predicate<List<TagPair>> filter) {
Objects.requireNonNull(filter);
if (tagPairFilter == null) {
tagPairFilter = filter;
} else {
tagPairFilter = tagPairFilter.and(filter);
}
}
void movetextFilter(final Predicate<List<MoveText>> moveTextFilter) {
Objects.requireNonNull(moveTextFilter);
if (this.moveTextFilter == null) {
this.moveTextFilter = moveTextFilter;
} else {
this.moveTextFilter = this.moveTextFilter.and(moveTextFilter);
}
}
GameFilter build() {
return new GameFilter(tagPairFilter, moveTextFilter);
}
}
}
| apache-2.0 |
javers/javers | javers-persistence-sql/src/main/java/org/javers/repository/sql/session/Parameter.java | 5041 | package org.javers.repository.sql.session;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
import org.javers.core.json.typeadapter.util.UtilTypeCoreAdapters;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
public abstract class Parameter<T> {
/** nullable */
private final String name;
private final T value;
Parameter(String name, T value) {
this.name = name;
this.value = value;
}
abstract int injectValuesTo(PreparedStatement preparedStatement, int orderStart) throws SQLException;
public static Parameter<Long> longParam(Long value){
return new LongParameter(null, value);
}
public static Parameter<String> stringParam(String value){
return new StringParameter(null, value);
}
public static Parameter<Collection<String>> listParam(Collection<String> value){
return new ListParameter(null, value);
}
public static Parameter<BigDecimal> bigDecimalParam(BigDecimal value){
return new BigDecimalParameter(null, value);
}
public static Parameter<LocalDateTime> localDateTimeParam(LocalDateTime value){
return new LocalDateTimeParameter(null, value);
}
public static Parameter<Instant> instantParam(Instant value) {
return new InstantParameter(null, value);
}
String getName() {
return name;
}
T getValue() {
return value;
}
String getRawSqlRepresentation() {
return "?";
}
static class StringParameter extends Parameter<String> {
StringParameter(String name, String value) {
super(name, value);
}
@Override
int injectValuesTo(PreparedStatement preparedStatement, int order) throws SQLException {
preparedStatement.setString(order, getValue());
return order + 1;
}
}
static class ListParameter extends Parameter<Collection<String>> {
ListParameter(String name, Collection<String> value) {
super(name, value);
}
@Override
int injectValuesTo(PreparedStatement preparedStatement, int order) throws SQLException {
int k = order;
for (String val : getValue()) {
preparedStatement.setString(k++, val);
}
return k;
}
}
static class LongParameter extends Parameter<Long> {
LongParameter(String name, Long value) {
super(name, value);
}
@Override
int injectValuesTo(PreparedStatement preparedStatement, int order) throws SQLException {
preparedStatement.setLong(order, getValue());
return order + 1;
}
}
static class InlinedParameter extends Parameter<String> {
InlinedParameter(String name, String inlinedExpression) {
super(name, inlinedExpression);
}
@Override
int injectValuesTo(PreparedStatement preparedStatement, int order) throws SQLException {
return order;
}
@Override
String getRawSqlRepresentation() {
return getValue();
}
}
static class IntParameter extends Parameter<Integer> {
IntParameter(String name, Integer value) {
super(name, value);
}
@Override
int injectValuesTo(PreparedStatement preparedStatement, int order) throws SQLException {
preparedStatement.setInt(order, getValue());
return order + 1;
}
}
static class BigDecimalParameter extends Parameter<BigDecimal> {
BigDecimalParameter(String name, BigDecimal value) {
super(name, value);
}
@Override
int injectValuesTo(PreparedStatement preparedStatement, int order) throws SQLException {
preparedStatement.setBigDecimal(order, getValue());
return order + 1;
}
}
static class LocalDateTimeParameter extends Parameter<LocalDateTime> {
LocalDateTimeParameter(String name, LocalDateTime value) {
super(name, value);
}
@Override
int injectValuesTo(PreparedStatement preparedStatement, int order) throws SQLException {
preparedStatement.setTimestamp(order, toTimestamp(getValue()));
return order + 1;
}
private Timestamp toTimestamp(LocalDateTime value) {
return new Timestamp(UtilTypeCoreAdapters.toUtilDate(value).getTime());
}
}
static class InstantParameter extends Parameter<Instant> {
InstantParameter(String name, Instant value) {
super(name, value);
}
@Override
int injectValuesTo(PreparedStatement preparedStatement, int order) throws SQLException {
preparedStatement.setString(order, getValue().toString());
return order + 1;
}
}
}
| apache-2.0 |
cgruber/guice | core/src/com/google/inject/internal/UntargettedBindingImpl.java | 2669 | /*
* Copyright (C) 2007 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.inject.internal;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.spi.BindingTargetVisitor;
import com.google.inject.spi.Dependency;
import com.google.inject.spi.UntargettedBinding;
final class UntargettedBindingImpl<T> extends BindingImpl<T> implements UntargettedBinding<T> {
UntargettedBindingImpl(InjectorImpl injector, Key<T> key, Object source) {
super(
injector,
key,
source,
new InternalFactory<T>() {
@Override
public T get(
Errors errors, InternalContext context, Dependency<?> dependency, boolean linked) {
throw new AssertionError();
}
},
Scoping.UNSCOPED);
}
public UntargettedBindingImpl(Object source, Key<T> key, Scoping scoping) {
super(source, key, scoping);
}
@Override
public <V> V acceptTargetVisitor(BindingTargetVisitor<? super T, V> visitor) {
return visitor.visit(this);
}
@Override
public BindingImpl<T> withScoping(Scoping scoping) {
return new UntargettedBindingImpl<T>(getSource(), getKey(), scoping);
}
@Override
public BindingImpl<T> withKey(Key<T> key) {
return new UntargettedBindingImpl<T>(getSource(), key, getScoping());
}
@Override
public void applyTo(Binder binder) {
getScoping().applyTo(binder.withSource(getSource()).bind(getKey()));
}
@Override
public String toString() {
return MoreObjects.toStringHelper(UntargettedBinding.class)
.add("key", getKey())
.add("source", getSource())
.toString();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof UntargettedBindingImpl) {
UntargettedBindingImpl<?> o = (UntargettedBindingImpl<?>) obj;
return getKey().equals(o.getKey()) && getScoping().equals(o.getScoping());
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hashCode(getKey(), getScoping());
}
}
| apache-2.0 |
Poorva17/twu_biblioteca-poorva | src/com/twu/biblioteca/view/View.java | 2204 | package com.twu.biblioteca.view;
import com.twu.biblioteca.model.Item;
import com.twu.biblioteca.model.User;
import java.util.ArrayList;
import java.util.HashMap;
public class View {
public void printMessage(String message) {
System.out.print(message);
}
public void printListOfBooks(ArrayList<Item> itemList) {
for (Item item : itemList) {
System.out.print(item.getDetails());
}
}
public void printBookCheckoutStatus(Item checkoutReturnBook) {
if (checkoutReturnBook.hasTitle(""))
System.out.print("That book is not available.\n");
else
System.out.print("Thank you! Enjoy the book\n");
}
public void printBookCheckinStatus(Item checkinReturnBook) {
if (checkinReturnBook.hasTitle(""))
System.out.print("That is not a valid book to return.\n");
else
System.out.print("Thank you for returning the book.\n");
}
public void printListOfMovies(ArrayList<Item> moviesList) {
for (Item movie : moviesList) {
System.out.print(movie.getDetails());
}
}
public void printMovieCheckoutStatus(Item checkoutReturnMovie) {
if (checkoutReturnMovie.hasTitle(""))
System.out.print("That movie is not available.\n");
else
System.out.print("Thank you! Enjoy the movie\n");
}
public void printMovieCheckinStatus(Item checkinReturnMovie) {
if (checkinReturnMovie.hasTitle(""))
System.out.print("That is not a valid movie to return.\n");
else
System.out.print("Thank you for returning the movie.\n");
}
public void printHashMapMovie(HashMap<Item, User> movieCheckoutList) {
for (Item movie: movieCheckoutList.keySet()) {
printMessage(movieCheckoutList.get(movie).getInformation());
printMessage(movie.getDetails());
}
}
public void printHashMapBook(HashMap<Item, User> bookCheckoutList) {
for (Item book: bookCheckoutList.keySet()) {
printMessage(bookCheckoutList.get(book).getInformation());
printMessage(book.getDetails());
}
}
}
| apache-2.0 |
valikir/vturbin | chapter_004/src/main/java/ru/iterators/Converter.java | 873 | package ru.iterators;
import java.util.*;
public class Converter {
private Integer Value;
Iterator<Integer> convert(Iterator<Iterator<Integer>> it) {
return new Iterator<Integer> () {
Iterator<Integer> n = it.next();
Integer cursor;
@Override
public boolean hasNext() {
return n.hasNext() || it.hasNext();
}
@Override
public Integer next() {
if (!hasNext()){
throw new NoSuchElementException();
}
if (n.hasNext()) {
cursor = n.next();
}
else{
n = it.next();
cursor = n.next();
}
Value = cursor;
return Value;
}
};
}
} | apache-2.0 |
fuhongliang/SFY | Shoufuyi/app/src/main/java/com/cchtw/sfy/uitls/ActivityCollector.java | 955 | package com.cchtw.sfy.uitls;
import android.app.Activity;
import java.util.ArrayList;
import java.util.List;
/**
* MiGo
* Description:
* Created by FuHL on
* Date:2016-01-14
* Time:下午3:18
* Copyright © 2016年 FuHL. All rights reserved.
* blog:http://fuhongliang.com/
*/
public class ActivityCollector {
public static List<Activity> activities = new ArrayList<Activity>();
public static void addActivity(Activity activity)
{
activities.add(activity);
}
public static void removeActivity(Activity activity) {
activities.remove(activity);
}
public static void finishAll() {
List delList = new ArrayList();//用来装需要删除的元素
for(Activity activity:activities)
if(!activity.isFinishing()){
delList.add(activity);
activity.finish();
}
activities.removeAll(delList);//遍历完成后执行删除
}
}
| apache-2.0 |
utgenome/utgb | utgb-core/src/main/java/org/utgenome/gwt/utgb/client/track/lib/old/OldUTGBProperty.java | 2291 | /*--------------------------------------------------------------------------
* Copyright 2007 utgenome.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
//--------------------------------------
// GenomeBrowser Project
//
// OldUTGBProperty.java
// Since: 2007/06/19
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.gwt.utgb.client.track.lib.old;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* @author ssksn
*/
public final class OldUTGBProperty {
/**
* Uncallable constructor.
*
* @throws AssertionError
* if this constructor is called.
*/
private OldUTGBProperty() {
throw new AssertionError();
}
public static final String SPECIES = "species";
public static final String REVISION = "revision";
public static final String TARGET = "target";
private static final String[] propertyNameArray = { SPECIES, REVISION, TARGET };
private static final Set<String> propertyNameSet = new HashSet<String>();
private static final List<String> propertyNameList = new ArrayList<String>();
static {
{
propertyNameSet.add(SPECIES);
propertyNameSet.add(REVISION);
propertyNameSet.add(TARGET);
}
{
propertyNameList.add(SPECIES);
propertyNameList.add(REVISION);
propertyNameList.add(TARGET);
}
}
public static final String[] getPropertyNameArray() {
return propertyNameArray;
}
public static final Set<String> getPropertyNameSet() {
return propertyNameSet;
}
public static final List<String> getPropertyNameList() {
return propertyNameList;
}
}
| apache-2.0 |
zoozooll/MyExercise | DuoDuoDataSource1.2/src/com/dcfs/esb/client/converter/StandardConverter.java | 4468 | package com.dcfs.esb.client.converter;
import java.io.StringReader;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import com.dc.eai.config.IOConfig;
import com.dc.eai.conv.InputPacket;
import com.dc.eai.conv.OutputPacket;
import com.dc.eai.conv.PackageConverter;
import com.dc.eai.data.CompositeData;
import com.dcfs.esb.client.config.Config;
/**
*
* 鏍囧噯鎷嗗寘缁勫寘妯″紡
*
* @author ex-wanghuaxi
*
* 2008-10-08
*/
public class StandardConverter implements PackageConverter
{
private static Log log = LogFactory.getLog(StandardConverter.class);
public static final String ROOT = "service";
public static final String SYS_HEAD = "SYS_HEAD";
public static final String sys_header = "sys-header";
public static final String BODY = "BODY";
public static final String body = "body";
public static final String DATA = "data";
public static final String FIELD = "field";
public static final String ARRAY = "array";
public static final String STRUCT = "struct";
private static boolean xmlOptimize = false;
private static boolean spaceTrim = false;
private static SAXParserFactory factory = null;
private static StandardCdToXml cdToXml = null;
static
{
try
{
init();
} catch (Exception e)
{
log.error("鎷嗙粍鍖呭垵濮嬪寲鍑洪敊", e);
}
}
/**
* 鍔熻兘 :鏍囧噯鎷嗙粍鍖呭垵濮嬪寲
*/
public static void init()
{
if(log.isInfoEnabled())
log.info("鏍囧噯鎷嗙粍鍖呭垵濮嬪寲寮�");
factory = SAXParserFactory.newInstance();
factory.setValidating(false);
cdToXml = new StandardCdToXml();
setConvertFlag();
if(log.isInfoEnabled())
log.info("鏍囧噯鎷嗙粍鍖呭垵濮嬪寲鎴愬姛");
}
/**
* 鍔熻兘 :妫�煡鎷嗙粍鍖呯浉鍏崇殑閰嶇疆淇℃伅
*/
private static void setConvertFlag()
{
String xmlFlag = Config.getLogProperty(Config.XML_OPTIMIZE_FLAG);
String trimFlag = Config.getLogProperty(Config.SPACE_TRIM_FLAG);
if (trimFlag != null)
StandardConverter.setSpaceTrim("true".equalsIgnoreCase(trimFlag));
if (xmlFlag != null)
StandardConverter.setXmlOptimize("true".equalsIgnoreCase(xmlFlag));
if (log.isInfoEnabled())
log.info(new StringBuffer("spaceTrim=").append(spaceTrim).append(
",setXmlOptimize=").append(xmlOptimize));
}
/**
* 鍔熻兘: 缁勫寘
*/
public void pack(OutputPacket packet, CompositeData data, IOConfig iocfg)
{
// 鎵ц缁勫寘
String xmlStr;
byte[] xmlData = null;
try
{
xmlStr = cdToXml.convert(data);
xmlData = xmlStr.getBytes("UTF-8");
int length = xmlData.length;
packet.ensure(length);
System.arraycopy(xmlData, 0, packet.getBuff(), packet.getOffset(),
length);
packet.advance(length);
} catch (Exception e)
{
// log.error("缁勫寘鍑洪敊锛� + e, e);
}
}
public String packXmlStr(CompositeData data)
{
String xmlStr = null;
try
{
xmlStr = cdToXml.convert(data);
} catch (Exception e)
{
// log.error("缁勫寘鍑洪敊锛� + e, e);
}
return xmlStr;
}
/**
* 鍔熻兘锛氭媶鍖�
*/
public void unpack(InputPacket packet, CompositeData data, IOConfig iocfg)
{
XMLReader parser = null;
try
{
parser = factory.newSAXParser().getXMLReader();
StandardContentHandler handler = new StandardContentHandler(data);
parser.setContentHandler(handler);
String inString = new String(packet.getBuff(), "UTF-8").trim();
parser.parse(new InputSource(new StringReader(inString)));
} catch (Exception e)
{
// log.error("鎷嗗寘鍑洪敊锛� + e, e);
}
}
public void unpackXmlStr(String xmlStr, CompositeData data)
{
XMLReader parser = null;
try
{
parser = factory.newSAXParser().getXMLReader();
StandardContentHandler handler = new StandardContentHandler(data);
parser.setContentHandler(handler);
parser.parse(new InputSource(new StringReader(xmlStr)));
} catch (Exception e)
{
// log.error("鎷嗗寘鍑洪敊锛� + e, e);
}
}
public static boolean isXmlOptimize()
{
return xmlOptimize;
}
public static void setXmlOptimize(boolean xmlOptimize)
{
StandardConverter.xmlOptimize = xmlOptimize;
}
public static boolean isSpaceTrim()
{
return spaceTrim;
}
public static void setSpaceTrim(boolean spaceTrim)
{
StandardConverter.spaceTrim = spaceTrim;
}
} | apache-2.0 |
ivankishko/ikishko | travel/traveltask/src/main/java/eng/epam/util/BeachTripFactory.java | 135 | package eng.epam.util;
import eng.epam.bin.BeachTrip;
public class BeachTripFactory {
public BeachTrip getBeachTrip() {
}
}
| apache-2.0 |
chrishumphreys/provocateur | provocateur-thirdparty/src/main/java/org/targettest/org/apache/lucene/index/AbstractAllTermDocs.java | 2435 | /**
* 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.targettest.org.apache.lucene.index;
import java.io.IOException;
/** Base class for enumerating all but deleted docs.
*
* <p>NOTE: this class is meant only to be used internally
* by Lucene; it's only public so it can be shared across
* packages. This means the API is freely subject to
* change, and, the class could be removed entirely, in any
* Lucene release. Use directly at your own risk! */
public abstract class AbstractAllTermDocs implements TermDocs {
protected int maxDoc;
protected int doc = -1;
protected AbstractAllTermDocs(int maxDoc) {
this.maxDoc = maxDoc;
}
public void seek(Term term) throws IOException {
if (term==null) {
doc = -1;
} else {
throw new UnsupportedOperationException();
}
}
public void seek(TermEnum termEnum) throws IOException {
throw new UnsupportedOperationException();
}
public int doc() {
return doc;
}
public int freq() {
return 1;
}
public boolean next() throws IOException {
return skipTo(doc+1);
}
public int read(int[] docs, int[] freqs) throws IOException {
final int length = docs.length;
int i = 0;
while (i < length && doc < maxDoc) {
if (!isDeleted(doc)) {
docs[i] = doc;
freqs[i] = 1;
++i;
}
doc++;
}
return i;
}
public boolean skipTo(int target) throws IOException {
doc = target;
while (doc < maxDoc) {
if (!isDeleted(doc)) {
return true;
}
doc++;
}
return false;
}
public void close() throws IOException {
}
public abstract boolean isDeleted(int doc);
} | apache-2.0 |
method76/android-MarvelApp | volley/src/test/java/com/android/volley/toolbox/PoolingByteArrayOutputStreamTest.java | 2543 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.volley.toolbox;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import static org.junit.Assert.*;
public class PoolingByteArrayOutputStreamTest {
@Test public void pooledOneBuffer() throws IOException {
ByteArrayPool pool = new ByteArrayPool(32768);
writeOneBuffer(pool);
writeOneBuffer(pool);
writeOneBuffer(pool);
}
@Test public void pooledIndividualWrites() throws IOException {
ByteArrayPool pool = new ByteArrayPool(32768);
writeBytesIndividually(pool);
writeBytesIndividually(pool);
writeBytesIndividually(pool);
}
@Test public void unpooled() throws IOException {
ByteArrayPool pool = new ByteArrayPool(0);
writeOneBuffer(pool);
writeOneBuffer(pool);
writeOneBuffer(pool);
}
@Test public void unpooledIndividualWrites() throws IOException {
ByteArrayPool pool = new ByteArrayPool(0);
writeBytesIndividually(pool);
writeBytesIndividually(pool);
writeBytesIndividually(pool);
}
private void writeOneBuffer(ByteArrayPool pool) throws IOException {
byte[] data = new byte[16384];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) (i & 0xff);
}
PoolingByteArrayOutputStream os = new PoolingByteArrayOutputStream(pool);
os.write(data);
assertTrue(Arrays.equals(data, os.toByteArray()));
}
private void writeBytesIndividually(ByteArrayPool pool) {
byte[] data = new byte[16384];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) (i & 0xff);
}
PoolingByteArrayOutputStream os = new PoolingByteArrayOutputStream(pool);
for (int i = 0; i < data.length; i++) {
os.write(data[i]);
}
assertTrue(Arrays.equals(data, os.toByteArray()));
}
}
| apache-2.0 |
danc86/jena-core | src-examples/jena/examples/ontology/classHierarchy/ClassHierarchy.java | 5915 | /*
* 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
///////////////
package jena.examples.ontology.classHierarchy;
// Imports
///////////////
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.shared.PrefixMapping;
import com.hp.hpl.jena.util.iterator.Filter;
import java.io.PrintStream;
import java.util.*;
/**
* <p>
* Simple demonstration program to show how to list a hierarchy of classes. This
* is not a complete solution to the problem (sub-classes of restrictions, for example,
* are not shown). It is intended only to be illustrative of the general approach.
* </p>
*
* @author Ian Dickinson, HP Labs
* (<a href="mailto:ian_dickinson@users.sourceforge.net" >email</a>)
* @version CVS $Id: ClassHierarchy.java,v 1.5 2009-10-06 13:04:43 ian_dickinson Exp $
*/
public class ClassHierarchy {
// Constants
//////////////////////////////////
// Static variables
//////////////////////////////////
// Instance variables
//////////////////////////////////
protected OntModel m_model;
private Map<AnonId,String> m_anonIDs = new HashMap<AnonId, String>();
private int m_anonCount = 0;
// Constructors
//////////////////////////////////
// External signature methods
//////////////////////////////////
/** Show the sub-class hierarchy encoded by the given model */
public void showHierarchy( PrintStream out, OntModel m ) {
// create an iterator over the root classes that are not anonymous class expressions
Iterator<OntClass> i = m.listHierarchyRootClasses()
.filterDrop( new Filter<OntClass>() {
@Override
public boolean accept( OntClass r ) {
return r.isAnon();
}} );
while (i.hasNext()) {
showClass( out, i.next(), new ArrayList<OntClass>(), 0 );
}
}
// Internal implementation methods
//////////////////////////////////
/** Present a class, then recurse down to the sub-classes.
* Use occurs check to prevent getting stuck in a loop
*/
protected void showClass( PrintStream out, OntClass cls, List<OntClass> occurs, int depth ) {
renderClassDescription( out, cls, depth );
out.println();
// recurse to the next level down
if (cls.canAs( OntClass.class ) && !occurs.contains( cls )) {
for (Iterator<OntClass> i = cls.listSubClasses( true ); i.hasNext(); ) {
OntClass sub = i.next();
// we push this expression on the occurs list before we recurse
occurs.add( cls );
showClass( out, sub, occurs, depth + 1 );
occurs.remove( cls );
}
}
}
/**
* <p>Render a description of the given class to the given output stream.</p>
* @param out A print stream to write to
* @param c The class to render
*/
public void renderClassDescription( PrintStream out, OntClass c, int depth ) {
indent( out, depth );
if (c.isRestriction()) {
renderRestriction( out, c.as( Restriction.class ) );
}
else {
if (!c.isAnon()) {
out.print( "Class " );
renderURI( out, c.getModel(), c.getURI() );
out.print( ' ' );
}
else {
renderAnonymous( out, c, "class" );
}
}
}
/**
* <p>Handle the case of rendering a restriction.</p>
* @param out The print stream to write to
* @param r The restriction to render
*/
protected void renderRestriction( PrintStream out, Restriction r ) {
if (!r.isAnon()) {
out.print( "Restriction " );
renderURI( out, r.getModel(), r.getURI() );
}
else {
renderAnonymous( out, r, "restriction" );
}
out.print( " on property " );
renderURI( out, r.getModel(), r.getOnProperty().getURI() );
}
/** Render a URI */
protected void renderURI( PrintStream out, PrefixMapping prefixes, String uri ) {
out.print( prefixes.shortForm( uri ) );
}
/** Render an anonymous class or restriction */
protected void renderAnonymous( PrintStream out, Resource anon, String name ) {
String anonID = m_anonIDs.get( anon.getId() );
if (anonID == null) {
anonID = "a-" + m_anonCount++;
m_anonIDs.put( anon.getId(), anonID );
}
out.print( "Anonymous ");
out.print( name );
out.print( " with ID " );
out.print( anonID );
}
/** Generate the indentation */
protected void indent( PrintStream out, int depth ) {
for (int i = 0; i < depth; i++) {
out.print( " " );
}
}
//==============================================================================
// Inner class definitions
//==============================================================================
}
| apache-2.0 |
kenota/dropwizard-perf-issue | src/main/java/com/test/HelloWorldApplication.java | 1901 | package com.test;
import com.test.conf.HelloWorldConfiguration;
import com.test.core.VideoJPA;
import com.test.dao.VideoHibernateDao;
import com.test.resource.VideoHibernateResource;
import io.dropwizard.Application;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.hibernate.HibernateBundle;
import io.dropwizard.jdbi.DBIFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.skife.jdbi.v2.DBI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.management.ManagementFactory;
public class HelloWorldApplication extends Application<HelloWorldConfiguration> {
private static final Logger logger = LoggerFactory.getLogger(HelloWorldApplication.class);
private final HibernateBundle<HelloWorldConfiguration> hibernate = new HibernateBundle<HelloWorldConfiguration>(VideoJPA.class) {
@Override
public DataSourceFactory getDataSourceFactory(HelloWorldConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
public static void main(String[] args) throws Exception {
new HelloWorldApplication().run(args);
}
@Override
public String getName() {
return "hello-world";
}
@Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {
bootstrap.addBundle(hibernate);
}
@Override
public void run(HelloWorldConfiguration configuration,
Environment environment) throws ClassNotFoundException {
final DBIFactory dbiFactory = new DBIFactory();
final DBI dbi = dbiFactory.build(environment, configuration.getDataSourceFactory(), "h2");
final VideoHibernateDao videoHibernateDao = new VideoHibernateDao(hibernate.getSessionFactory());
environment.jersey().register(new VideoHibernateResource(videoHibernateDao));
}
} | apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Debug/Debugger-agent-dbgeng/src/main/java/agent/dbgeng/jna/dbgeng/registers/IDebugRegisters2.java | 3235 | /* ###
* IP: GHIDRA
*
* 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 agent.dbgeng.jna.dbgeng.registers;
import com.sun.jna.WString;
import com.sun.jna.platform.win32.Guid.IID;
import com.sun.jna.platform.win32.WinDef.*;
import com.sun.jna.platform.win32.WinNT.HRESULT;
import agent.dbgeng.jna.dbgeng.DbgEngNative.DEBUG_REGISTER_DESCRIPTION;
import agent.dbgeng.jna.dbgeng.DbgEngNative.DEBUG_VALUE;
import agent.dbgeng.jna.dbgeng.UnknownWithUtils.VTableIndex;
public interface IDebugRegisters2 extends IDebugRegisters {
final IID IID_IDEBUG_REGISTERS2 = new IID("1656afa9-19c6-4e3a-97e7-5dc9160cf9c4");
enum VTIndices2 implements VTableIndex {
GET_DESCRIPTION_WIDE, //
GET_INDEX_BY_NAME_WIDE, //
GET_NUMBER_PSEUDO_REGISTERS, //
GET_PSEUDO_DESCRIPTION, //
GET_PSEUDO_DESCRIPTION_WIDE, //
GET_PSEUDO_INDEX_BY_NAME, //
GET_PSEUDO_INDEX_BY_NAME_WIDE, //
GET_PSEUDO_VALUES, //
SET_PSEUDO_VALUES, //
GET_VALUES2, //
SET_VALUES2, //
OUTPUT_REGISTERS2, //
GET_INSTRUCTION_OFFSET2, //
GET_STACK_OFFSET2, //
GET_FRAME_OFFSET2, //
;
static int start = VTableIndex.follow(VTIndices.class);
@Override
public int getIndex() {
return this.ordinal() + start;
}
}
HRESULT GetDescriptionWide(ULONG Register, char[] NameBuffer, ULONG NameBufferSize,
ULONGByReference NameSize, DEBUG_REGISTER_DESCRIPTION.ByReference Desc);
HRESULT GetIndexByNameWide(WString Name, ULONGByReference Index);
HRESULT GetNumberPseudoRegisters(ULONGByReference Number);
HRESULT GetPseudoDescription(ULONG Register, byte[] NameBuffer, ULONG NameBufferSize,
ULONGByReference NameSize, ULONGLONGByReference TypeModule, ULONGByReference TypeId);
HRESULT GetPseudoDescriptionWide(ULONG Register, char[] NameBuffer, ULONG NameBufferSize,
ULONGByReference NameSize, ULONGLONGByReference TypeModule, ULONGByReference TypeId);
HRESULT GetPseudoIndexByName(String Name, ULONGByReference Index);
HRESULT GetPseudoIndexByNameWide(WString Name, ULONGByReference Index);
HRESULT GetPseudoValues(ULONG Source, ULONG Count, ULONG[] Indices, ULONG Start,
DEBUG_VALUE[] Values);
HRESULT SetPseudoValues(ULONG Source, ULONG Count, ULONG[] Indices, ULONG Start,
DEBUG_VALUE[] Values);
HRESULT GetValues2(ULONG Source, ULONG Count, ULONG[] Indices, ULONG Start,
DEBUG_VALUE[] Values);
HRESULT SetValues2(ULONG Source, ULONG Count, ULONG[] Indices, ULONG Start,
DEBUG_VALUE[] Values);
HRESULT OutputRegisters2(ULONG OutputControl, ULONG Source, ULONG Flags);
HRESULT GetInstructionOffset2(ULONG Source, ULONGLONGByReference Offset);
HRESULT GetStackOffset2(ULONG Source, ULONGLONGByReference Offset);
HRESULT GetFrameOffset2(ULONG Source, ULONGLONGByReference Offset);
}
| apache-2.0 |
hongjun117/mpush | mpush-core/src/main/java/com/mpush/core/push/SingleUserPushTask.java | 12734 | /*
* (C) Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* ohun@live.cn (夜色)
*/
package com.mpush.core.push;
import com.mpush.api.message.Message;
import com.mpush.api.connection.Connection;
import com.mpush.api.spi.push.IPushMessage;
import com.mpush.common.message.PushMessage;
import com.mpush.common.druid.MysqlConnecter;
import com.mpush.common.qps.FlowControl;
import com.mpush.common.router.RemoteRouter;
import com.mpush.core.MPushServer;
import com.mpush.core.ack.AckTask;
import com.mpush.core.router.LocalRouter;
import com.mpush.tools.common.TimeLine;
import com.mpush.tools.log.Logs;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ScheduledExecutorService;
/**
* Created by ohun on 16/10/24.
*
* @author ohun@live.cn (夜色)
*/
public final class SingleUserPushTask implements PushTask, ChannelFutureListener {
private final FlowControl flowControl;
private final IPushMessage message;
private int messageId;
private long start;
private final TimeLine timeLine = new TimeLine();
private final MPushServer mPushServer;
public SingleUserPushTask(MPushServer mPushServer, IPushMessage message, FlowControl flowControl) {
this.mPushServer = mPushServer;
this.flowControl = flowControl;
this.message = message;
this.timeLine.begin("push-center-begin");
}
@Override
public ScheduledExecutorService getExecutor() {
return ((Message) message).getConnection().getChannel().eventLoop();
}
/**
* 处理PushClient发送过来的Push推送请求
* <p>
* 查寻路由策略,先查本地路由,本地不存在,查远程,(注意:有可能远程查到也是本机IP)
* <p>
* 正常情况本地路由应该存在,如果不存在或链接失效,有以下几种情况:
* <p>
* 1.客户端重连,并且链接到了其他机器
* 2.客户端下线,本地路由失效,远程路由还未清除
* 3.PushClient使用了本地缓存,但缓存数据已经和实际情况不一致了
* <p>
* 对于三种情况的处理方式是, 再重新查寻下远程路由:
* 1.如果发现远程路由是本机,直接删除,因为此时的路由已失效 (解决场景2)
* 2.如果用户真在另一台机器,让PushClient清理下本地缓存后,重新推送 (解决场景1,3)
* <p>
*/
@Override
public void run() {
if (checkTimeout()) return;// 超时
if (checkLocal(message)) return;// 本地连接存在
checkRemote(message);//本地连接不存在,检测远程路由
}
private boolean checkTimeout() {
if (start > 0) {
if (System.currentTimeMillis() - start > message.getTimeoutMills()) {
mPushServer.getPushCenter().getPushListener().onTimeout(message, timeLine.timeoutEnd().getTimePoints());
Logs.PUSH.info("push 超时");
Logs.PUSH.info("[SingleUserPush] push message to client timeout, timeLine={}, message={}", timeLine, message);
return true;
}
} else {
start = System.currentTimeMillis();
}
return false;
}
/**
* 检查本地路由,如果存在并且链接可用直接推送
* 否则要检查下远程路由
*
* @param message message
* @return true/false true:success
*/
private boolean checkLocal(IPushMessage message) {
String userId = message.getUserId();
int clientType = message.getClientType();
LocalRouter localRouter = mPushServer.getRouterCenter().getLocalRouterManager().lookup(userId, clientType);
//1.如果本机不存在,再查下远程,看用户是否登陆到其他机器
if (localRouter == null){
Logs.PUSH.info("如果本机不存在,再查下远程,看用户是否登陆到其他机器");
return false;
}
Connection connection = localRouter.getRouteValue();
//2.如果链接失效,先删除本地失效的路由,再查下远程路由,看用户是否登陆到其他机器
if (!connection.isConnected()) {
Logs.PUSH.info("如果链接失效,先删除本地失效的路由,再查下远程路由,看用户是否登陆到其他机器");
Logs.PUSH.warn("[SingleUserPush] find local router but conn disconnected, message={}, conn={}", message, connection);
//删除已经失效的本地路由
mPushServer.getRouterCenter().getLocalRouterManager().unRegister(userId, clientType);
return false;
}
//3.检测TCP缓冲区是否已满且写队列超过最高阀值
if (!connection.getChannel().isWritable()) {
mPushServer.getPushCenter().getPushListener().onFailure(message, timeLine.failureEnd().getTimePoints());
Logs.PUSH.info("检测TCP缓冲区是否已满且写队列超过最高阀值");
Logs.PUSH.error("[SingleUserPush] push message to client failure, tcp sender too busy, message={}, conn={}", message, connection);
return true;
}
//4. 检测qps, 是否超过流控限制,如果超过则进队列延后发送
if (flowControl.checkQps()) {
timeLine.addTimePoint("before-send");
//5.链接可用,直接下发消息到手机客户端
String pushMessageDetail = null;
try {
pushMessageDetail = new String(message.getContent(),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Logs.PUSH.info("链接可用,直接下发消息到手机客户端:"+pushMessageDetail);
// //处理截取推送内容
// String[] strArray = pushMessageDetail.split("say:");
// strArray = strArray[1].split("\\\\");
// System.out.println(strArray[0]);
PushMessage pushMessage = PushMessage.build(connection).setContent(message.getContent());
pushMessage.getPacket().addFlag(message.getFlags());
messageId = pushMessage.getSessionId();
pushMessage.send(this);
} else {//超过流控限制, 进队列延后发送
Logs.PUSH.info("超过流控限制, 进队列延后发送");
mPushServer.getPushCenter().delayTask(flowControl.getDelay(), this);
}
return true;
}
/**
* 检测远程路由,
* 如果不存在直接返回用户已经下线
* 如果是本机直接删除路由信息
* 如果是其他机器让PushClient重推
*
* @param message message
*/
private void checkRemote(IPushMessage message) {
String userId = message.getUserId();
int clientType = message.getClientType();
RemoteRouter remoteRouter = mPushServer.getRouterCenter().getRemoteRouterManager().lookup(userId, clientType);
// 1.如果远程路由信息也不存在, 说明用户此时不在线,
if (remoteRouter == null || remoteRouter.isOffline()) {
String pushMessage = null;
try {
pushMessage = new String(message.getContent(),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
MysqlConnecter mc = new MysqlConnecter();
String mobile = mc.selectOne("select mobile from m_user where device_id=\""+message.getUserId()+"\"");
Logs.PUSH.info("路由信息不存在,mobile:"+mobile+",content:"+pushMessage);
/**
* 关于推送失败的解决思路
* 1.用户设备号在数据库中不存在:舍弃
* 2.用户设备号在数据库中存在,但没有绑定过用户,直接发短信
* 3.用户设备号在数据库中存在,绑定过用户,不在线,直接发短信
* 4.用户设备号在数据库中存在,绑定过用户,在线
* 4.1走推送,在这个位置加入发短信的接口,因为这里会判断用户是否在线。
*/
mPushServer.getPushCenter().getPushListener().onOffline(message, timeLine.end("offline-end").getTimePoints());
Logs.PUSH.info("[SingleUserPush] remote router not exists user offline, message={}", message);
return;
}
//2.如果查出的远程机器是当前机器,说明路由已经失效,此时用户已下线,需要删除失效的缓存
if (remoteRouter.getRouteValue().isThisMachine(mPushServer.getGatewayServerNode().getHost(), mPushServer.getGatewayServerNode().getPort())) {
Logs.PUSH.info("路由失效");
/**
* 这块是采用分布式才会用到
*/
mPushServer.getPushCenter().getPushListener().onOffline(message, timeLine.end("offline-end").getTimePoints());
//删除失效的远程缓存
mPushServer.getRouterCenter().getRemoteRouterManager().unRegister(userId, clientType);
Logs.PUSH.info("[SingleUserPush] find remote router in this pc, but local router not exists, userId={}, clientType={}, router={}"
, userId, clientType, remoteRouter);
return;
}
//3.否则说明用户已经跑到另外一台机器上了;路由信息发生更改,让PushClient重推
mPushServer.getPushCenter().getPushListener().onRedirect(message, timeLine.end("redirect-end").getTimePoints());
Logs.PUSH.info("路由发生更改");
/**
* 这块采用分布式才会用到
*/
Logs.PUSH.info("[SingleUserPush] find router in another pc, userId={}, clientType={}, router={}", userId, clientType, remoteRouter);
}
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (checkTimeout()) return;
if (future.isSuccess()) {//推送成功
if (message.isNeedAck()) {//需要客户端ACK, 添加等待客户端响应ACK的任务
addAckTask(messageId);
} else {
mPushServer.getPushCenter().getPushListener().onSuccess(message, timeLine.successEnd().getTimePoints());
}
Logs.PUSH.info("这里应该是单推");
Logs.PUSH.info("[SingleUserPush] push message to client success, timeLine={}, message={}", timeLine, message);
} else {//推送失败
/**
* 推送失败,这里加入发短信接口
*/
String pushMessage = null;
try {
pushMessage = new String(message.getContent(),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
MysqlConnecter mc = new MysqlConnecter();
String mobile = mc.selectOne("select mobile from m_user where device_id=\""+message.getUserId()+"\"");
Logs.PUSH.info("推送失败,mobile:"+mobile+",content:"+pushMessage);
mPushServer.getPushCenter().getPushListener().onFailure(message, timeLine.failureEnd().getTimePoints());
Logs.PUSH.error("[SingleUserPush] push message to client failure, message={}, conn={}", message, future.channel());
}
}
/**
* 添加ACK任务到队列, 等待客户端响应
*
* @param messageId 下发到客户端待ack的消息的sessionId
*/
private void addAckTask(int messageId) {
timeLine.addTimePoint("waiting-ack");
//因为要进队列,可以提前释放一些比较占用内存的字段,便于垃圾回收
message.finalized();
AckTask task = AckTask
.from(messageId)
.setCallback(new PushAckCallback(message, timeLine, mPushServer.getPushCenter()));
mPushServer.getPushCenter().getAckTaskQueue().add(task, message.getTimeoutMills() - (int) (System.currentTimeMillis() - start));
}
}
| apache-2.0 |
vdmeer/skb-java-examples | src/main/java/de/vandermeer/skb/examples/asciitable/examples/AT_01d_3Columns.java | 2096 | /* Copyright 2016 Sven van der Meer <vdmeer.sven@mykolab.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 de.vandermeer.skb.examples.asciitable.examples;
import org.apache.commons.lang3.text.StrBuilder;
import de.vandermeer.asciitable.AsciiTable;
import de.vandermeer.skb.interfaces.StandardExampleAsCmd;
/**
* AsciiTable example for a simple table as getting started example.
*
* @author Sven van der Meer <vdmeer.sven@mykolab.com>
*
*
*/
public class AT_01d_3Columns implements StandardExampleAsCmd {
@Override
public void showOutput(){
// tag::example[]
AsciiTable at = new AsciiTable();
at.addRule();
at.addRow("first row (col1)", "some information (col2)", "more info (col3)");
at.addRule();
at.addRow("second row (col1)", "some information (col2)", "more info (col3)");
at.addRule();
System.out.println(at.render());
// end::example[]
}
@Override
public StrBuilder getSource(){
String[] source = new String[]{
"AsciiTable at = new AsciiTable();",
"at.addRule();",
"at.addRow(\"first row (col1)\", \"some information (col2)\", \"more info (col3)\");",
"at.addRule();",
"at.addRow(\"second row (col1)\", \"some information (col2)\", \"more info (col3)\");",
"at.addRule();",
"System.out.println(at.render());",
};
return new StrBuilder().appendWithSeparators(source, "\n");
}
@Override
public String getDescription() {
return "table with 3 columns";
}
@Override
public String getID() {
return "3cols";
}
}
| apache-2.0 |
feb13th/CustomView | 广告条效果/src/main/java/com/example/ad/MainActivity.java | 4877 | package com.example.ad;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private TextView text;
private LinearLayout ll_point;
private int[] imgs = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e};
private String[] texts = {"1", "2", "3", "4", "5", "6"};
private List<ImageView> imageViews;
private int perPosition = 0;
private boolean isDragging=false;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int item = viewPager.getCurrentItem() + 1;
viewPager.setCurrentItem(item);
handler.sendEmptyMessageDelayed(0, 3000);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
text = (TextView) findViewById(R.id.textView);
ll_point = (LinearLayout) findViewById(R.id.ll_point);
imageViews = new ArrayList<>();
for (int i = 0; i < imgs.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(imgs[i]);
imageViews.add(imageView);
ImageView point = new ImageView(this);
point.setBackgroundResource(R.drawable.point_selector);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(16, 16);
if (i == 0) {
point.setEnabled(true);
} else {
point.setEnabled(false);
params.leftMargin = 8;
}
point.setLayoutParams(params);
ll_point.addView(point);
}
MyPagerAdapter adapter = new MyPagerAdapter();
viewPager.setAdapter(adapter);
int item = Integer.MAX_VALUE / 2 - Integer.MAX_VALUE % imageViews.size();
viewPager.setCurrentItem(item);
text.setText(texts[0]);
handler.sendEmptyMessageDelayed(0, 3000);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
int realPosition = position % imageViews.size();
text.setText(texts[realPosition]);
ll_point.getChildAt(perPosition).setEnabled(false);
ll_point.getChildAt(realPosition).setEnabled(true);
perPosition = realPosition;
}
@Override
public void onPageScrollStateChanged(int state) {
if (state==ViewPager.SCROLL_STATE_DRAGGING){
isDragging=true;
handler.removeCallbacksAndMessages(null);
}else if (state==ViewPager.SCROLL_STATE_SETTLING){
}else if (state==ViewPager.SCROLL_STATE_IDLE&&isDragging){
isDragging=false;
handler.removeCallbacksAndMessages(null);
handler.sendEmptyMessageDelayed(0,3000);
}
}
});
}
class MyPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
final int realPosition = position % imageViews.size();
ImageView imageView = imageViews.get(realPosition);
container.addView(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text_t=texts[realPosition];
Toast.makeText(MainActivity.this, "被点击了"+text_t, Toast.LENGTH_SHORT).show();
}
});
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
| apache-2.0 |
interpss/DeepMachineLearning | ipss.dml/src/org/interpss/service/train_data/singleNet/aclf/load_change_random/BaseLoadRandomChangeTrainCaseBuilder.java | 2732 | package org.interpss.service.train_data.singleNet.aclf.load_change_random;
import java.util.Random;
import org.interpss.service.train_data.ITrainCaseBuilder.BusData;
import org.interpss.service.train_data.singleNet.aclf.load_change.BaseLoadChangeTrainCaseBuilder;
import com.interpss.core.aclf.AclfBus;
public abstract class BaseLoadRandomChangeTrainCaseBuilder extends BaseLoadChangeTrainCaseBuilder{
@Override
public double[] getNetInput() {
double[] input = new double[4*this.noBus];
int i = 0;
for (AclfBus bus : aclfNet.getBusList()) {
if (bus.isActive()) {
if (this.busId2NoMapping != null)
i = this.busId2NoMapping.get(bus.getId());
BusData busdata = this.baseCaseData[i];
if (busdata.isSwing() /*bus.isSwing()*/) { // Swing Bus
// AclfSwingBus swing = bus.toSwingBus();
// input[2*i] = swing.getDesiredVoltAng(UnitType.Rad);
// input[2*i+1] = swing.getDesiredVoltMag(UnitType.PU);
}
else if (busdata.isPV() /*bus.isGenPV()*/) { // PV bus
// AclfPVGenBus pv = bus.toPVBus();
if (bus.getGenP() !=0 ) {
input[4 * i] = bus.getGenP();
input[4 * i + 1] = bus.getGenP() * bus.getGenP();
}
}
else {
input[4*i] = bus.getLoadP();
input[4*i+1] = bus.getLoadQ();
input[4 * i + 2] = bus.getLoadP() * bus.getLoadP();
// input[4 * i + 3] = bus.getLoadQ() * bus.getLoadQ();
}
i++;
}
}
return input;
}
/**
* The bus load is scaled by the scaling factor
*
* @param factor the scaling factor
*/
@Override
public void createTestCase() {
int i = 0;
double dp = 0;
for (AclfBus bus : getAclfNet().getBusList()) {
if (bus.isActive()) {
if ( this.busId2NoMapping != null )
i = this.busId2NoMapping.get(bus.getId());
if (!bus.isSwing() && !bus.isGenPV()) {
double factor= 2*new Random().nextFloat();
bus.setLoadP(this.baseCaseData[i].loadP * factor);
bus.setLoadQ(this.baseCaseData[i].loadQ * factor * (0.8 + 0.4 * new Random().nextFloat()));
dp +=bus.getLoadP()-this.baseCaseData[i].loadP;
// System.out.println("Bus id :"+bus.getId()+
// ", load factor: " + factor);
}
i++;
}
}
AclfBus bus = getAclfNet().getBus("Bus2");
bus.setGenP(dp + bus.getGenP()*new Random().nextFloat());
// System.out.println("Total system load: " + ComplexFunc.toStr(getAclfNet().totalLoad(UnitType.PU)) +
// ", factor: " + factor);
//System.out.println(aclfNet.net2String());
String result = this.runLF(this.getAclfNet());
System.out.println(result);
}
@Override
public void createTrainCase(int nth, int nTotal) {
createTestCase();
}
}
| apache-2.0 |
darranl/keycloak | services/src/main/java/org/keycloak/userprofile/validator/UsernameMutationValidator.java | 2431 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.userprofile.validator;
import java.util.List;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.services.messages.Messages;
import org.keycloak.services.validation.Validation;
import org.keycloak.userprofile.UserProfileAttributeValidationContext;
import org.keycloak.validate.SimpleValidator;
import org.keycloak.validate.ValidationContext;
import org.keycloak.validate.ValidationError;
import org.keycloak.validate.ValidatorConfig;
/**
* Validator to check User Profile username change and prevent it if not allowed in realm. Expects List of Strings as
* input.
*
* @author Vlastimil Elias <velias@redhat.com>
*
*/
public class UsernameMutationValidator implements SimpleValidator {
public static final String ID = "up-username-mutation";
@Override
public String getId() {
return ID;
}
@Override
public ValidationContext validate(Object input, String inputHint, ValidationContext context, ValidatorConfig config) {
@SuppressWarnings("unchecked")
List<String> values = (List<String>) input;
if (values.isEmpty()) {
return context;
}
String value = values.get(0);
if (Validation.isBlank(value)) {
return context;
}
UserModel user = UserProfileAttributeValidationContext.from(context).getAttributeContext().getUser();
RealmModel realm = context.getSession().getContext().getRealm();
if (!realm.isEditUsernameAllowed() && user != null && !value.equals(user.getFirstAttribute(UserModel.USERNAME))) {
context.addError(new ValidationError(ID, inputHint, Messages.READ_ONLY_USERNAME));
}
return context;
}
}
| apache-2.0 |
ppatierno/kaas | cluster-operator/src/main/java/io/strimzi/operator/cluster/operator/resource/ZookeeperScaler.java | 16729 | /*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.operator.resource;
import io.fabric8.kubernetes.api.model.Secret;
import io.strimzi.operator.cluster.model.Ca;
import io.strimzi.operator.cluster.model.ZookeeperCluster;
import io.strimzi.operator.common.PasswordGenerator;
import io.strimzi.operator.common.Reconciliation;
import io.strimzi.operator.common.ReconciliationLogger;
import io.strimzi.operator.common.Util;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.client.ZKClientConfig;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* Class for scaling Zookeeper 3.5 using the ZookeeperAdmin client
*/
public class ZookeeperScaler implements AutoCloseable {
private static final ReconciliationLogger LOGGER = ReconciliationLogger.create(ZookeeperScaler.class);
private final Vertx vertx;
private final ZooKeeperAdminProvider zooAdminProvider;
private final String zookeeperConnectionString;
private final Function<Integer, String> zkNodeAddress;
private final long operationTimeoutMs;
private final int zkAdminSessionTimeoutMs;
private final Secret clusterCaCertSecret;
private final Secret coKeySecret;
private final String trustStorePassword;
private File trustStoreFile;
private final String keyStorePassword;
private File keyStoreFile;
private final Reconciliation reconciliation;
/**
* ZookeeperScaler constructor
*
* @param reconciliation The reconciliation
* @param vertx Vertx instance
* @param zookeeperConnectionString Connection string to connect to the right Zookeeper
* @param zkNodeAddress Function for generating the Zookeeper node addresses
* @param clusterCaCertSecret Secret with Kafka cluster CA public key
* @param coKeySecret Secret with Cluster Operator public and private key
* @param operationTimeoutMs Operation timeout
* @param zkAdminSessionTimeoutMs Zookeeper Admin session timeout
*
*/
protected ZookeeperScaler(Reconciliation reconciliation, Vertx vertx, ZooKeeperAdminProvider zooAdminProvider,
String zookeeperConnectionString, Function<Integer, String> zkNodeAddress,
Secret clusterCaCertSecret, Secret coKeySecret, long operationTimeoutMs,
int zkAdminSessionTimeoutMs) {
this.reconciliation = reconciliation;
LOGGER.debugCr(reconciliation, "Creating Zookeeper Scaler for cluster {}", zookeeperConnectionString);
this.vertx = vertx;
this.zooAdminProvider = zooAdminProvider;
this.zookeeperConnectionString = zookeeperConnectionString;
this.zkNodeAddress = zkNodeAddress;
this.operationTimeoutMs = operationTimeoutMs;
this.zkAdminSessionTimeoutMs = zkAdminSessionTimeoutMs;
this.clusterCaCertSecret = clusterCaCertSecret;
this.coKeySecret = coKeySecret;
// Setup truststore from PEM file in cluster CA secret
// We cannot use P12 because of custom CAs which for simplicity provide only PEM
PasswordGenerator pg = new PasswordGenerator(12);
trustStorePassword = pg.generate();
// Setup keystore from PKCS12 in cluster-operator secret
keyStorePassword = new String(Util.decodeFromSecret(coKeySecret, "cluster-operator.password"), StandardCharsets.US_ASCII);
}
/**
* Scales Zookeeper to defined number of instances.
* It generates new configuration according to the desired number of nodes and updates Zookeeper configuration.
*
* @param scaleTo Number of Zookeeper nodes which should be used by the cluster
*
* @return Future which succeeds / fails when the scaling is finished
*/
public Future<Void> scale(int scaleTo) {
return getClientConfig()
.compose(this::connect)
.compose(zkAdmin -> {
Promise<Void> scalePromise = Promise.promise();
getCurrentConfig(zkAdmin)
.compose(servers -> scaleTo(zkAdmin, servers, scaleTo))
.onComplete(res ->
closeConnection(zkAdmin)
.onComplete(closeResult -> {
// Ignoring the result of `closeConnection`
if (res.succeeded()) {
scalePromise.complete();
} else {
scalePromise.fail(res.cause());
}
}));
return scalePromise.future();
});
}
/**
* Close the ZookeeperScaler instance. This deletes the certificate files.
*/
@Override
public void close() {
if (trustStoreFile != null) {
if (!trustStoreFile.delete()) {
LOGGER.debugCr(reconciliation, "Failed to delete file {}", trustStoreFile);
}
}
if (keyStoreFile != null) {
if (!keyStoreFile.delete()) {
LOGGER.debugCr(reconciliation, "Failed to delete file {}", keyStoreFile);
}
}
}
/**
* Internal method used to create the Zookeeper Admin client and connect it to Zookeeper
*
* @return Future indicating success or failure
*/
private Future<ZooKeeperAdmin> connect(ZKClientConfig clientConfig) {
Promise<ZooKeeperAdmin> connected = Promise.promise();
try {
ZooKeeperAdmin zkAdmin = zooAdminProvider.createZookeeperAdmin(
this.zookeeperConnectionString,
zkAdminSessionTimeoutMs,
watchedEvent -> LOGGER.debugCr(reconciliation, "Received event {} from ZooKeeperAdmin client connected to {}", watchedEvent, zookeeperConnectionString),
clientConfig);
Util.waitFor(reconciliation, vertx,
String.format("ZooKeeperAdmin connection to %s", zookeeperConnectionString),
"connected",
1_000,
operationTimeoutMs,
() -> zkAdmin.getState().isAlive() && zkAdmin.getState().isConnected())
.onSuccess(nothing -> connected.complete(zkAdmin))
.onFailure(cause -> {
String message = String.format("Failed to connect to Zookeeper %s. Connection was not ready in %d ms.", zookeeperConnectionString, operationTimeoutMs);
LOGGER.warnCr(reconciliation, message);
closeConnection(zkAdmin)
.onComplete(nothing -> connected.fail(new ZookeeperScalingException(message, cause)));
});
} catch (IOException e) {
LOGGER.warnCr(reconciliation, "Failed to connect to {} to scale Zookeeper", zookeeperConnectionString, e);
connected.fail(new ZookeeperScalingException("Failed to connect to Zookeeper " + zookeeperConnectionString, e));
}
return connected.future();
}
/**
* Internal method to scale Zookeeper up or down or check configuration. It will:
* 1) Compare the current configuration with the desired configuration
* 2) Update the configuration if needed
*
* @param currentServers Current list of servers from Zookeeper cluster
* @param scaleTo Desired scale
* @return Future indicating success or failure
*/
private Future<Void> scaleTo(ZooKeeperAdmin zkAdmin, Map<String, String> currentServers, int scaleTo) {
Map<String, String> desiredServers = generateConfig(scaleTo, zkNodeAddress);
if (isDifferent(currentServers, desiredServers)) {
LOGGER.debugCr(reconciliation, "The Zookeeper server configuration needs to be updated");
return updateConfig(zkAdmin, desiredServers).map((Void) null);
} else {
LOGGER.debugCr(reconciliation, "The Zookeeper server configuration is already up to date");
return Future.succeededFuture();
}
}
/**
* Gets the current configuration from Zookeeper.
*
* @return Future containing Map with the current Zookeeper configuration
*/
private Future<Map<String, String>> getCurrentConfig(ZooKeeperAdmin zkAdmin) {
Promise<Map<String, String>> configPromise = Promise.promise();
vertx.executeBlocking(promise -> {
try {
byte[] config = zkAdmin.getConfig(false, null);
Map<String, String> servers = parseConfig(config);
LOGGER.debugCr(reconciliation, "Current Zookeeper configuration is {}", servers);
promise.complete(servers);
} catch (KeeperException | InterruptedException e) {
LOGGER.warnCr(reconciliation, "Failed to get current Zookeeper server configuration", e);
promise.fail(new ZookeeperScalingException("Failed to get current Zookeeper server configuration", e));
}
}, false, configPromise);
return configPromise.future();
}
/**
* Updates the configuration in the Zookeeper cluster
*
* @param newServers New configuration which will be used for the update
* @return Future with the updated configuration
*/
private Future<Map<String, String>> updateConfig(ZooKeeperAdmin zkAdmin, Map<String, String> newServers) {
Promise<Map<String, String>> configPromise = Promise.promise();
vertx.executeBlocking(promise -> {
try {
LOGGER.debugCr(reconciliation, "Updating Zookeeper configuration to {}", newServers);
byte[] newConfig = zkAdmin.reconfigure(null, null, serversMapToList(newServers), -1, null);
Map<String, String> servers = parseConfig(newConfig);
LOGGER.debugCr(reconciliation, "New Zookeeper configuration is {}", servers);
promise.complete(servers);
} catch (KeeperException | InterruptedException e) {
LOGGER.warnCr(reconciliation, "Failed to update Zookeeper server configuration", e);
promise.fail(new ZookeeperScalingException("Failed to update Zookeeper server configuration", e));
}
}, false, configPromise);
return configPromise.future();
}
/**
* Closes the Zookeeper connection
*/
private Future<Void> closeConnection(ZooKeeperAdmin zkAdmin) {
Promise<Void> closePromise = Promise.promise();
if (zkAdmin != null) {
vertx.executeBlocking(promise -> {
try {
zkAdmin.close((int) operationTimeoutMs);
promise.complete();
} catch (Exception e) {
LOGGER.warnCr(reconciliation, "Failed to close the ZooKeeperAdmin", e);
promise.fail(e);
}
}, false, closePromise);
} else {
closePromise.complete();
}
return closePromise.future();
}
/**
* Generates the TLS configuration for Zookeeper.
*
* @return
*/
private Future<ZKClientConfig> getClientConfig() {
Promise<ZKClientConfig> configPromise = Promise.promise();
vertx.executeBlocking(promise -> {
try {
ZKClientConfig clientConfig = new ZKClientConfig();
trustStoreFile = Util.createFileTrustStore(getClass().getName(), "p12", Ca.certs(clusterCaCertSecret), trustStorePassword.toCharArray());
keyStoreFile = Util.createFileStore(getClass().getName(), "p12", Util.decodeFromSecret(coKeySecret, "cluster-operator.p12"));
clientConfig.setProperty("zookeeper.clientCnxnSocket", "org.apache.zookeeper.ClientCnxnSocketNetty");
clientConfig.setProperty("zookeeper.client.secure", "true");
clientConfig.setProperty("zookeeper.sasl.client", "false");
clientConfig.setProperty("zookeeper.ssl.trustStore.location", trustStoreFile.getAbsolutePath());
clientConfig.setProperty("zookeeper.ssl.trustStore.password", trustStorePassword);
clientConfig.setProperty("zookeeper.ssl.trustStore.type", "PKCS12");
clientConfig.setProperty("zookeeper.ssl.keyStore.location", keyStoreFile.getAbsolutePath());
clientConfig.setProperty("zookeeper.ssl.keyStore.password", keyStorePassword);
clientConfig.setProperty("zookeeper.ssl.keyStore.type", "PKCS12");
clientConfig.setProperty("zookeeper.request.timeout", String.valueOf(operationTimeoutMs));
promise.complete(clientConfig);
} catch (Exception e) {
LOGGER.warnCr(reconciliation, "Failed to create Zookeeper client configuration", e);
promise.fail(new ZookeeperScalingException("Failed to create Zookeeper client configuration", e));
}
}, false, configPromise);
return configPromise.future();
}
/**
* Converts the map with configuration to List of Strings which is the format in which the ZookeeperAdmin client
* expects the new configuration.
*
* @param servers Map with Zookeeper configuration
* @return List with Zookeeper configuration
*/
/*test*/ static List<String> serversMapToList(Map<String, String> servers) {
List<String> serversList = new ArrayList<>(servers.size());
for (var entry : servers.entrySet()) {
serversList.add(String.format("%s=%s", entry.getKey(), entry.getValue()));
}
return serversList;
}
/**
* Parse the byte array we get from Zookeeper into a map we use internally. The returned Map will container only
* the server entries from the Zookeeper configuration. Other entries such as version will be ignored.
*
* @param byteConfig byte[] from Zookeeper client
* @return Map with Zookeeper configuration
*/
/*test*/ static Map<String, String> parseConfig(byte[] byteConfig) {
String config = new String(byteConfig, StandardCharsets.US_ASCII);
Map<String, String> configMap = Util.parseMap(config);
Map<String, String> serverMap = new HashMap<>(configMap.size() - 1);
for (Map.Entry<String, String> entry : configMap.entrySet()) {
if (entry.getKey().startsWith("server.")) {
serverMap.put(entry.getKey(), entry.getValue());
}
}
return serverMap;
}
/**
* Checks whether two Zookeeper configurations are different or not. We will change the configuration only if it
* differs to minimize the load.
*
* @param current Map with current configuration
* @param desired Map with desired configuration
* @return True if the configurations differ and should be updated. False otherwise.
*/
/*test*/ static boolean isDifferent(Map<String, String> current, Map<String, String> desired) {
return !current.equals(desired);
}
/**
* Generates a map with Zookeeper configuration
*
* @param scale Number of nodes which the Zookeeper cluster should have
* @return Map with configuration
*/
/*test*/ static Map<String, String> generateConfig(int scale, Function<Integer, String> zkNodeAddress) {
Map<String, String> servers = new HashMap<>(scale);
for (int i = 0; i < scale; i++) {
// The Zookeeper server IDs starts with 1, but pod index starts from 0
String key = String.format("server.%d", i + 1);
String value = String.format("%s:%d:%d:participant;127.0.0.1:%d", zkNodeAddress.apply(i), ZookeeperCluster.CLUSTERING_PORT, ZookeeperCluster.LEADER_ELECTION_PORT, ZookeeperCluster.CLIENT_PLAINTEXT_PORT);
servers.put(key, value);
}
return servers;
}
}
| apache-2.0 |
abstools/java-timsort-bug | KeY/jre/java/nio/ByteBuffer.java | 7163 | /* This file has been generated by Stubmaker (de.uka.ilkd.stubmaker)
* Date: Wed Nov 26 11:26:00 CET 2014
*/
package java.nio;
public abstract class ByteBuffer extends java.nio.Buffer implements java.lang.Comparable
{
final byte[] hb;
final int offset;
boolean isReadOnly;
boolean bigEndian;
boolean nativeByteOrder;
/*@ requires true; ensures true; assignable \everything; */
public static java.nio.ByteBuffer allocateDirect(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public static java.nio.ByteBuffer allocate(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public static java.nio.ByteBuffer wrap(byte[] arg0, int arg1, int arg2);
/*@ requires true; ensures true; assignable \everything; */
public static java.nio.ByteBuffer wrap(byte[] arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer slice();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer duplicate();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer asReadOnlyBuffer();
/*@ requires true; ensures true; assignable \everything; */
public abstract byte get();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer put(byte arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract byte get(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer put(int arg0, byte arg1);
/*@ requires true; ensures true; assignable \everything; */
public java.nio.ByteBuffer get(byte[] arg0, int arg1, int arg2);
/*@ requires true; ensures true; assignable \everything; */
public java.nio.ByteBuffer get(byte[] arg0);
/*@ requires true; ensures true; assignable \everything; */
public java.nio.ByteBuffer put(java.nio.ByteBuffer arg0);
/*@ requires true; ensures true; assignable \everything; */
public java.nio.ByteBuffer put(byte[] arg0, int arg1, int arg2);
/*@ requires true; ensures true; assignable \everything; */
public final java.nio.ByteBuffer put(byte[] arg0);
/*@ requires true; ensures true; assignable \everything; */
public final boolean hasArray();
/*@ requires true; ensures true; assignable \everything; */
public final byte[] array();
/*@ requires true; ensures true; assignable \everything; */
public final int arrayOffset();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer compact();
/*@ requires true; ensures true; assignable \everything; */
public abstract boolean isDirect();
/*@ requires true; ensures true; assignable \everything; */
public java.lang.String toString();
/*@ requires true; ensures true; assignable \everything; */
public int hashCode();
/*@ requires true; ensures true; assignable \everything; */
public boolean equals(java.lang.Object arg0);
/*@ requires true; ensures true; assignable \everything; */
public int compareTo(java.nio.ByteBuffer arg0);
/*@ requires true; ensures true; assignable \everything; */
public final java.nio.ByteOrder order();
/*@ requires true; ensures true; assignable \everything; */
public final java.nio.ByteBuffer order(java.nio.ByteOrder arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract char getChar();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putChar(char arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract char getChar(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putChar(int arg0, char arg1);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.CharBuffer asCharBuffer();
/*@ requires true; ensures true; assignable \everything; */
public abstract short getShort();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putShort(short arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract short getShort(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putShort(int arg0, short arg1);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ShortBuffer asShortBuffer();
/*@ requires true; ensures true; assignable \everything; */
public abstract int getInt();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putInt(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract int getInt(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putInt(int arg0, int arg1);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.IntBuffer asIntBuffer();
/*@ requires true; ensures true; assignable \everything; */
public abstract long getLong();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putLong(long arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract long getLong(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putLong(int arg0, long arg1);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.LongBuffer asLongBuffer();
/*@ requires true; ensures true; assignable \everything; */
public abstract float getFloat();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putFloat(float arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract float getFloat(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putFloat(int arg0, float arg1);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.FloatBuffer asFloatBuffer();
/*@ requires true; ensures true; assignable \everything; */
public abstract double getDouble();
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putDouble(double arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract double getDouble(int arg0);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.ByteBuffer putDouble(int arg0, double arg1);
/*@ requires true; ensures true; assignable \everything; */
public abstract java.nio.DoubleBuffer asDoubleBuffer();
/*@ requires true; ensures true; assignable \everything; */
public java.lang.Object array();
/*@ requires true; ensures true; assignable \everything; */
public int compareTo(java.lang.Object arg0);
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/transform/DeleteMonitoringScheduleRequestProtocolMarshaller.java | 2822 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.sagemaker.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.sagemaker.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteMonitoringScheduleRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteMonitoringScheduleRequestProtocolMarshaller implements Marshaller<Request<DeleteMonitoringScheduleRequest>, DeleteMonitoringScheduleRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("SageMaker.DeleteMonitoringSchedule").serviceName("AmazonSageMaker").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DeleteMonitoringScheduleRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DeleteMonitoringScheduleRequest> marshall(DeleteMonitoringScheduleRequest deleteMonitoringScheduleRequest) {
if (deleteMonitoringScheduleRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DeleteMonitoringScheduleRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, deleteMonitoringScheduleRequest);
protocolMarshaller.startMarshalling();
DeleteMonitoringScheduleRequestMarshaller.getInstance().marshall(deleteMonitoringScheduleRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/CreateDhcpOptionsResultStaxUnmarshaller.java | 2496 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ec2.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* CreateDhcpOptionsResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateDhcpOptionsResultStaxUnmarshaller implements Unmarshaller<CreateDhcpOptionsResult, StaxUnmarshallerContext> {
public CreateDhcpOptionsResult unmarshall(StaxUnmarshallerContext context) throws Exception {
CreateDhcpOptionsResult createDhcpOptionsResult = new CreateDhcpOptionsResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return createDhcpOptionsResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("dhcpOptions", targetDepth)) {
createDhcpOptionsResult.setDhcpOptions(DhcpOptionsStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return createDhcpOptionsResult;
}
}
}
}
private static CreateDhcpOptionsResultStaxUnmarshaller instance;
public static CreateDhcpOptionsResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new CreateDhcpOptionsResultStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
wjlwcllover/ViewPagerTest | src/com/example/viewpagertest/MainActivity.java | 2369 | package com.example.viewpagertest;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.R.integer;
import android.app.Activity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class MainActivity extends Activity {
private ViewPager viewPager ;
private int[] mImagesIds = new int[]{R.drawable.a1, R.drawable.a2,R.drawable.a3};
List<ImageView> imageViews = new ArrayList<ImageView>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager= (ViewPager) findViewById( R.id.view_pager);
//Ìí¼ÓÇл»¶¯»Ð§¹û 3.0 ֮ǰ²»¿ÉÒÔʹÓÃÕâÖÖЧ¹û
// viewPager.setPageTransformer(true, new DepthPagesTransForm());
viewPager.setAdapter(new PagerAdapter() {
@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
ImageView imageView =new ImageView(MainActivity.this);
imageView.setImageResource(mImagesIds[position]);
imageView.setScaleType(ScaleType.CENTER_CROP);
container.addView(imageView);
imageViews.add(imageView);
return imageView;
}
@Override
public void destroyItem(View container, int position, Object object) {
// TODO Auto-generated method stub
((ViewPager) container).removeView(imageViews.get(position));
}
@Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == object;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mImagesIds.length;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_6245.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_6245 {
}
| apache-2.0 |
joewalnes/idea-community | java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacCompiler.java | 18510 | /*
* Copyright 2000-2009 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.compiler.impl.javaCompiler.javac;
import com.intellij.compiler.CompilerConfiguration;
import com.intellij.compiler.CompilerConfigurationImpl;
import com.intellij.compiler.CompilerIOUtil;
import com.intellij.compiler.OutputParser;
import com.intellij.compiler.impl.CompilerUtil;
import com.intellij.compiler.impl.javaCompiler.ExternalCompiler;
import com.intellij.compiler.impl.javaCompiler.ModuleChunk;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.compiler.CompilerPaths;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdkType;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkType;
import com.intellij.openapi.projectRoots.ex.JavaSdkUtil;
import com.intellij.openapi.projectRoots.impl.MockJdkWrapper;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.rt.compiler.JavacRunner;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.*;
import java.util.*;
public class JavacCompiler extends ExternalCompiler {
private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler");
private final Project myProject;
private final List<File> myTempFiles = new ArrayList<File>();
@NonNls private static final String JAVAC_MAIN_CLASS_OLD = "sun.tools.javac.Main";
@NonNls public static final String JAVAC_MAIN_CLASS = "com.sun.tools.javac.Main";
private boolean myAnnotationProcessorMode = false;
public JavacCompiler(Project project) {
myProject = project;
}
public boolean isAnnotationProcessorMode() {
return myAnnotationProcessorMode;
}
/**
* @param annotationProcessorMode
* @return previous value
*/
public boolean setAnnotationProcessorMode(boolean annotationProcessorMode) {
final boolean oldValue = myAnnotationProcessorMode;
myAnnotationProcessorMode = annotationProcessorMode;
return oldValue;
}
public boolean checkCompiler(final CompileScope scope) {
final Module[] modules = scope.getAffectedModules();
final Set<Sdk> checkedJdks = new HashSet<Sdk>();
for (final Module module : modules) {
final Sdk jdk = ModuleRootManager.getInstance(module).getSdk();
if (jdk == null) {
continue;
}
if (checkedJdks.contains(jdk)) {
continue;
}
final VirtualFile homeDirectory = jdk.getHomeDirectory();
if (homeDirectory == null) {
Messages.showMessageDialog(myProject, CompilerBundle.jdkHomeNotFoundMessage(jdk),
CompilerBundle.message("compiler.javac.name"), Messages.getErrorIcon());
return false;
}
final SdkType sdkType = jdk.getSdkType();
if (sdkType instanceof JavaSdkType){
final String vmExecutablePath = ((JavaSdkType)sdkType).getVMExecutablePath(jdk);
if (vmExecutablePath == null) {
Messages.showMessageDialog(myProject,
CompilerBundle.message("javac.error.vm.executable.missing", jdk.getName()),
CompilerBundle.message("compiler.javac.name"), Messages.getErrorIcon());
return false;
}
final String toolsJarPath = ((JavaSdkType)sdkType).getToolsPath(jdk);
if (toolsJarPath == null) {
Messages.showMessageDialog(myProject,
CompilerBundle.message("javac.error.tools.jar.missing", jdk.getName()), CompilerBundle.message("compiler.javac.name"),
Messages.getErrorIcon());
return false;
}
final String versionString = jdk.getVersionString();
if (versionString == null) {
Messages.showMessageDialog(myProject, CompilerBundle.message("javac.error.unknown.jdk.version", jdk.getName()),
CompilerBundle.message("compiler.javac.name"), Messages.getErrorIcon());
return false;
}
if (CompilerUtil.isOfVersion(versionString, "1.0")) {
Messages.showMessageDialog(myProject, CompilerBundle.message("javac.error.1_0_compilation.not.supported"), CompilerBundle.message("compiler.javac.name"), Messages.getErrorIcon());
return false;
}
}
checkedJdks.add(jdk);
}
return true;
}
@NotNull
@NonNls
public String getId() { // used for externalization
return "Javac";
}
@NotNull
public String getPresentableName() {
return CompilerBundle.message("compiler.javac.name");
}
@NotNull
public Configurable createConfigurable() {
return new JavacConfigurable(JavacSettings.getInstance(myProject));
}
public OutputParser createErrorParser(@NotNull final String outputDir, Process process) {
return new JavacOutputParser(myProject);
}
public OutputParser createOutputParser(@NotNull final String outputDir) {
return null;
}
private static class MyException extends RuntimeException {
private MyException(Throwable cause) {
super(cause);
}
}
@NotNull
public String[] createStartupCommand(final ModuleChunk chunk, final CompileContext context, final String outputPath)
throws IOException, IllegalArgumentException {
try {
return ApplicationManager.getApplication().runReadAction(new Computable<String[]>() {
public String[] compute() {
try {
final List<String> commandLine = new ArrayList<String>();
createStartupCommand(chunk, commandLine, outputPath, JavacSettings.getInstance(myProject), context.isAnnotationProcessorsEnabled());
return ArrayUtil.toStringArray(commandLine);
}
catch (IOException e) {
throw new MyException(e);
}
}
});
}
catch (MyException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
throw (IOException)cause;
}
throw e;
}
}
private void createStartupCommand(final ModuleChunk chunk, @NonNls final List<String> commandLine, final String outputPath,
JavacSettings javacSettings, final boolean annotationProcessorsEnabled) throws IOException {
final Sdk jdk = getJdkForStartupCommand(chunk);
final String versionString = jdk.getVersionString();
if (versionString == null || "".equals(versionString) || !(jdk.getSdkType() instanceof JavaSdkType)) {
throw new IllegalArgumentException(CompilerBundle.message("javac.error.unknown.jdk.version", jdk.getName()));
}
final boolean isVersion1_0 = CompilerUtil.isOfVersion(versionString, "1.0");
final boolean isVersion1_1 = CompilerUtil.isOfVersion(versionString, "1.1");
final boolean isVersion1_2 = CompilerUtil.isOfVersion(versionString, "1.2");
final boolean isVersion1_3 = CompilerUtil.isOfVersion(versionString, "1.3");
final boolean isVersion1_4 = CompilerUtil.isOfVersion(versionString, "1.4");
final boolean isVersion1_5 = CompilerUtil.isOfVersion(versionString, "1.5") || CompilerUtil.isOfVersion(versionString, "5.0");
final boolean isVersion1_5_or_higher = isVersion1_5 || !(isVersion1_0 || isVersion1_1 || isVersion1_2 || isVersion1_3 || isVersion1_4);
final int versionIndex = isVersion1_0? 0 : isVersion1_1? 1 : isVersion1_2? 2 : isVersion1_3? 3 : isVersion1_4? 4 : isVersion1_5? 5 : 6;
JavaSdkType sdkType = (JavaSdkType)jdk.getSdkType();
final String toolsJarPath = sdkType.getToolsPath(jdk);
if (toolsJarPath == null) {
throw new IllegalArgumentException(CompilerBundle.message("javac.error.tools.jar.missing", jdk.getName()));
}
final String vmExePath = sdkType.getVMExecutablePath(jdk);
commandLine.add(vmExePath);
if (isVersion1_1 || isVersion1_0) {
commandLine.add("-mx" + javacSettings.MAXIMUM_HEAP_SIZE + "m");
}
else {
commandLine.add("-Xmx" + javacSettings.MAXIMUM_HEAP_SIZE + "m");
}
final List<String> additionalOptions =
addAdditionalSettings(commandLine, javacSettings, myAnnotationProcessorMode, versionIndex, myProject, annotationProcessorsEnabled);
CompilerUtil.addLocaleOptions(commandLine, false);
commandLine.add("-classpath");
if (isVersion1_0) {
commandLine.add(sdkType.getToolsPath(jdk)); // do not use JavacRunner for jdk 1.0
}
else {
commandLine.add(sdkType.getToolsPath(jdk) + File.pathSeparator + JavaSdkUtil.getIdeaRtJarPath());
commandLine.add(JavacRunner.class.getName());
commandLine.add("\"" + versionString + "\"");
}
if (isVersion1_2 || isVersion1_1 || isVersion1_0) {
commandLine.add(JAVAC_MAIN_CLASS_OLD);
}
else {
commandLine.add(JAVAC_MAIN_CLASS);
}
addCommandLineOptions(chunk, commandLine, outputPath, jdk, isVersion1_0, isVersion1_1, myTempFiles, true, true, myAnnotationProcessorMode);
commandLine.addAll(additionalOptions);
final List<VirtualFile> files = chunk.getFilesToCompile();
if (isVersion1_0) {
for (VirtualFile file : files) {
String path = file.getPath();
if (LOG.isDebugEnabled()) {
LOG.debug("Adding path for compilation " + path);
}
commandLine.add(CompilerUtil.quotePath(path));
}
}
else {
File sourcesFile = FileUtil.createTempFile("javac", ".tmp");
sourcesFile.deleteOnExit();
myTempFiles.add(sourcesFile);
final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(sourcesFile)));
try {
for (final VirtualFile file : files) {
// Important: should use "/" slashes!
// but not for JDK 1.5 - see SCR 36673
final String path = isVersion1_5_or_higher ? file.getPath().replace('/', File.separatorChar) : file.getPath();
if (LOG.isDebugEnabled()) {
LOG.debug("Adding path for compilation " + path);
}
writer.println(isVersion1_1 ? path : CompilerUtil.quotePath(path));
}
}
finally {
writer.close();
}
commandLine.add("@" + sourcesFile.getAbsolutePath());
}
}
public static List<String> addAdditionalSettings(List<String> commandLine, JavacSettings javacSettings, boolean isAnnotationProcessing,
int versionIndex, Project project, final boolean annotationProcessorsEnabled) {
final List<String> additionalOptions = new ArrayList<String>();
StringTokenizer tokenizer = new StringTokenizer(javacSettings.getOptionsString(project), " ");
if (versionIndex < 6) {
isAnnotationProcessing = false; // makes no sense for these versions
}
if (isAnnotationProcessing) {
final CompilerConfiguration config = CompilerConfiguration.getInstance(project);
additionalOptions.add("-Xprefer:source");
additionalOptions.add("-implicit:none");
additionalOptions.add("-proc:only");
if (!config.isObtainProcessorsFromClasspath()) {
final String processorPath = config.getProcessorPath();
if (processorPath.length() > 0) {
additionalOptions.add("-processorpath");
additionalOptions.add(FileUtil.toSystemDependentName(processorPath));
}
}
for (Map.Entry<String, String> entry : config.getAnnotationProcessorsMap().entrySet()) {
additionalOptions.add("-processor");
additionalOptions.add(entry.getKey());
final String options = entry.getValue();
if (options.length() > 0) {
StringTokenizer optionsTokenizer = new StringTokenizer(options, " ", false);
while (optionsTokenizer.hasMoreTokens()) {
final String token = optionsTokenizer.nextToken();
if (token.startsWith("-A")) {
additionalOptions.add(token.substring("-A".length()));
}
else {
additionalOptions.add("-A" + token);
}
}
}
}
}
else {
if (versionIndex > 5) {
if (annotationProcessorsEnabled) {
// Unless explicitly specified by user, disable annotation processing by default for 'java compilation' mode
// This is needed to suppress unwanted side-effects from auto-discovered processors from compilation classpath
additionalOptions.add("-proc:none");
}
}
}
while (tokenizer.hasMoreTokens()) {
@NonNls String token = tokenizer.nextToken();
if (versionIndex == 0) {
if ("-deprecation".equals(token)) {
continue; // not supported for this version
}
}
if (versionIndex <= 4) {
if ("-Xlint".equals(token)) {
continue; // not supported in these versions
}
}
if (token.startsWith("-proc:")) {
continue;
}
if (isAnnotationProcessing) {
if (token.startsWith("-implicit:")) {
continue;
}
}
if (token.startsWith("-J-")) {
commandLine.add(token.substring("-J".length()));
}
else {
additionalOptions.add(token);
}
}
return additionalOptions;
}
public static void addCommandLineOptions(ModuleChunk chunk, @NonNls List<String> commandLine, String outputPath, Sdk jdk,
boolean version1_0,
boolean version1_1,
List<File> tempFiles, boolean addSourcePath, boolean useTempFile,
boolean isAnnotationProcessingMode) throws IOException {
LanguageLevel languageLevel = chunk.getLanguageLevel();
CompilerUtil.addSourceCommandLineSwitch(jdk, languageLevel, commandLine);
commandLine.add("-verbose");
final String cp = chunk.getCompilationClasspath();
final String bootCp = chunk.getCompilationBootClasspath();
final String classPath;
if (version1_0 || version1_1) {
classPath = bootCp + File.pathSeparator + cp;
}
else {
classPath = cp;
commandLine.add("-bootclasspath");
addClassPathValue(jdk, false, commandLine, bootCp, "javac_bootcp", tempFiles, useTempFile);
}
commandLine.add("-classpath");
addClassPathValue(jdk, version1_0, commandLine, classPath, "javac_cp", tempFiles, useTempFile);
if (!version1_1 && !version1_0 && addSourcePath) {
commandLine.add("-sourcepath");
// this way we tell the compiler that the sourcepath is "empty". However, javac thinks that sourcepath is 'new File("")'
// this may cause problems if we have java code in IDEA working directory
if (isAnnotationProcessingMode) {
final int currentSourcesMode = chunk.getSourcesFilter();
commandLine.add(chunk.getSourcePath(currentSourcesMode == ModuleChunk.TEST_SOURCES? ModuleChunk.ALL_SOURCES : currentSourcesMode));
}
else {
commandLine.add("\"\"");
}
}
if (isAnnotationProcessingMode) {
commandLine.add("-s");
commandLine.add(outputPath.replace('/', File.separatorChar));
final String moduleOutputPath = CompilerPaths.getModuleOutputPath(chunk.getModules()[0], false);
if (moduleOutputPath != null) {
commandLine.add("-d");
commandLine.add(moduleOutputPath.replace('/', File.separatorChar));
}
}
else {
commandLine.add("-d");
commandLine.add(outputPath.replace('/', File.separatorChar));
}
}
private static void addClassPathValue(final Sdk jdk, final boolean isVersion1_0, final List<String> commandLine, final String cpString, @NonNls final String tempFileName,
List<File> tempFiles,
boolean useTempFile) throws IOException {
if (!useTempFile) {
commandLine.add(cpString);
return;
}
// must include output path to classpath, otherwise javac will compile all dependent files no matter were they compiled before or not
if (isVersion1_0) {
commandLine.add(((JavaSdkType)jdk.getSdkType()).getToolsPath(jdk) + File.pathSeparator + cpString);
}
else {
File cpFile = FileUtil.createTempFile(tempFileName, ".tmp");
cpFile.deleteOnExit();
tempFiles.add(cpFile);
final DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(cpFile)));
try {
CompilerIOUtil.writeString(cpString, out);
}
finally {
out.close();
}
commandLine.add("@" + cpFile.getAbsolutePath());
}
}
private Sdk getJdkForStartupCommand(final ModuleChunk chunk) {
final Sdk jdk = chunk.getJdk();
if (ApplicationManager.getApplication().isUnitTestMode() && JavacSettings.getInstance(myProject).isTestsUseExternalCompiler()) {
final String jdkHomePath = CompilerConfigurationImpl.getTestsExternalCompilerHome();
if (jdkHomePath == null) {
throw new IllegalArgumentException("[TEST-MODE] Cannot determine home directory for JDK to use javac from");
}
// when running under Mock JDK use VM executable from the JDK on which the tests run
return new MockJdkWrapper(jdkHomePath, jdk);
}
return jdk;
}
public void compileFinished() {
FileUtil.asyncDelete(myTempFiles);
myTempFiles.clear();
}
}
| apache-2.0 |
searchbox-io/Jest | jest-common/src/test/java/io/searchbox/indices/OptimizeTest.java | 1101 | package io.searchbox.indices;
import io.searchbox.client.config.ElasticsearchVersion;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class OptimizeTest {
@Test
public void testBasicUriGeneration() {
Optimize optimize = new Optimize.Builder().addIndex("twitter").build();
assertEquals("POST", optimize.getRestMethodName());
assertEquals("twitter/_optimize", optimize.getURI(ElasticsearchVersion.UNKNOWN));
}
@Test
public void equalsReturnsTrueForSameIndex() {
Optimize optimize1 = new Optimize.Builder().addIndex("twitter").build();
Optimize optimize1Duplicate = new Optimize.Builder().addIndex("twitter").build();
assertEquals(optimize1, optimize1Duplicate);
}
@Test
public void equalsReturnsFalseForDifferentIndex() {
Optimize optimize1 = new Optimize.Builder().addIndex("twitter").build();
Optimize optimize2 = new Optimize.Builder().addIndex("myspace").build();
assertNotEquals(optimize1, optimize2);
}
} | apache-2.0 |
zhanhongbo1112/trunk | yqboots-web/yqboots-web-thymeleaf/src/main/java/com/yqboots/web/thymeleaf/processor/element/ProgressElementProcessor.java | 3198 | /*
*
* * Copyright 2015-2016 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.yqboots.web.thymeleaf.processor.element;
import org.apache.commons.lang3.StringUtils;
import org.thymeleaf.Arguments;
import org.thymeleaf.Configuration;
import org.thymeleaf.dom.Element;
import org.thymeleaf.dom.Node;
import org.thymeleaf.dom.Text;
import org.thymeleaf.processor.element.AbstractMarkupSubstitutionElementProcessor;
import org.thymeleaf.standard.expression.IStandardExpression;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import java.util.ArrayList;
import java.util.List;
/**
* Progress Bar.
*
* @author Eric H B Zhan
* @since 1.2.0
*/
public class ProgressElementProcessor extends AbstractMarkupSubstitutionElementProcessor {
public static final String ATTR_VALUE = "value";
public ProgressElementProcessor() {
super("progress");
}
@Override
protected List<Node> getMarkupSubstitutes(final Arguments arguments, final Element element) {
final List<Node> nodes = new ArrayList<>();
final Configuration configuration = arguments.getConfiguration();
// Obtain the Thymeleaf Standard Expression parser
final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
String value = element.getAttributeValue(ATTR_VALUE);
final IStandardExpression expression = parser.parseExpression(configuration, arguments, value);
value = (String) expression.execute(configuration, arguments);
nodes.add(build(StringUtils.defaultIfBlank(value, "0")));
return nodes;
}
private Element build(final String valueAttrValue) {
final Element container = new Element("div");
container.setAttribute("class", "progress progress-u");
container.addChild(buildProgressBar(valueAttrValue));
return container;
}
private Element buildProgressBar(final String valueAttrValue) {
final Element result = new Element("div");
result.setAttribute("class", "progress-bar progress-bar-u");
result.setAttribute("style", "width: " + valueAttrValue + "%");
result.setAttribute("aria-valuemax", "100");
result.setAttribute("aria-valuemin", "0");
result.setAttribute("aria-valuenow", valueAttrValue);
result.setAttribute("role", "progressbar");
result.addChild(new Text(valueAttrValue + "%"));
return result;
}
@Override
public int getPrecedence() {
return 2000;
}
}
| apache-2.0 |
JottaReyes/SunshineV2.0 | app/src/main/java/com/example/android/sunshine/app/DetailFragment.java | 10170 | package com.example.android.sunshine.app;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.sunshine.app.data.WeatherContract;
/**
* Created by jorge.reyes on 11/09/2014.
*/
public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private static final String LOCATION_KEY = "location";
private ShareActionProvider mShareActionProvider;
private String mLocation;
private String mForecast;
private String mDateStr;
private static final int DETAIL_LOADER = 0;
private static final String[] FORECAST_COLUMNS = {
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
WeatherContract.WeatherEntry.COLUMN_DATETEXT,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.WeatherEntry.COLUMN_HUMIDITY,
WeatherContract.WeatherEntry.COLUMN_PRESSURE,
WeatherContract.WeatherEntry.COLUMN_WIND_SPEED,
WeatherContract.WeatherEntry.COLUMN_DEGREES,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
// This works because the WeatherProvider returns location data joined with
// weather data, even though they're stored in two different tables.
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING
};
private ImageView mIconView;
private TextView mFriendlyDateView;
private TextView mDateView;
private TextView mDescriptionView;
private TextView mHighTempView;
private TextView mLowTempView;
private TextView mHumidityView;
private TextView mWindView;
private TextView mPressureView;
public DetailFragment() {
setHasOptionsMenu(true);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(LOCATION_KEY, mLocation);
super.onSaveInstanceState(outState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mDateStr = arguments.getString(DetailActivity.DATE_KEY);
}
if (savedInstanceState != null) {
mLocation = savedInstanceState.getString(LOCATION_KEY);
}
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
mIconView = (ImageView) rootView.findViewById(R.id.detail_icon);
mDateView = (TextView) rootView.findViewById(R.id.detail_date_textview);
mFriendlyDateView = (TextView) rootView.findViewById(R.id.detail_day_textview);
mDescriptionView = (TextView) rootView.findViewById(R.id.detail_forecast_textview);
mHighTempView = (TextView) rootView.findViewById(R.id.detail_high_textview);
mLowTempView = (TextView) rootView.findViewById(R.id.detail_low_textview);
mHumidityView = (TextView) rootView.findViewById(R.id.detail_humidity_textview);
mWindView = (TextView) rootView.findViewById(R.id.detail_wind_textview);
mPressureView = (TextView) rootView.findViewById(R.id.detail_pressure_textview);
return rootView;
}
@Override
public void onResume() {
super.onResume();
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(DetailActivity.DATE_KEY) &&
mLocation != null &&
!mLocation.equals(Utility.getPreferredLocation(getActivity()))) {
getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.detailfragment, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// If onLoadFinished happens before this, we can go ahead and set the share intent now.
if (mForecast != null) {
mShareActionProvider.setShareIntent(createShareForecastIntent());
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast + FORECAST_SHARE_HASHTAG);
return shareIntent;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mLocation = savedInstanceState.getString(LOCATION_KEY);
}
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey(DetailActivity.DATE_KEY)) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATETEXT + " ASC";
mLocation = Utility.getPreferredLocation(getActivity());
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
mLocation, mDateStr);
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(
getActivity(),
weatherForLocationUri,
FORECAST_COLUMNS,
null,
null,
sortOrder
);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.moveToFirst()) {
// Read weather condition ID from cursor
int weatherId = data.getInt(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID));
// Use weather art image
mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId));
// Read date from cursor and update views for day of week and date
String date = data.getString(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DATETEXT));
String friendlyDateText = Utility.getDayName(getActivity(), date);
String dateText = Utility.getFormattedMonthDay(getActivity(), date);
mFriendlyDateView.setText(friendlyDateText);
mDateView.setText(dateText);
// Read description from cursor and update view
String description = data.getString(data.getColumnIndex(
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC));
mDescriptionView.setText(description);
// For accessibility, add a content description to the icon field
mIconView.setContentDescription(description);
// Read high temperature from cursor and update view
boolean isMetric = Utility.isMetric(getActivity());
double high = data.getDouble(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP));
String highString = Utility.formatTemperature(getActivity(), high, isMetric);
mHighTempView.setText(highString);
// Read low temperature from cursor and update view
double low = data.getDouble(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP));
String lowString = Utility.formatTemperature(getActivity(), low, isMetric);
mLowTempView.setText(lowString);
// Read humidity from cursor and update view
float humidity = data.getFloat(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_HUMIDITY));
mHumidityView.setText(getActivity().getString(R.string.format_humidity, humidity));
// Read wind speed and direction from cursor and update view
float windSpeedStr = data.getFloat(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED));
float windDirStr = data.getFloat(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DEGREES));
mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr));
// Read pressure from cursor and update view
float pressure = data.getFloat(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_PRESSURE));
mPressureView.setText(getActivity().getString(R.string.format_pressure, pressure));
// We still need this for the share intent
mForecast = String.format("%s - %s - %s/%s", dateText, description, high, low);
// If onCreateOptionsMenu has already happened, we need to update the share intent now.
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(createShareForecastIntent());
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) { }
}
| apache-2.0 |
tenten0213/todo | java-jax-rs/todo/src/main/java/tenten0213/entity/TodoEntity.java | 1279 | package tenten0213.entity;
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
@Table(name = "todo")
@NamedQuery(
name = "todo_findAll",
query = "select t from TodoEntity t order by t.updatedTime desc"
)
public class TodoEntity {
@Id @GeneratedValue @Column(name = "id")
private Long todoId;
@Column(nullable = false, length = 200)
private String descrption;
@Column(nullable = false)
private Boolean done;
@Column(nullable = false)
private Timestamp updatedTime;
public Timestamp getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Timestamp updatedTime) {
this.updatedTime = updatedTime;
}
public Long getTodoId() {
return todoId;
}
public void setTodoId(Long todoId) {
this.todoId = todoId;
}
public String getDescrption() {
return descrption;
}
public void setDescrption(String descrption) {
this.descrption = descrption;
}
public Boolean getDone() {
return done;
}
public void setDone(Boolean done) {
this.done = done;
}
@PrePersist
@PreUpdate
public void pre() {
this.updatedTime = new Timestamp(System.currentTimeMillis());
}
}
| apache-2.0 |
wyukawa/presto | presto-main/src/main/java/io/prestosql/sql/planner/optimizations/MetadataQueryOptimizer.java | 9407 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.sql.planner.optimizations;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import io.prestosql.Session;
import io.prestosql.SystemSessionProperties;
import io.prestosql.execution.warnings.WarningCollector;
import io.prestosql.metadata.Metadata;
import io.prestosql.metadata.TableProperties;
import io.prestosql.spi.connector.ColumnHandle;
import io.prestosql.spi.connector.ColumnMetadata;
import io.prestosql.spi.connector.DiscretePredicates;
import io.prestosql.spi.predicate.NullableValue;
import io.prestosql.spi.predicate.TupleDomain;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.planner.DeterminismEvaluator;
import io.prestosql.sql.planner.LiteralEncoder;
import io.prestosql.sql.planner.PlanNodeIdAllocator;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.SymbolAllocator;
import io.prestosql.sql.planner.TypeProvider;
import io.prestosql.sql.planner.plan.AggregationNode;
import io.prestosql.sql.planner.plan.AggregationNode.Aggregation;
import io.prestosql.sql.planner.plan.FilterNode;
import io.prestosql.sql.planner.plan.LimitNode;
import io.prestosql.sql.planner.plan.MarkDistinctNode;
import io.prestosql.sql.planner.plan.PlanNode;
import io.prestosql.sql.planner.plan.ProjectNode;
import io.prestosql.sql.planner.plan.SimplePlanRewriter;
import io.prestosql.sql.planner.plan.SortNode;
import io.prestosql.sql.planner.plan.TableScanNode;
import io.prestosql.sql.planner.plan.TopNNode;
import io.prestosql.sql.planner.plan.ValuesNode;
import io.prestosql.sql.tree.Expression;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static java.util.Objects.requireNonNull;
/**
* Converts cardinality-insensitive aggregations (max, min, "distinct") over partition keys
* into simple metadata queries
*/
public class MetadataQueryOptimizer
implements PlanOptimizer
{
private static final Set<String> ALLOWED_FUNCTIONS = ImmutableSet.of("max", "min", "approx_distinct");
private final Metadata metadata;
private final LiteralEncoder literalEncoder;
public MetadataQueryOptimizer(Metadata metadata)
{
requireNonNull(metadata, "metadata is null");
this.metadata = metadata;
this.literalEncoder = new LiteralEncoder(metadata);
}
@Override
public PlanNode optimize(PlanNode plan, Session session, TypeProvider types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, WarningCollector warningCollector)
{
if (!SystemSessionProperties.isOptimizeMetadataQueries(session)) {
return plan;
}
return SimplePlanRewriter.rewriteWith(new Optimizer(session, metadata, literalEncoder, idAllocator), plan, null);
}
private static class Optimizer
extends SimplePlanRewriter<Void>
{
private final PlanNodeIdAllocator idAllocator;
private final Session session;
private final Metadata metadata;
private final LiteralEncoder literalEncoder;
private Optimizer(Session session, Metadata metadata, LiteralEncoder literalEncoder, PlanNodeIdAllocator idAllocator)
{
this.session = session;
this.metadata = metadata;
this.literalEncoder = literalEncoder;
this.idAllocator = idAllocator;
}
@Override
public PlanNode visitAggregation(AggregationNode node, RewriteContext<Void> context)
{
// supported functions are only MIN/MAX/APPROX_DISTINCT or distinct aggregates
for (Aggregation aggregation : node.getAggregations().values()) {
if (!ALLOWED_FUNCTIONS.contains(aggregation.getSignature().getName()) && !aggregation.isDistinct()) {
return context.defaultRewrite(node);
}
}
Optional<TableScanNode> result = findTableScan(node.getSource());
if (!result.isPresent()) {
return context.defaultRewrite(node);
}
// verify all outputs of table scan are partition keys
TableScanNode tableScan = result.get();
ImmutableMap.Builder<Symbol, Type> typesBuilder = ImmutableMap.builder();
ImmutableMap.Builder<Symbol, ColumnHandle> columnBuilder = ImmutableMap.builder();
List<Symbol> inputs = tableScan.getOutputSymbols();
for (Symbol symbol : inputs) {
ColumnHandle column = tableScan.getAssignments().get(symbol);
ColumnMetadata columnMetadata = metadata.getColumnMetadata(session, tableScan.getTable(), column);
typesBuilder.put(symbol, columnMetadata.getType());
columnBuilder.put(symbol, column);
}
Map<Symbol, ColumnHandle> columns = columnBuilder.build();
Map<Symbol, Type> types = typesBuilder.build();
// Materialize the list of partitions and replace the TableScan node
// with a Values node
TableProperties layout = metadata.getTableProperties(session, tableScan.getTable());
if (!layout.getDiscretePredicates().isPresent()) {
return context.defaultRewrite(node);
}
DiscretePredicates predicates = layout.getDiscretePredicates().get();
// the optimization is only valid if the aggregation node only relies on partition keys
if (!predicates.getColumns().containsAll(columns.values())) {
return context.defaultRewrite(node);
}
ImmutableList.Builder<List<Expression>> rowsBuilder = ImmutableList.builder();
for (TupleDomain<ColumnHandle> domain : predicates.getPredicates()) {
if (!domain.isNone()) {
Map<ColumnHandle, NullableValue> entries = TupleDomain.extractFixedValues(domain).get();
ImmutableList.Builder<Expression> rowBuilder = ImmutableList.builder();
// for each input column, add a literal expression using the entry value
for (Symbol input : inputs) {
ColumnHandle column = columns.get(input);
Type type = types.get(input);
NullableValue value = entries.get(column);
if (value == null) {
// partition key does not have a single value, so bail out to be safe
return context.defaultRewrite(node);
}
else {
rowBuilder.add(literalEncoder.toExpression(value.getValue(), type));
}
}
rowsBuilder.add(rowBuilder.build());
}
}
// replace the tablescan node with a values node
ValuesNode valuesNode = new ValuesNode(idAllocator.getNextId(), inputs, rowsBuilder.build());
return SimplePlanRewriter.rewriteWith(new Replacer(valuesNode), node);
}
private static Optional<TableScanNode> findTableScan(PlanNode source)
{
while (true) {
// allow any chain of linear transformations
if (source instanceof MarkDistinctNode ||
source instanceof FilterNode ||
source instanceof LimitNode ||
source instanceof TopNNode ||
source instanceof SortNode) {
source = source.getSources().get(0);
}
else if (source instanceof ProjectNode) {
// verify projections are deterministic
ProjectNode project = (ProjectNode) source;
if (!Iterables.all(project.getAssignments().getExpressions(), DeterminismEvaluator::isDeterministic)) {
return Optional.empty();
}
source = project.getSource();
}
else if (source instanceof TableScanNode) {
return Optional.of((TableScanNode) source);
}
else {
return Optional.empty();
}
}
}
}
private static class Replacer
extends SimplePlanRewriter<Void>
{
private final ValuesNode replacement;
private Replacer(ValuesNode replacement)
{
this.replacement = replacement;
}
@Override
public PlanNode visitTableScan(TableScanNode node, RewriteContext<Void> context)
{
return replacement;
}
}
}
| apache-2.0 |
nikolskayaos/java_tests | sandbox/src/main/java/ru/sandbox/Collections.java | 500 | package ru.sandbox;
import java.util.ArrayList;
import java.util.List;
public class Collections {
public static void main (String[] args){
List<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Swing");
languages.add("Python");
languages.add("PHP");
for (String l : languages){
System.out.println("I want to learn " + l);
}
System.out.println("Size of collection " + languages.size());
}
}
| apache-2.0 |
miswenwen/My_bird_work | Bird_work/我的项目/Settings/ext/src/com/mediatek/settings/ext/IStatusExt.java | 449 | package com.mediatek.settings.ext;
import android.preference.PreferenceScreen;
public interface IStatusExt {
/**
* customize imei & imei sv display name.
* @param imeikey: the name of imei
* @param imeiSvKey: the name of imei software version
* @param parent: parent preference
* @param slotId: slot id
* @internal
*/
void customizeImei(String imeiKey, String imeiSvKey, PreferenceScreen parent, int slotId);
}
| apache-2.0 |
santhosh-tekuri/jlibs | greplog/src/main/java/jlibs/util/logging/FieldCondition.java | 1105 | /**
* Copyright 2015 Santhosh Kumar Tekuri
*
* The JLibs authors license 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 jlibs.util.logging;
import java.util.regex.Pattern;
/**
* @author Santhosh Kumar T
*/
public class FieldCondition implements Condition{
public final Pattern pattern;
public final int index;
public FieldCondition(Pattern pattern, int index){
this.pattern = pattern;
this.index = index;
}
@Override
public boolean matches(LogRecord record){
return pattern.matcher(record.fields[index]).matches();
}
}
| apache-2.0 |
gabedwrds/cas | api/cas-server-core-api-events/src/main/java/org/apereo/cas/support/events/CasConfigurationModifiedEvent.java | 643 | package org.apereo.cas.support.events;
import java.nio.file.Path;
/**
* This is {@link CasConfigurationModifiedEvent}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
public class CasConfigurationModifiedEvent extends AbstractCasEvent {
private static final long serialVersionUID = -5738763037210896455L;
private final Path file;
/**
* Instantiates a new Abstract cas sso event.
*
* @param source the source
*/
public CasConfigurationModifiedEvent(final Object source, final Path file) {
super(source);
this.file = file;
}
public Path getFile() {
return file;
}
}
| apache-2.0 |
pkware/truth-android | truth-android/src/main/java/com/pkware/truth/android/widget/AbstractHorizontalScrollViewSubject.java | 1831 | /*
* Copyright 2013 Square, Inc.
* Copyright 2016 PKWARE, 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.pkware.truth.android.widget;
import android.widget.HorizontalScrollView;
import com.google.common.truth.FailureMetadata;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public abstract class AbstractHorizontalScrollViewSubject<T extends HorizontalScrollView>
extends AbstractFrameLayoutSubject<T> {
@Nullable
private final T actual;
protected AbstractHorizontalScrollViewSubject(@Nonnull FailureMetadata failureMetadata, @Nullable T actual) {
super(failureMetadata, actual);
this.actual = actual;
}
public void hasMaximumScrollAmount(int amount) {
check("getMaxScrollAmount()").that(actual.getMaxScrollAmount()).isEqualTo(amount);
}
public void isFillingViewport() {
check("isFillViewport()").that(actual.isFillViewport()).isTrue();
}
public void isNotFillingViewport() {
check("isFillViewport()").that(actual.isFillViewport()).isFalse();
}
public void isSmoothScrollingEnabled() {
check("isSmoothScrollingEnabled()").that(actual.isSmoothScrollingEnabled()).isTrue();
}
public void isSmoothScrollingDisabled() {
check("isSmoothScrollingEnabled()").that(actual.isSmoothScrollingEnabled()).isFalse();
}
}
| apache-2.0 |
qinannmj/FireFly | src/main/java/cn/com/sparkle/firefly/net/netlayer/raptor/RaptorServer.java | 2449 | package cn.com.sparkle.firefly.net.netlayer.raptor;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import cn.com.sparkle.firefly.net.netlayer.NetHandler;
import cn.com.sparkle.firefly.net.netlayer.NetServer;
import cn.com.sparkle.raptor.core.handler.IoHandler;
import cn.com.sparkle.raptor.core.protocol.CodecHandler;
import cn.com.sparkle.raptor.core.protocol.MultiThreadHandler;
import cn.com.sparkle.raptor.core.transport.socket.nio.NioSocketConfigure;
import cn.com.sparkle.raptor.core.transport.socket.nio.NioSocketServer;
public class RaptorServer implements NetServer {
private final static AtomicInteger INSTANCE_NUM = new AtomicInteger(0);
private NioSocketServer server;
private IoHandler handler;
private String ip = null;
private int port;
@Override
public void init(String confPath, int heartBeatInterval, NetHandler netHandler,String ip,int port, String threadName) throws IOException {
this.ip = ip;
this.port = port;
Conf conf = new Conf(confPath);
NioSocketConfigure nsc = new NioSocketConfigure();
nsc.setProcessorNum(conf.getIothreadnum());
nsc.setTcpNoDelay(true);
nsc.setClearTimeoutSessionInterval(2 * heartBeatInterval);
nsc.setCycleRecieveBuffCellSize(conf.getCycleRecieveCell());
nsc.setRecieveBuffSize(conf.getRecieveBuffSize());
nsc.setSentBuffSize(conf.getSendBuffSize());
nsc.setBackLog(conf.getBacklog());
server = new NioSocketServer(nsc, threadName);
String workthreadName = threadName + INSTANCE_NUM.incrementAndGet();
if (conf.getWorkthreadMaxNum() == 0) {
handler = new CodecHandler(conf.getCycleSendCell(), conf.getCycleSendBuffSize(), new BufProtocol(), new RaptorHandler(netHandler));
} else {
handler = new MultiThreadHandler(conf.getWorkthreadMinNum(), conf.getWorkthreadMaxNum(), 60, TimeUnit.SECONDS, new CodecHandler(
conf.getCycleSendCell(), conf.getCycleSendBuffSize(), new BufProtocol(), new RaptorHandler(netHandler)), workthreadName);
}
}
@Override
public void listen() throws UnknownHostException, IOException {
if(ip == null) {
throw new RuntimeException("Not initialize the server!Please run init method!");
}
server.waitToBind(new InetSocketAddress(InetAddress.getByName(ip), port), handler);
}
}
| apache-2.0 |
tomzo/gocd | plugin-infra/go-plugin-config-repo/src/main/java/com/thoughtworks/go/plugin/configrepo/contract/CRPipeline.java | 14156 | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.plugin.configrepo.contract;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.plugin.configrepo.contract.material.CRMaterial;
import com.thoughtworks.go.plugin.configrepo.contract.material.SourceCodeMaterial;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.text.MessageFormat;
import java.util.*;
public class CRPipeline extends CRBase {
private String group;
private String name;
private int display_order_weight = -1;
private String label_template;
private String lock_behavior;
private CRTrackingTool tracking_tool;
private CRMingle mingle;
private CRTimer timer;
private Collection<CREnvironmentVariable> environment_variables = new ArrayList<>();
private Collection<CRParameter> parameters = new ArrayList<>();
private Collection<CRMaterial> materials = new ArrayList<>();
private List<CRStage> stages = new ArrayList<>();
private String template;
public CRPipeline(){}
public CRPipeline(String name, String groupName, CRMaterial material, String template, CRStage... stages)
{
this.name = name;
this.group = groupName;
this.template = template;
this.materials.add(material);
this.stages = Arrays.asList(stages);
}
public CRPipeline(String name, String groupName, String labelTemplate, String lockBehavior, CRTrackingTool trackingTool,
CRMingle mingle, CRTimer timer, Collection<CREnvironmentVariable> environmentVariables,
Collection<CRMaterial> materials, List<CRStage> stages, String template, Collection<CRParameter> parameters) {
this.name = name;
this.group = groupName;
this.label_template = labelTemplate;
this.lock_behavior = lockBehavior;
this.tracking_tool = trackingTool;
this.mingle = mingle;
this.timer = timer;
this.environment_variables = environmentVariables;
this.materials = materials;
this.stages = stages;
this.template = template;
this.parameters = parameters;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLabelTemplate() {
return label_template;
}
public void setLabelTemplate(String labelTemplate) {
this.label_template = labelTemplate;
}
public String lockBehavior() {
return lock_behavior;
}
public CRTrackingTool getTrackingTool() {
return tracking_tool;
}
public void setTrackingTool(CRTrackingTool trackingTool) {
this.tracking_tool = trackingTool;
}
public CRMingle getMingle() {
return mingle;
}
public void setMingle(CRMingle mingle) {
this.mingle = mingle;
}
public CRTimer getTimer() {
return timer;
}
public void setTimer(CRTimer timer) {
this.timer = timer;
}
public Collection<CREnvironmentVariable> getEnvironmentVariables() {
return environment_variables;
}
public void setEnvironmentVariables(Collection<CREnvironmentVariable> environmentVariables) {
this.environment_variables = environmentVariables;
}
public boolean hasEnvironmentVariable(String key) {
for (CREnvironmentVariable var: environment_variables) {
if (var.getName().equals(key)) {
return true;
}
}
return false;
}
public Collection<CRParameter> getParameters() {
return parameters;
}
public void setParameters(Collection<CRParameter> parameters) {
this.parameters = parameters;
}
public Collection<CRMaterial> getMaterials() {
return materials;
}
public CRMaterial getMaterialByName(String name)
{
if(this.materials == null)
return null;
for(CRMaterial m : this.materials)
{
if(m.getName().equals(name))
return m;
}
return null;
}
public void setMaterials(Collection<CRMaterial> materials) {
this.materials = materials;
}
public List<CRStage> getStages() {
return stages;
}
public void setStages(List<CRStage> stages) {
this.stages = stages;
}
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
public void addMaterial(CRMaterial material) {
this.materials.add(material);
}
public void addStage(CRStage stage) {
this.stages.add(stage);
}
public void addParameter (CRParameter param) {
this.parameters.add(param);
}
public void addEnvironmentVariable(String key,String value) {
CREnvironmentVariable variable = new CREnvironmentVariable(key);
variable.setValue(value);
this.environment_variables.add(variable);
}
public void addEnvironmentVariable(CREnvironmentVariable variable) {
this.environment_variables.add(variable);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CRPipeline that = (CRPipeline) o;
if (label_template != null ? !label_template.equals(that.label_template) : that.label_template != null) {
return false;
}
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
if (group != null ? !group.equals(that.group) : that.group != null) {
return false;
}
if (timer != null ? !timer.equals(that.timer) : that.timer != null) {
return false;
}
if (tracking_tool != null ? !tracking_tool.equals(that.tracking_tool) : that.tracking_tool != null) {
return false;
}
if (mingle != null ? !mingle.equals(that.mingle) : that.mingle != null) {
return false;
}
if (materials != null ? !CollectionUtils.isEqualCollection(materials, that.materials) : that.materials != null) {
return false;
}
if (stages != null ? !CollectionUtils.isEqualCollection(stages, that.stages) : that.stages != null) {
return false;
}
if (environment_variables != null ? !CollectionUtils.isEqualCollection(environment_variables,that.environment_variables) : that.environment_variables != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (group != null ? group.hashCode() : 0);
result = 31 * result + (label_template != null ? label_template.hashCode() : 0);
result = 31 * result + (mingle != null ? mingle.hashCode() : 0);
result = 31 * result + (tracking_tool != null ? tracking_tool.hashCode() : 0);
result = 31 * result + (materials != null ? materials.size() : 0);
result = 31 * result + (stages != null ? stages.size() : 0);
result = 31 * result + (environment_variables != null ? environment_variables.size() : 0);
result = 31 * result + (timer != null ? timer.hashCode() : 0);
return result;
}
public String getGroupName() {
return group;
}
public void setGroupName(String groupName) {
this.group = groupName;
}
@Override
public String getLocation(String parent) {
return StringUtils.isBlank(location) ?
StringUtils.isBlank(name) ? String.format("Pipeline in %s",parent) :
String.format("Pipeline %s",name) : String.format("%s; Pipeline %s",location,name);
}
@Override
public void getErrors(ErrorCollection errors, String parentLocation) {
String location = this.getLocation(parentLocation);
errors.checkMissing(location,"name",name);
errors.checkMissing(location,"group",group);
errors.checkMissing(location,"materials",materials);
validateAtLeastOneMaterial(errors,location);
if(materials != null) {
for (CRMaterial material : this.materials) {
material.getErrors(errors, location);
}
if (materials.size() > 1) {
validateMaterialNameUniqueness(errors, location);
validateScmMaterials(errors,location);
}
}
validateTemplateOrStages(errors, location);
if (!hasTemplate()) {
validateAtLeastOneStage(errors,location);
if(stages != null){
for (CRStage stage : this.stages) {
stage.getErrors(errors, location);
}
if (stages.size() > 1) {
validateStageNameUniqueness(errors, location);
}
}
}
validateEnvironmentVariableUniqueness(errors, location);
validateParamNameUniqueness(errors, location);
validateLockBehaviorValue(errors, location);
}
private void validateLockBehaviorValue(ErrorCollection errors, String location) {
if (lock_behavior != null && !PipelineConfig.VALID_LOCK_VALUES.contains(lock_behavior)) {
errors.addError(location, MessageFormat.format("Lock behavior has an invalid value ({0}). Valid values are: {1}",
lock_behavior, PipelineConfig.VALID_LOCK_VALUES));
}
}
private void validateEnvironmentVariableUniqueness(ErrorCollection errors, String location) {
HashSet<String> keys = new HashSet<>();
for(CREnvironmentVariable var : environment_variables)
{
String error = var.validateNameUniqueness(keys);
if(error != null)
errors.addError(location,error);
}
}
private void validateParamNameUniqueness(ErrorCollection errors, String location) {
HashSet<String> keys = new HashSet<>();
for(CRParameter param : parameters)
{
String error = param.validateNameUniqueness(keys);
if(error != null)
errors.addError(location,error);
}
}
private void validateScmMaterials(ErrorCollection errors, String pipelineLocation) {
List<SourceCodeMaterial> allSCMMaterials = filterScmMaterials();
if (allSCMMaterials.size() > 1) {
for (SourceCodeMaterial material : allSCMMaterials) {
String directory = material.getDestination();
if (StringUtils.isBlank(directory)) {
String location = material.getLocation(pipelineLocation);
errors.addError(location,"Material must have destination directory when there are many SCM materials");
}
}
}
}
private List<SourceCodeMaterial> filterScmMaterials() {
List<SourceCodeMaterial> scmMaterials = new ArrayList<>();
for (CRMaterial material : this.materials) {
if (material instanceof SourceCodeMaterial) {
scmMaterials.add((SourceCodeMaterial) material);
}
}
return scmMaterials;
}
private void validateStageNameUniqueness(ErrorCollection errors, String location) {
HashSet<String> keys = new HashSet<>();
for(CRStage stage : stages)
{
String error = stage.validateNameUniqueness(keys);
if(error != null)
errors.addError(location,error);
}
}
private void validateMaterialNameUniqueness(ErrorCollection errors, String location) {
HashSet<String> keys = new HashSet<>();
for(CRMaterial material1 : materials)
{
String error = material1.validateNameUniqueness(keys);
if(error != null)
errors.addError(location,error);
}
}
private void validateAtLeastOneStage(ErrorCollection errors, String location) {
if(!hasStages())
errors.addError(location,"Pipeline has no stages.");
}
private boolean hasStages() {
return !(this.stages == null || this.stages.isEmpty());
}
private void validateTemplateOrStages(ErrorCollection errors, String location) {
if (!hasTemplate() && !hasStages()) {
errors.addError(location, "Pipeline has to define stages or template.");
}
else if (hasTemplate() && hasStages()) {
errors.addError(location, "Pipeline has to either define stages or template. Not both.");
}
}
private void validateAtLeastOneMaterial(ErrorCollection errors, String location) {
if(this.materials == null || this.materials.isEmpty())
errors.addError(location,"Pipeline has no materials.");
}
public boolean hasTemplate() {
return template != null && !StringUtils.isBlank(template);
}
public String getLock_behavior() {
return lock_behavior;
}
public void setLock_behavior(String lock_behavior) {
this.lock_behavior = lock_behavior;
}
public void setDisplayOrderWeight(int display_order_weight) {
this.display_order_weight = display_order_weight;
}
public int getDisplayOrderWeight() {
return display_order_weight;
}
}
| apache-2.0 |
phimpme/android-prototype | app/src/main/java/org/fossasia/phimpme/share/imgur/ImgurPicUploadReq.java | 364 | package org.fossasia.phimpme.share.imgur;
public class ImgurPicUploadReq {
String image;
String caption;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
}
| apache-2.0 |
wangtonghe/learn-sample | src/main/java/com/wthfeng/learn/lang/ForEachTest.java | 220 | package com.wthfeng.learn.lang;
import org.junit.Test;
/**
* @author wangtonghe
* @date 2017/11/14 11:05
*/
public class ForEachTest {
@Test
public void test(){
int[] arr = {1,4,5,6,2,3};
}
}
| apache-2.0 |
liudih/rabbitmq | rabbitmq-consumer/src/main/java/com/rabbit/dto/transfer/product/AttributeItem.java | 1051 | package com.rabbit.dto.transfer.product;
public class AttributeItem {
Integer keyId;
String key;
Integer valueId;
String value;
Integer languangeId;
Boolean showImg;
Boolean visible;
public Integer getKeyId() {
return keyId;
}
public void setKeyId(Integer keyId) {
this.keyId = keyId;
}
public Integer getValueId() {
return valueId;
}
public void setValueId(Integer valueId) {
this.valueId = valueId;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getLanguangeId() {
return languangeId;
}
public void setLanguangeId(Integer languangeId) {
this.languangeId = languangeId;
}
public Boolean getShowImg() {
return showImg;
}
public void setShowImg(Boolean showImg) {
this.showImg = showImg;
}
public Boolean getVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
}
| apache-2.0 |
KEOpenSource/CAExplorer | cellularAutomata/util/graphics/SpinningIconJOptionPane.java | 4863 | /*
SpinningIconJOptionPane -- a class within the Cellular Automaton Explorer.
Copyright (C) 2007 David B. Bahr (http://academic.regis.edu/dbahr/)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package cellularAutomata.util.graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.interpolation.PropertySetter;
import cellularAutomata.util.math.RandomSingleton;
/**
* Creates a JOptionPane with an icon that spins.
*
* @author David Bahr
*/
public class SpinningIconJOptionPane extends JOptionPane implements
MouseListener
{
// the number of milliseconds that the icon spins.
private final static int SPIN_TIME = 6000;
// the class that animates the spinning
private Animator animator = null;
// the degree of spin of the icon.
private float rotation = 0;
// used to decide how far the icon should rotate
private Random random = RandomSingleton.getInstance();
/**
* Create a JOptionPane with an icon that spins.
*/
public SpinningIconJOptionPane(Object message, int messageType,
int optionType, RotatedImageIcon icon, Object[] options, Object initialValue)
{
super(message, messageType, optionType, icon, options, initialValue);
// so user can click and spin the icon
this.addMouseListener(this);
}
/**
* Makes the icon start spinning.
*/
public void startSpin()
{
// stop any previous fading
if(animator != null)
{
animator.stop();
}
// rotate by 360 degrees plus some random amount (so stops in a random
// position)
float amountOfRotation = 360.0f + (360.0f * random.nextFloat());
// This keeps changing the degree of rotation of the icon.
PropertySetter setter = new PropertySetter(this, "rotation", rotation,
rotation + amountOfRotation);
animator = new Animator(SPIN_TIME, setter);
// speed up then slow down the spinning
animator.setAcceleration(0.1f);
animator.setDeceleration(0.5f);
// start the animation
animator.start();
}
/**
* Makes the icon stop spinning.
*/
public void stopSpin()
{
// stop any previous spinning
if(animator != null)
{
animator.stop();
}
}
/**
* Get the degree of rotation.
*
* @return The degree of rotation (0.0f to 1.0f).
*/
public float getRotation()
{
return rotation;
}
/**
* Set the degree of rotation of the icon.
*
* @param rotation
* The rotation in degrees (for example, 0.0 to 360.0).
*/
public void setRotation(float rotation)
{
this.rotation = rotation;
// this tells the icon to paint itself in this rotated position
RotatedImageIcon icon = (RotatedImageIcon) this.getIcon();
icon.setRotation(rotation);
// and when repainting this JOptionPane, it automatically calls the icon
// and asks it to repaint itself (by calling paintIcon(), which is
// overridden in RotatedImageIcon to paint in the rotated position).
repaint();
}
/**
* Starts spinning the icon if (1) it has stopped and (2) the user clicks on
* the panel.
*/
public void mouseClicked(MouseEvent e)
{
if((animator != null) && !animator.isRunning())
{
startSpin();
}
}
/**
* Does nothing.
*/
public void mousePressed(MouseEvent e)
{
}
/**
* Does nothing.
*/
public void mouseReleased(MouseEvent e)
{
}
/**
* Does nothing.
*/
public void mouseEntered(MouseEvent e)
{
}
/**
* Does nothing.
*/
public void mouseExited(MouseEvent e)
{
}
}
| apache-2.0 |
rometools/rome | rome-core/src/main/java/com/rometools/rome/io/SyndFeedOutput.java | 8632 | /*
* Copyright 2004 Sun Microsystems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.rometools.rome.io;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import org.jdom2.Document;
import com.rometools.rome.feed.synd.SyndFeed;
/**
* Generates an XML document (String, File, OutputStream, Writer, W3C DOM document or JDOM document)
* out of an SyndFeedImpl..
* <p>
* It delegates to a WireFeedOutput to generate all feed types.
*/
public class SyndFeedOutput {
private final WireFeedOutput feedOutput = new WireFeedOutput();
/**
* Creates a String with the XML representation for the given SyndFeedImpl.
* <p>
* If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It is
* the responsibility of the developer to ensure that if the String is written to a character
* stream the stream charset is the same as the feed encoding property.
* <p>
*
* @param feed Abstract feed to create XML representation from. The type of the SyndFeedImpl
* must match the type given to the FeedOuptut constructor.
* @return a String with the XML representation for the given SyndFeedImpl.
* @throws FeedException thrown if the XML representation for the feed could not be created.
*
*/
public String outputString(final SyndFeed feed) throws FeedException {
return feedOutput.outputString(feed.createWireFeed());
}
/**
* Creates a String with the XML representation for the given SyndFeedImpl.
* <p>
* If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It is
* the responsibility of the developer to ensure that if the String is written to a character
* stream the stream charset is the same as the feed encoding property.
* <p>
*
* @param feed Abstract feed to create XML representation from. The type of the SyndFeedImpl
* must match the type given to the FeedOuptut constructor.
* @param prettyPrint pretty-print XML (true) oder collapsed
* @return a String with the XML representation for the given SyndFeedImpl.
* @throws FeedException thrown if the XML representation for the feed could not be created.
*
*/
public String outputString(final SyndFeed feed, final boolean prettyPrint) throws FeedException {
return feedOutput.outputString(feed.createWireFeed(), prettyPrint);
}
/**
* Creates a File containing with the XML representation for the given SyndFeedImpl.
* <p>
* If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. The
* platform default charset encoding is used to write the feed to the file. It is the
* responsibility of the developer to ensure the feed encoding is set to the platform charset
* encoding.
* <p>
*
* @param feed Abstract feed to create XML representation from. The type of the SyndFeedImpl
* must match the type given to the FeedOuptut constructor.
* @param file the file where to write the XML representation for the given SyndFeedImpl.
* @throws IOException thrown if there was some problem writing to the File.
* @throws FeedException thrown if the XML representation for the feed could not be created.
*
*/
public void output(final SyndFeed feed, final File file) throws IOException, FeedException {
feedOutput.output(feed.createWireFeed(), file);
}
/**
* Creates a File containing with the XML representation for the given SyndFeedImpl.
* <p>
* If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. The
* platform default charset encoding is used to write the feed to the file. It is the
* responsibility of the developer to ensure the feed encoding is set to the platform charset
* encoding.
* <p>
*
* @param feed Abstract feed to create XML representation from. The type of the SyndFeedImpl
* must match the type given to the FeedOuptut constructor.
* @param prettyPrint pretty-print XML (true) oder collapsed
* @param file the file where to write the XML representation for the given SyndFeedImpl.
* @throws IOException thrown if there was some problem writing to the File.
* @throws FeedException thrown if the XML representation for the feed could not be created.
*
*/
public void output(final SyndFeed feed, final File file, final boolean prettyPrint) throws IOException, FeedException {
feedOutput.output(feed.createWireFeed(), file, prettyPrint);
}
/**
* Writes to an Writer the XML representation for the given SyndFeedImpl.
* <p>
* If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It is
* the responsibility of the developer to ensure that if the String is written to a character
* stream the stream charset is the same as the feed encoding property.
* <p>
*
* @param feed Abstract feed to create XML representation from. The type of the SyndFeedImpl
* must match the type given to the FeedOuptut constructor.
* @param writer Writer to write the XML representation for the given SyndFeedImpl.
* @throws IOException thrown if there was some problem writing to the Writer.
* @throws FeedException thrown if the XML representation for the feed could not be created.
*
*/
public void output(final SyndFeed feed, final Writer writer) throws IOException, FeedException {
feedOutput.output(feed.createWireFeed(), writer);
}
/**
* Writes to an Writer the XML representation for the given SyndFeedImpl.
* <p>
* If the feed encoding is not NULL, it will be used in the XML prolog encoding attribute. It is
* the responsibility of the developer to ensure that if the String is written to a character
* stream the stream charset is the same as the feed encoding property.
* <p>
*
* @param feed Abstract feed to create XML representation from. The type of the SyndFeedImpl
* must match the type given to the FeedOuptut constructor.
* @param prettyPrint pretty-print XML (true) oder collapsed
* @param writer Writer to write the XML representation for the given SyndFeedImpl.
* @throws IOException thrown if there was some problem writing to the Writer.
* @throws FeedException thrown if the XML representation for the feed could not be created.
*
*/
public void output(final SyndFeed feed, final Writer writer, final boolean prettyPrint) throws IOException, FeedException {
feedOutput.output(feed.createWireFeed(), writer, prettyPrint);
}
/**
* Creates a W3C DOM document for the given SyndFeedImpl.
* <p>
* This method does not use the feed encoding property.
* <p>
*
* @param feed Abstract feed to create W3C DOM document from. The type of the SyndFeedImpl must
* match the type given to the FeedOuptut constructor.
* @return the W3C DOM document for the given SyndFeedImpl.
* @throws FeedException thrown if the W3C DOM document for the feed could not be created.
*
*/
public org.w3c.dom.Document outputW3CDom(final SyndFeed feed) throws FeedException {
return feedOutput.outputW3CDom(feed.createWireFeed());
}
/**
* Creates a JDOM document for the given SyndFeedImpl.
* <p>
* This method does not use the feed encoding property.
* <p>
*
* @param feed Abstract feed to create JDOM document from. The type of the SyndFeedImpl must
* match the type given to the FeedOuptut constructor.
* @return the JDOM document for the given SyndFeedImpl.
* @throws FeedException thrown if the JDOM document for the feed could not be created.
*
*/
public Document outputJDom(final SyndFeed feed) throws FeedException {
return feedOutput.outputJDom(feed.createWireFeed());
}
}
| apache-2.0 |
multilateralis/android-furk-app | app/src/main/java/io/github/multilateralis/android_furk_app/Furk.java | 16408 | package io.github.multilateralis.android_furk_app;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import io.github.multilateralis.android_furk_app.adapter.ActiveFilesAdapter;
import io.github.multilateralis.android_furk_app.adapter.FilesAdapter;
import io.github.multilateralis.android_furk_app.adapter.MyFilesAdapter;
public class Furk extends AppCompatActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks,OnQueryTextListener,APIClient.APICallback {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private int mPosition = -1;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private boolean refreshing;
private boolean collapseSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
refreshing = false;
collapseSearch = false;
setContentView(R.layout.activity_furk);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
handleIntent();
}
private void handleIntent() {
if (getIntent().getAction() != null && getIntent().getAction().equals("io.github.multilateralis.android_furk_app.TORRENT_SEARCH")) {
torrentSearch();
}
else if (getIntent().getScheme() != null) {
addTorrent(getIntent().getScheme());
}
}
private void addTorrent(String scheme) {
String url = getIntent().getDataString();
if(scheme.contains("magnet")) {
try {
url = java.net.URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
HashMap<String, String> params = new HashMap<String, String>();
params.put("url", url);
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Adding torrent");
dialog.setIndeterminate(true);
dialog.show();
APIClient.get(this, "dl/add", params, this, dialog);
}
private void torrentSearch() {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Searching episode");
dialog.setIndeterminate(true);
dialog.show();
String url = getIntent().getDataString();
Ion.with(this, url)
.asString()
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
int start = result.indexOf("<torrent:infoHash>") + "<torrent:infoHash>".length();
int end = result.indexOf("</torrent:infoHash>");
if (start < end) {
String hashInfo = result.substring(start, end);
HashMap<String, String> params = new HashMap<String, String>();
params.put("url", hashInfo);
APIClient.get(Furk.this, "dl/add", params, Furk.this, dialog);
} else {
String query = getIntent().getExtras().getString("query");
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
intent.setData(Uri.parse("http://thepiratebay.se/search/"+ URLEncoder.encode(query,"UTF-8")+"/0/0/1"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
finally {
dialog.dismiss();
startActivity(intent);
}
}
}
});
}
@Override
public void onBackPressed() {
if(mPosition != 0){
switchFragment(0);
}
else {
super.onBackPressed();
}
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
switchFragment(position);
}
private void switchFragment(int position){
if(mPosition == position) return;
if(position == 2)
{
mPosition = 2;
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, new SettingsFragment(),"CURRENT")
.commit();
}
else if(position == 1)
{
mPosition = 1;
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, new ActiveFilesFragment(),"CURRENT")
.commit();
}
else
{
mPosition = 0;
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, new MyFilesFragment(),"CURRENT")
.commit();
}
}
public CharSequence getFragmentTitle() {
switch (mPosition) {
case 0:
return getString(R.string.title_section1);
case 1:
return getString(R.string.title_section2);
case 2:
return getString(R.string.title_section3);
case 3:
return getString(R.string.title_section4);
default:
return getTitle();
}
}
public void setRefreshing()
{
refreshing = true;
invalidateOptionsMenu();
}
public void doneRefrshing()
{
refreshing = false;
invalidateOptionsMenu();
}
private void refreshCurrentFragmet()
{
FragmentManager fragmentManager = getFragmentManager();
Fragment currentFragment = fragmentManager.findFragmentByTag("CURRENT");
if(currentFragment.getClass().equals(MyFilesFragment.class))
{
((MyFilesFragment)currentFragment).refresh();
}
else if(currentFragment.getClass().equals(ActiveFilesFragment.class))
{
((ActiveFilesFragment)currentFragment).refresh();
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
if(actionBar == null) return;
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setHomeAsUpIndicator(R.drawable.ic_action_menu);
actionBar.setTitle(getFragmentTitle());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
restoreActionBar();
if(mPosition != 2 ) {
getMenuInflater().inflate(R.menu.furk, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnQueryTextListener(this);
searchView.setIconifiedByDefault(false);
searchView.setQueryHint("Search Furk.net");
return true;
}
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu (Menu menu)
{
//MenuItem refreshButton = (MenuItem)findViewById(R.id.action_refresh);
MenuItem refreshButton = menu.findItem(R.id.action_refresh);
if(refreshButton != null)
{
if(refreshing)
{
refreshButton.setActionView(R.layout.actionbar_refresh_progress);
}
else
{
refreshButton.setActionView(null);
}
if(collapseSearch)
{
MenuItem search = menu.findItem(R.id.action_search);
search.collapseActionView();
collapseSearch = false;
}
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_search) {
onSearchRequested();
return true;
}
else if(id == R.id.action_refresh)
{
//item.setActionView(R.layout.actionbar_refresh_progress);
refreshCurrentFragmet();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onQueryTextSubmit(String s) {
collapseSearch = true;
invalidateOptionsMenu();
Intent intent = new Intent(this,SearchActivity.class);
intent.putExtra("query",s);
startActivityForResult(intent,2);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
@Override
public void processAPIResponse(JSONObject response) {
try {
if(response.getString("status").equals("ok"))
{
if(response.has("files"))
{
JSONArray files = response.getJSONArray("files");
if(files.length() > 0)
{
try {
files.getJSONObject(0).getString("url_dl");
Intent intent = new Intent(this, FileActivity.class);
intent.putExtra("file", files.getJSONObject(0).toString());
startActivityForResult(intent,3);
}
catch (JSONException e)
{
switchFragment(1);
}
}
else
{
switchFragment(1);
}
}
}
else
Toast.makeText(this,"Error downloading",Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(this,"Error downloading",Toast.LENGTH_LONG).show();
}
}
@Override
public void processAPIError(Throwable e) {
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
}
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
public static class MyFilesFragment extends ListFragment {
protected MyFilesAdapter adapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new MyFilesAdapter(this);
setListAdapter(adapter);
adapter.Execute();
// registerForContextMenu(getListView());
}
public void refresh()
{
adapter.Execute();
}
@Override
public void onStop() {
super.onStop();
adapter.saveState();
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
try {
JSONObject jObj = ((FilesAdapter) l.getAdapter()).getJSONObject(position);
Intent intent = new Intent(getActivity(),FileActivity.class);
intent.putExtra("file",jObj.toString());
startActivityForResult(intent,1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static class ActiveFilesFragment extends ListFragment implements APIClient.APICallback {
protected ActiveFilesAdapter adapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new ActiveFilesAdapter(this);
setListAdapter(adapter);
adapter.Execute();
}
public void refresh()
{
adapter.Execute();
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
try {
JSONObject jObj = ((ActiveFilesAdapter)l.getAdapter()).getJSONObject(position);
if(jObj.getString("dl_status").equals("failed"))
{
showRetryDialog(jObj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showRetryDialog(final JSONObject jObj)
{
try {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
//adb.setView(alertDialogView);
adb.setTitle("Retry");
String name = jObj.getString("name");
adb.setMessage("Do you want to retry the download " + name +"?");
adb.setIcon(android.R.drawable.ic_dialog_alert);
adb
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
retryDownload(jObj);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
adb.show();
} catch (Exception e) {
e.printStackTrace();
}
}
private void retryDownload(JSONObject jObj)
{
try {
HashMap<String, String> params = new HashMap<String, String>();
params.put("info_hash", jObj.getString("info_hash"));
APIClient.get(getActivity().getApplicationContext(),"dl/add", params, ActiveFilesFragment.this);
} catch (JSONException e) {
Toast.makeText(getActivity(),"Error adding file to downloads", Toast.LENGTH_LONG).show();
}
}
@Override
public void processAPIResponse(JSONObject response) {
Toast.makeText(getActivity(),"File added",Toast.LENGTH_LONG).show();
this.refresh();
}
@Override
public void processAPIError(Throwable e) {
Toast.makeText(getActivity(),"Error adding file to downloads. "+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
| apache-2.0 |
looker-open-source/java-spanner | google-cloud-spanner/src/main/java/com/google/cloud/spanner/ValueBinder.java | 6573 | /*
* Copyright 2017 Google LLC
*
* 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.cloud.spanner;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.Timestamp;
import java.math.BigDecimal;
import javax.annotation.Nullable;
/**
* An interface for binding a {@link Value} in some context. Users of the Cloud Spanner client
* library never create a {@code ValueBinder} directly; instead this interface is returned from
* other parts of the library involved in {@code Value} construction. For example, {@link
* Mutation.WriteBuilder#set(String)} returns a binder to bind a column value, and {@code
* Statement#bind(String)} returns a binder to bind a parameter to a value.
*
* <p>{@code ValueBinder} subclasses typically carry state and are therefore not thread-safe,
* although the core implementation itself is thread-safe.
*/
public abstract class ValueBinder<R> {
/**
* Intentionally package-protected constructor; only the Cloud Spanner library can create
* instances.
*/
ValueBinder() {}
/**
* Subclasses should implement this method to handle value binding.
*
* <p>This method is intentionally package-protected rather than protected; the internal API is
* subject to change.
*
* @param value the newly bound value
* @return the object to return from the bind call ({@code to(...)}
*/
abstract R handle(Value value);
/** Binds a {@link Value} */
public R to(Value value) {
return handle(value);
}
/** Binds to {@code Value.bool(value)} */
public R to(boolean value) {
return handle(Value.bool(value));
}
/** Binds to {@code Value.bool(value)} */
public R to(@Nullable Boolean value) {
return handle(Value.bool(value));
}
/** Binds to {@code Value.int64(value)} */
public R to(long value) {
return handle(Value.int64(value));
}
/** Binds to {@code Value.int64(value)} */
public R to(@Nullable Long value) {
return handle(Value.int64(value));
}
/** Binds to {@code Value.float64(value)} */
public R to(double value) {
return handle(Value.float64(value));
}
/** Binds to {@code Value.float64(value)} */
public R to(@Nullable Double value) {
return handle(Value.float64(value));
}
/** Binds to {@code Value.numeric(value)} */
public R to(BigDecimal value) {
return handle(Value.numeric(value));
}
/** Binds to {@code Value.string(value)} */
public R to(@Nullable String value) {
return handle(Value.string(value));
}
/** Binds to {@code Value.bytes(value)} */
public R to(@Nullable ByteArray value) {
return handle(Value.bytes(value));
}
/** Binds to {@code Value.timestamp(value)} */
public R to(@Nullable Timestamp value) {
return handle(Value.timestamp(value));
}
/** Binds to {@code Value.date(value)} */
public R to(@Nullable Date value) {
return handle(Value.date(value));
}
/** Binds a non-{@code NULL} struct value to {@code Value.struct(value)} */
public R to(Struct value) {
return handle(Value.struct(value));
}
/**
* Binds a nullable {@code Struct} reference with given {@code Type} to {@code
* Value.struct(type,value}
*/
public R to(Type type, @Nullable Struct value) {
return handle(Value.struct(type, value));
}
/** Binds to {@code Value.boolArray(values)} */
public R toBoolArray(@Nullable boolean[] values) {
return handle(Value.boolArray(values));
}
/** Binds to {@code Value.boolArray(values, int, pos)} */
public R toBoolArray(@Nullable boolean[] values, int pos, int length) {
return handle(Value.boolArray(values, pos, length));
}
/** Binds to {@code Value.boolArray(values)} */
public R toBoolArray(@Nullable Iterable<Boolean> values) {
return handle(Value.boolArray(values));
}
/** Binds to {@code Value.int64Array(values)} */
public R toInt64Array(@Nullable long[] values) {
return handle(Value.int64Array(values));
}
/** Binds to {@code Value.int64Array(values, pos, length)} */
public R toInt64Array(@Nullable long[] values, int pos, int length) {
return handle(Value.int64Array(values, pos, length));
}
/** Binds to {@code Value.int64Array(values)} */
public R toInt64Array(@Nullable Iterable<Long> values) {
return handle(Value.int64Array(values));
}
/** Binds to {@code Value.float64Array(values)} */
public R toFloat64Array(@Nullable double[] values) {
return handle(Value.float64Array(values));
}
/** Binds to {@code Value.float64Array(values, pos, length)} */
public R toFloat64Array(@Nullable double[] values, int pos, int length) {
return handle(Value.float64Array(values, pos, length));
}
/** Binds to {@code Value.float64Array(values)} */
public R toFloat64Array(@Nullable Iterable<Double> values) {
return handle(Value.float64Array(values));
}
/** Binds to {@code Value.numericArray(values)} */
public R toNumericArray(@Nullable Iterable<BigDecimal> values) {
return handle(Value.numericArray(values));
}
/** Binds to {@code Value.stringArray(values)} */
public R toStringArray(@Nullable Iterable<String> values) {
return handle(Value.stringArray(values));
}
/** Binds to {@code Value.jsonArray(values)} */
public R toJsonArray(@Nullable Iterable<String> values) {
return handle(Value.jsonArray(values));
}
/** Binds to {@code Value.bytesArray(values)} */
public R toBytesArray(@Nullable Iterable<ByteArray> values) {
return handle(Value.bytesArray(values));
}
/** Binds to {@code Value.timestampArray(values)} */
public R toTimestampArray(@Nullable Iterable<Timestamp> values) {
return handle(Value.timestampArray(values));
}
/** Binds to {@code Value.dateArray(values)} */
public R toDateArray(@Nullable Iterable<Date> values) {
return handle(Value.dateArray(values));
}
/** Binds to {@code Value.structArray(fieldTypes, values)} */
public R toStructArray(Type elementType, @Nullable Iterable<Struct> values) {
return handle(Value.structArray(elementType, values));
}
}
| apache-2.0 |
hequn8128/flink | flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TestingTaskExecutorGateway.java | 11038 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.taskexecutor;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple6;
import org.apache.flink.runtime.blob.TransientBlobKey;
import org.apache.flink.runtime.checkpoint.CheckpointOptions;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.clusterframework.types.SlotID;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.deployment.TaskDeploymentDescriptor;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.executiongraph.PartitionInfo;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobmaster.AllocatedSlotReport;
import org.apache.flink.runtime.jobmaster.JobMasterId;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.messages.TaskBackPressureResponse;
import org.apache.flink.runtime.operators.coordination.OperatorEvent;
import org.apache.flink.runtime.resourcemanager.ResourceManagerId;
import org.apache.flink.runtime.rest.messages.LogInfo;
import org.apache.flink.runtime.rest.messages.taskmanager.ThreadDumpInfo;
import org.apache.flink.runtime.rpc.RpcTimeout;
import org.apache.flink.types.SerializableOptional;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.SerializedValue;
import org.apache.flink.util.function.TriConsumer;
import org.apache.flink.util.function.TriFunction;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Simple {@link TaskExecutorGateway} implementation for testing purposes.
*/
public class TestingTaskExecutorGateway implements TaskExecutorGateway {
private final String address;
private final String hostname;
private final BiConsumer<ResourceID, AllocatedSlotReport> heartbeatJobManagerConsumer;
private final BiConsumer<JobID, Throwable> disconnectJobManagerConsumer;
private final BiFunction<TaskDeploymentDescriptor, JobMasterId, CompletableFuture<Acknowledge>> submitTaskConsumer;
private final Function<Tuple6<SlotID, JobID, AllocationID, ResourceProfile, String, ResourceManagerId>, CompletableFuture<Acknowledge>> requestSlotFunction;
private final BiFunction<AllocationID, Throwable, CompletableFuture<Acknowledge>> freeSlotFunction;
private final Consumer<ResourceID> heartbeatResourceManagerConsumer;
private final Consumer<Exception> disconnectResourceManagerConsumer;
private final Function<ExecutionAttemptID, CompletableFuture<Acknowledge>> cancelTaskFunction;
private final Supplier<CompletableFuture<Boolean>> canBeReleasedSupplier;
private final TriConsumer<JobID, Set<ResultPartitionID>, Set<ResultPartitionID>> releaseOrPromotePartitionsConsumer;
private final Consumer<Collection<IntermediateDataSetID>> releaseClusterPartitionsConsumer;
private final TriFunction<ExecutionAttemptID, OperatorID, SerializedValue<OperatorEvent>, CompletableFuture<Acknowledge>> operatorEventHandler;
private final Supplier<CompletableFuture<ThreadDumpInfo>> requestThreadDumpSupplier;
TestingTaskExecutorGateway(
String address,
String hostname,
BiConsumer<ResourceID, AllocatedSlotReport> heartbeatJobManagerConsumer,
BiConsumer<JobID, Throwable> disconnectJobManagerConsumer,
BiFunction<TaskDeploymentDescriptor, JobMasterId, CompletableFuture<Acknowledge>> submitTaskConsumer,
Function<Tuple6<SlotID, JobID, AllocationID, ResourceProfile, String, ResourceManagerId>, CompletableFuture<Acknowledge>> requestSlotFunction,
BiFunction<AllocationID, Throwable, CompletableFuture<Acknowledge>> freeSlotFunction,
Consumer<ResourceID> heartbeatResourceManagerConsumer,
Consumer<Exception> disconnectResourceManagerConsumer,
Function<ExecutionAttemptID, CompletableFuture<Acknowledge>> cancelTaskFunction,
Supplier<CompletableFuture<Boolean>> canBeReleasedSupplier,
TriConsumer<JobID, Set<ResultPartitionID>, Set<ResultPartitionID>> releaseOrPromotePartitionsConsumer,
Consumer<Collection<IntermediateDataSetID>> releaseClusterPartitionsConsumer,
TriFunction<ExecutionAttemptID, OperatorID, SerializedValue<OperatorEvent>, CompletableFuture<Acknowledge>> operatorEventHandler,
Supplier<CompletableFuture<ThreadDumpInfo>> requestThreadDumpSupplier) {
this.address = Preconditions.checkNotNull(address);
this.hostname = Preconditions.checkNotNull(hostname);
this.heartbeatJobManagerConsumer = Preconditions.checkNotNull(heartbeatJobManagerConsumer);
this.disconnectJobManagerConsumer = Preconditions.checkNotNull(disconnectJobManagerConsumer);
this.submitTaskConsumer = Preconditions.checkNotNull(submitTaskConsumer);
this.requestSlotFunction = Preconditions.checkNotNull(requestSlotFunction);
this.freeSlotFunction = Preconditions.checkNotNull(freeSlotFunction);
this.heartbeatResourceManagerConsumer = heartbeatResourceManagerConsumer;
this.disconnectResourceManagerConsumer = disconnectResourceManagerConsumer;
this.cancelTaskFunction = cancelTaskFunction;
this.canBeReleasedSupplier = canBeReleasedSupplier;
this.releaseOrPromotePartitionsConsumer = releaseOrPromotePartitionsConsumer;
this.releaseClusterPartitionsConsumer = releaseClusterPartitionsConsumer;
this.operatorEventHandler = operatorEventHandler;
this.requestThreadDumpSupplier = requestThreadDumpSupplier;
}
@Override
public CompletableFuture<Acknowledge> requestSlot(SlotID slotId, JobID jobId, AllocationID allocationId, ResourceProfile resourceProfile, String targetAddress, ResourceManagerId resourceManagerId, Time timeout) {
return requestSlotFunction.apply(Tuple6.of(slotId, jobId, allocationId, resourceProfile, targetAddress, resourceManagerId));
}
@Override
public CompletableFuture<TaskBackPressureResponse> requestTaskBackPressure(ExecutionAttemptID executionAttemptId, int requestId, @RpcTimeout Time timeout) {
throw new UnsupportedOperationException();
}
@Override
public CompletableFuture<Acknowledge> submitTask(TaskDeploymentDescriptor tdd, JobMasterId jobMasterId, Time timeout) {
return submitTaskConsumer.apply(tdd, jobMasterId);
}
@Override
public CompletableFuture<Acknowledge> updatePartitions(ExecutionAttemptID executionAttemptID, Iterable<PartitionInfo> partitionInfos, Time timeout) {
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public void releaseOrPromotePartitions(JobID jobId, Set<ResultPartitionID> partitionToRelease, Set<ResultPartitionID> partitionsToPromote) {
releaseOrPromotePartitionsConsumer.accept(jobId, partitionToRelease, partitionsToPromote);
}
@Override
public CompletableFuture<Acknowledge> releaseClusterPartitions(Collection<IntermediateDataSetID> dataSetsToRelease, Time timeout) {
releaseClusterPartitionsConsumer.accept(dataSetsToRelease);
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public CompletableFuture<Acknowledge> triggerCheckpoint(ExecutionAttemptID executionAttemptID, long checkpointID, long checkpointTimestamp, CheckpointOptions checkpointOptions, boolean advanceToEndOfEventTime) {
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public CompletableFuture<Acknowledge> confirmCheckpoint(ExecutionAttemptID executionAttemptID, long checkpointId, long checkpointTimestamp) {
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public CompletableFuture<Acknowledge> cancelTask(ExecutionAttemptID executionAttemptID, Time timeout) {
return cancelTaskFunction.apply(executionAttemptID);
}
@Override
public void heartbeatFromJobManager(ResourceID heartbeatOrigin, AllocatedSlotReport allocatedSlotReport) {
heartbeatJobManagerConsumer.accept(heartbeatOrigin, allocatedSlotReport);
}
@Override
public void heartbeatFromResourceManager(ResourceID heartbeatOrigin) {
heartbeatResourceManagerConsumer.accept(heartbeatOrigin);
}
@Override
public void disconnectJobManager(JobID jobId, Exception cause) {
disconnectJobManagerConsumer.accept(jobId, cause);
}
@Override
public void disconnectResourceManager(Exception cause) {
disconnectResourceManagerConsumer.accept(cause);
}
@Override
public CompletableFuture<Acknowledge> freeSlot(AllocationID allocationId, Throwable cause, Time timeout) {
return freeSlotFunction.apply(allocationId, cause);
}
@Override
public CompletableFuture<TransientBlobKey> requestFileUploadByType(FileType fileType, Time timeout) {
return FutureUtils.completedExceptionally(new UnsupportedOperationException());
}
@Override
public CompletableFuture<TransientBlobKey> requestFileUploadByName(String fileName, Time timeout) {
return FutureUtils.completedExceptionally(new UnsupportedOperationException());
}
@Override
public CompletableFuture<SerializableOptional<String>> requestMetricQueryServiceAddress(Time timeout) {
return CompletableFuture.completedFuture(SerializableOptional.empty());
}
@Override
public CompletableFuture<Boolean> canBeReleased() {
return canBeReleasedSupplier.get();
}
@Override
public CompletableFuture<Acknowledge> sendOperatorEventToTask(
ExecutionAttemptID task,
OperatorID operator,
SerializedValue<OperatorEvent> evt) {
return operatorEventHandler.apply(task, operator, evt);
}
@Override
public CompletableFuture<ThreadDumpInfo> requestThreadDump(Time timeout) {
return requestThreadDumpSupplier.get();
}
@Override
public String getAddress() {
return address;
}
@Override
public String getHostname() {
return hostname;
}
@Override
public CompletableFuture<Collection<LogInfo>> requestLogList(Time timeout) {
return FutureUtils.completedExceptionally(new UnsupportedOperationException());
}
}
| apache-2.0 |
leleuj/cas | support/cas-server-support-geolocation/src/main/java/org/apereo/cas/support/geo/AbstractGeoLocationService.java | 4259 | package org.apereo.cas.support.geo;
import org.apereo.cas.authentication.adaptive.geo.GeoLocationRequest;
import org.apereo.cas.authentication.adaptive.geo.GeoLocationResponse;
import org.apereo.cas.authentication.adaptive.geo.GeoLocationService;
import org.apereo.cas.util.HttpUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.userinfo.client.UserInfo;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.hjson.JsonValue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* This is {@link AbstractGeoLocationService}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Slf4j
@Setter
@Getter
public abstract class AbstractGeoLocationService implements GeoLocationService {
private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules();
private String ipStackAccessKey;
@Override
@SneakyThrows
public GeoLocationResponse locate(final String address) {
try {
val info = UserInfo.getInfo(address);
if (info != null) {
val pos = info.getPosition();
if (pos != null && pos.getLatitude() != null && pos.getLongitude() != null) {
return locate(pos.getLatitude(), pos.getLongitude());
}
return locateByIpStack(address);
}
return null;
} catch (final Exception e) {
return locateByIpStack(address);
}
}
@Override
public GeoLocationResponse locate(final String clientIp, final GeoLocationRequest location) {
LOGGER.trace("Attempting to find geolocation for [{}]", clientIp);
val loc = locate(clientIp);
if (loc == null && location != null) {
LOGGER.trace("Attempting to find geolocation for [{}]", location);
if (StringUtils.isNotBlank(location.getLatitude()) && StringUtils.isNotBlank(location.getLongitude())) {
return locate(Double.valueOf(location.getLatitude()), Double.valueOf(location.getLongitude()));
}
}
return loc;
}
@Override
public GeoLocationResponse locate(final GeoLocationRequest request) {
return locate(Double.valueOf(request.getLatitude()), Double.valueOf(request.getLongitude()));
}
private GeoLocationResponse locateByIpStack(final String address) throws IOException {
if (StringUtils.isBlank(ipStackAccessKey)) {
return null;
}
val url = buildIpStackUrlFor(address);
HttpResponse response = null;
try {
response = HttpUtils.executeGet(url);
if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
val result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
val infos = MAPPER.readValue(JsonValue.readHjson(result).toString(), Map.class);
val geoResponse = new GeoLocationResponse();
geoResponse.setLatitude((double) infos.getOrDefault("latitude", 0D));
geoResponse.setLongitude((double) infos.getOrDefault("longitude", 0D));
geoResponse
.addAddress((String) infos.getOrDefault("city", StringUtils.EMPTY))
.addAddress((String) infos.getOrDefault("region_name", StringUtils.EMPTY))
.addAddress((String) infos.getOrDefault("region_code", StringUtils.EMPTY))
.addAddress((String) infos.getOrDefault("county_name", StringUtils.EMPTY));
return geoResponse;
}
} finally {
HttpUtils.close(response);
}
return null;
}
/**
* Build ip stack url for address.
*
* @param address the address
* @return the string
*/
protected String buildIpStackUrlFor(final String address) {
return String.format("https://api.ipstack.com/%s?access_key=%s", address, ipStackAccessKey);
}
}
| apache-2.0 |
ebyhr/presto | core/trino-main/src/main/java/io/trino/operator/join/PagesHash.java | 9432 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.operator.join;
import io.airlift.units.DataSize;
import io.trino.operator.HashArraySizeSupplier;
import io.trino.operator.PagesHashStrategy;
import io.trino.spi.Page;
import io.trino.spi.PageBuilder;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import org.openjdk.jol.info.ClassLayout;
import java.util.Arrays;
import static io.airlift.slice.SizeOf.sizeOf;
import static io.airlift.units.DataSize.Unit.KILOBYTE;
import static io.trino.operator.SyntheticAddress.decodePosition;
import static io.trino.operator.SyntheticAddress.decodeSliceIndex;
import static io.trino.util.HashCollisionsEstimator.estimateNumberOfHashCollisions;
import static java.lang.Math.toIntExact;
import static java.util.Objects.requireNonNull;
// This implementation assumes arrays used in the hash are always a power of 2
public final class PagesHash
{
private static final int INSTANCE_SIZE = ClassLayout.parseClass(PagesHash.class).instanceSize();
private static final DataSize CACHE_SIZE = DataSize.of(128, KILOBYTE);
private final LongArrayList addresses;
private final PagesHashStrategy pagesHashStrategy;
private final int mask;
private final int[] key;
private final long size;
// Native array of hashes for faster collisions resolution compared
// to accessing values in blocks. We use bytes to reduce memory foot print
// and there is no performance gain from storing full hashes
private final byte[] positionToHashes;
private final long hashCollisions;
private final double expectedHashCollisions;
public PagesHash(
LongArrayList addresses,
PagesHashStrategy pagesHashStrategy,
PositionLinks.FactoryBuilder positionLinks,
HashArraySizeSupplier hashArraySizeSupplier)
{
this.addresses = requireNonNull(addresses, "addresses is null");
this.pagesHashStrategy = requireNonNull(pagesHashStrategy, "pagesHashStrategy is null");
// reserve memory for the arrays
int hashSize = hashArraySizeSupplier.getHashArraySize(addresses.size());
mask = hashSize - 1;
key = new int[hashSize];
Arrays.fill(key, -1);
positionToHashes = new byte[addresses.size()];
// We will process addresses in batches, to save memory on array of hashes.
int positionsInStep = Math.min(addresses.size() + 1, (int) CACHE_SIZE.toBytes() / Integer.SIZE);
long[] positionToFullHashes = new long[positionsInStep];
long hashCollisionsLocal = 0;
for (int step = 0; step * positionsInStep <= addresses.size(); step++) {
int stepBeginPosition = step * positionsInStep;
int stepEndPosition = Math.min((step + 1) * positionsInStep, addresses.size());
int stepSize = stepEndPosition - stepBeginPosition;
// First extract all hashes from blocks to native array.
// Somehow having this as a separate loop is much faster compared
// to extracting hashes on the fly in the loop below.
for (int position = 0; position < stepSize; position++) {
int realPosition = position + stepBeginPosition;
long hash = readHashPosition(realPosition);
positionToFullHashes[position] = hash;
positionToHashes[realPosition] = (byte) hash;
}
// index pages
for (int position = 0; position < stepSize; position++) {
int realPosition = position + stepBeginPosition;
if (isPositionNull(realPosition)) {
continue;
}
long hash = positionToFullHashes[position];
int pos = getHashPosition(hash, mask);
// look for an empty slot or a slot containing this key
while (key[pos] != -1) {
int currentKey = key[pos];
if (((byte) hash) == positionToHashes[currentKey] && positionEqualsPositionIgnoreNulls(currentKey, realPosition)) {
// found a slot for this key
// link the new key position to the current key position
realPosition = positionLinks.link(realPosition, currentKey);
// key[pos] updated outside of this loop
break;
}
// increment position and mask to handler wrap around
pos = (pos + 1) & mask;
hashCollisionsLocal++;
}
key[pos] = realPosition;
}
}
size = sizeOf(addresses.elements()) + pagesHashStrategy.getSizeInBytes() +
sizeOf(key) + sizeOf(positionToHashes);
hashCollisions = hashCollisionsLocal;
expectedHashCollisions = estimateNumberOfHashCollisions(addresses.size(), hashSize);
}
public int getPositionCount()
{
return addresses.size();
}
public long getInMemorySizeInBytes()
{
return INSTANCE_SIZE + size;
}
public long getHashCollisions()
{
return hashCollisions;
}
public double getExpectedHashCollisions()
{
return expectedHashCollisions;
}
public int getAddressIndex(int position, Page hashChannelsPage)
{
return getAddressIndex(position, hashChannelsPage, pagesHashStrategy.hashRow(position, hashChannelsPage));
}
public int getAddressIndex(int rightPosition, Page hashChannelsPage, long rawHash)
{
int pos = getHashPosition(rawHash, mask);
while (key[pos] != -1) {
if (positionEqualsCurrentRowIgnoreNulls(key[pos], (byte) rawHash, rightPosition, hashChannelsPage)) {
return key[pos];
}
// increment position and mask to handler wrap around
pos = (pos + 1) & mask;
}
return -1;
}
public void appendTo(long position, PageBuilder pageBuilder, int outputChannelOffset)
{
long pageAddress = addresses.getLong(toIntExact(position));
int blockIndex = decodeSliceIndex(pageAddress);
int blockPosition = decodePosition(pageAddress);
pagesHashStrategy.appendTo(blockIndex, blockPosition, pageBuilder, outputChannelOffset);
}
private boolean isPositionNull(int position)
{
long pageAddress = addresses.getLong(position);
int blockIndex = decodeSliceIndex(pageAddress);
int blockPosition = decodePosition(pageAddress);
return pagesHashStrategy.isPositionNull(blockIndex, blockPosition);
}
private long readHashPosition(int position)
{
long pageAddress = addresses.getLong(position);
int blockIndex = decodeSliceIndex(pageAddress);
int blockPosition = decodePosition(pageAddress);
return pagesHashStrategy.hashPosition(blockIndex, blockPosition);
}
private boolean positionEqualsCurrentRowIgnoreNulls(int leftPosition, byte rawHash, int rightPosition, Page rightPage)
{
if (positionToHashes[leftPosition] != rawHash) {
return false;
}
long pageAddress = addresses.getLong(leftPosition);
int blockIndex = decodeSliceIndex(pageAddress);
int blockPosition = decodePosition(pageAddress);
return pagesHashStrategy.positionEqualsRowIgnoreNulls(blockIndex, blockPosition, rightPosition, rightPage);
}
private boolean positionEqualsPositionIgnoreNulls(int leftPosition, int rightPosition)
{
long leftPageAddress = addresses.getLong(leftPosition);
int leftBlockIndex = decodeSliceIndex(leftPageAddress);
int leftBlockPosition = decodePosition(leftPageAddress);
long rightPageAddress = addresses.getLong(rightPosition);
int rightBlockIndex = decodeSliceIndex(rightPageAddress);
int rightBlockPosition = decodePosition(rightPageAddress);
return pagesHashStrategy.positionEqualsPositionIgnoreNulls(leftBlockIndex, leftBlockPosition, rightBlockIndex, rightBlockPosition);
}
private static int getHashPosition(long rawHash, long mask)
{
// Avalanches the bits of a long integer by applying the finalisation step of MurmurHash3.
//
// This function implements the finalisation step of Austin Appleby's <a href="http://sites.google.com/site/murmurhash/">MurmurHash3</a>.
// Its purpose is to avalanche the bits of the argument to within 0.25% bias. It is used, among other things, to scramble quickly (but deeply) the hash
// values returned by {@link Object#hashCode()}.
//
rawHash ^= rawHash >>> 33;
rawHash *= 0xff51afd7ed558ccdL;
rawHash ^= rawHash >>> 33;
rawHash *= 0xc4ceb9fe1a85ec53L;
rawHash ^= rawHash >>> 33;
return (int) (rawHash & mask);
}
}
| apache-2.0 |
hcuffy/concourse | concourse-server/src/main/java/com/cinchapi/concourse/util/Producer.java | 2547 | /*
* Copyright (c) 2013-2015 Cinchapi 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.cinchapi.concourse.util;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import javax.annotation.concurrent.ThreadSafe;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
/**
* A {@link Producer} provides elements to a consumer.
*
* @author Jeff Nelson
*/
@ThreadSafe
public class Producer<T> {
/**
* The queue that holds that next element to be transferred to the consumer.
*/
private final SynchronousQueue<T> queue = new SynchronousQueue<T>();
/**
* Construct a new instance.
*
* @param supplier
*/
public Producer(final Callable<T> supplier) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
for (;;) {
T element = supplier.call();
queue.put(element);
}
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
};
// Create threads that will continuously try to insert elements into the
// queue, blocking until one of the elements is taken.
int count = Runtime.getRuntime().availableProcessors();
ExecutorService executor = Executors.newFixedThreadPool(count,
new ThreadFactoryBuilder().setDaemon(true).build());
for (int i = 0; i < count; ++i) {
executor.execute(runnable);
}
}
/**
* Consume the next element from this Producer.
*
* @return the element
*/
public T consume() {
try {
return queue.take();
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
| apache-2.0 |
turtlebender/crux-security-core | jsse/src/main/java/org/globus/security/jaas/JaasSubject.java | 4095 | /*
* Copyright 1999-2006 University of Chicago
*
* 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.globus.security.jaas;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import javax.security.auth.Subject;
import org.globus.util.I18n;
/**
* Generic JAAS Subject helper API that provides abstraction layer on top of
* vendor-specific JAAS Subject extensions implementations.
* Most vendors defined their own JAAS Subject helper classes because of the
* <a href="http://publib7b.boulder.ibm.com/wasinfo1/en/info/aes/ae/rsec_jaasauthor.html">
* Subject propagation issue</a> in JAAS.
*/
public abstract class JaasSubject {
private static I18n i18n = I18n.getI18n("org.globus.security.jaas.JaasErrors", JaasSubject.class.getClassLoader());
private static JaasSubject subject;
protected JaasSubject() {
}
/**
* Gets current implementation of the <code>JaasSubject</code> API.
* The method attempts to load a <code>JaasSubject</code> implementation
* by loading a class specified by the
* "<i>org.globus.jaas.provider</i>" system property. If the property
* is not set the default Globus implementation is loaded.
*/
public static synchronized JaasSubject getJaasSubject() {
if (subject == null) {
String className = System.getProperty("org.globus.jaas.provider");
if (className == null) {
className = "org.globus.security.jaas.GlobusSubject";
}
try {
Class <?> clazz = Class.forName(className);
if (!JaasSubject.class.isAssignableFrom(clazz)) {
throw new RuntimeException(i18n.getMessage("invalidJaasSubject", className));
}
subject = (JaasSubject) clazz.newInstance();
} catch (ClassNotFoundException e) {
throw new RuntimeException(i18n.getMessage("loadError", className) + e.getMessage());
} catch (InstantiationException e) {
throw new RuntimeException(i18n.getMessage("instanError", className) + e.getMessage());
} catch (IllegalAccessException e) {
throw new RuntimeException(i18n.getMessage("instanError", className) + e.getMessage());
}
}
return subject;
}
// SPI
/**
* SPI method.
*/
public abstract Subject getSubject();
/**
* SPI method.
*/
public abstract Object runAs(Subject subject, PrivilegedAction<?> action);
/**
* SPI method.
*/
public abstract Object runAs(Subject subject, PrivilegedExceptionAction<?> action)
throws PrivilegedActionException;
// API
/**
* A convenience method, calls
* <code>JaasSubject.getJaasSubject().runAs()<code/>.
*/
public static Object doAs(Subject subject, PrivilegedExceptionAction action)
throws PrivilegedActionException {
return JaasSubject.getJaasSubject().runAs(subject, action);
}
/**
* A convenience method, calls
* <code>JaasSubject.getJaasSubject().runAs()<code/>.
*/
public static Object doAs(Subject subject, PrivilegedAction action) {
return JaasSubject.getJaasSubject().runAs(subject, action);
}
/**
* A convenience method, calls
* <code>JaasSubject.getJaasSubject().getSubject()<code/>.
*/
public static Subject getCurrentSubject() {
return JaasSubject.getJaasSubject().getSubject();
}
}
| apache-2.0 |
wapalxj/Java | javaworkplace/source/src/com/google/gson/stream/JsonScope.java | 2436 | /*
* Copyright (C) 2010 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.gson.stream;
/**
* Lexical scoping elements within a JSON reader or writer.
*
* @author Jesse Wilson
* @since 1.6
*/
final class JsonScope {
/**
* An array with no elements requires no separators or newlines before
* it is closed.
*/
//没有元素的数组(相当于之前刚读了“[”),下一个元素一定不是逗号。
static final int EMPTY_ARRAY = 1;
/**
* A array with at least one value requires a comma and newline before
* the next element.
*/
//非空数组(至少已经有一个元素),下一个元素不是逗号就是“]”
static final int NONEMPTY_ARRAY = 2;
/**
* An object with no name/value pairs requires no separators or newlines
* before it is closed.
*/
//空对象(刚读到“{”,一个name/value对都没有),下一个一定不是逗号。
static final int EMPTY_OBJECT = 3;
/**
* An object whose most recent element is a key. The next element must
* be a value.
*/
//名字,下一个元素一定是值。
static final int DANGLING_NAME = 4;
/**
* An object with at least one name/value pair requires a comma and
* newline before the next element.
*/
//非空对象(至少一个name/value对),下一个元素不是逗号就是“}”
static final int NONEMPTY_OBJECT = 5;
/**
* No object or array has been started.
*/
//空文档,初识状态,啥也没读
static final int EMPTY_DOCUMENT = 6;
/**
* A document with at an array or object.
*/
//文档中有一个顶级的数组/对象
static final int NONEMPTY_DOCUMENT = 7;
/**
* A document that's been closed and cannot be accessed.
*/
//文档已被关闭
static final int CLOSED = 8;
}
| apache-2.0 |
fengyouchao/tesseract4j | src/main/java/tesseract4j/util/BashShellExecutor.java | 3449 | package tesseract4j.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* The class <code>BashShellExecutor</code> represents a shell executor that
* can execute bash shell.
*
* @author Youchao Feng
* @date Mar 5, 2015 2:06:56 PM
* @version 1.0
*/
public class BashShellExecutor extends AbstractShellExecutor{
private File workDir = new File(System.getProperty("user.home"));
public ShellExecuteResult execute(String cmd){
if(cmd.startsWith("cd ")){
String path = cmd.substring(3);
System.out.println("path"+path);
String fullPath = null;
if(isAbsolutePath(path)){
fullPath = path;
}else{
fullPath = workDir.getAbsoluteFile()+FILE_SEPARATOR+path;
}
fullPath = simplifyPath(fullPath);
System.out.println("Work Path:"+fullPath);
File file = new File(fullPath);
if(file.exists()&&file.isDirectory()){
workDir = new File(fullPath);
return new ShellExecuteResult().setCurrentWorkDir(workDir.getAbsolutePath()).setSuccess(true);
}else{
return new ShellExecuteResult().setCurrentWorkDir(workDir.getAbsolutePath()).setSuccess(false)
.setErrorMessage("No such directory");
}
}
// if(getCommandExecutor().canHandle(cmd)){
// return getCommandExecutor().execute(cmd);
// }
try {
// Process ps = Runtime.getRuntime().exec(getConsoleProgram()+cmd,null, workDir);
List<String> cmds = new ArrayList<String>();
cmds.add("sh");
cmds.add("-c");
cmds.add(cmd);
// cmds.add(System.getProperty("user.home"));
ProcessBuilder pBuilder =new ProcessBuilder(cmds).directory(workDir);
Process ps = pBuilder.start();
// Process ps = Runtime.getRuntime()
String resultMessage = loadStream(ps.getInputStream());
String errorMessage = loadStream(ps.getErrorStream());
ps.waitFor();
int exitValue = ps.exitValue();
return new ShellExecuteResult().setCurrentWorkDir(workDir.getAbsolutePath())
.setErrorMessage(errorMessage).setResultMessage(resultMessage)
.setSuccess(exitValue == 0);
} catch(Exception ioe) {
ioe.printStackTrace();
}
return null;
}
static public void main(String[] args) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
BashShellExecutor shellExecutor = new BashShellExecutor();
System.out.print(ShellExecutor.USERNAME+"-"+shellExecutor.getWorkDir().getAbsolutePath()+"$:");
while(scanner.hasNext()){
String cmd = scanner.nextLine();
ShellExecuteResult result = shellExecutor.execute(cmd);
if(result.isSuccess()){
System.out.println(result.getResultMessage());
}else{
System.err.println(result.getErrorMessage());
}
System.out.print(ShellExecutor.USERNAME+"-"+shellExecutor.getWorkDir().getAbsolutePath()+"$:");
}
}
// read an input-stream into a String
static String loadStream(InputStream in) throws IOException {
// in = new BufferedInputStream(in);
BufferedReader reader = new BufferedReader(new InputStreamReader(in,SYS_ENCODING));
;
StringBuffer buffer = new StringBuffer();
String line = null;
while( (line = reader.readLine()) != null ) {
buffer.append(line+"\n");
}
return buffer.toString();
}
public File getWorkDir() {
return workDir;
}
public void setWorkDir(File workDir) {
this.workDir = workDir;
}
} | apache-2.0 |
luisfrt/netty-storm | netty-spout/src/main/java/NettySpoutServerInitializer.java | 1611 |
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
/**
* Creates a newly configured {@link ChannelPipeline} for a new channel.
*/
public class NettySpoutServerInitializer extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
NettySpout spout;
public NettySpoutServerInitializer(NettySpout spout, SslContext sslCtx) {
this.sslCtx = sslCtx;
this.spout=spout;
}
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// Add SSL handler first to encrypt and decrypt everything.
// In this example, we use a bogus certificate in the server side
// and accept any invalid certificates in the client side.
// You will need something more complicated to identify both
// and server in the real world.
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
// On top of the SSL handler, add the text line codec.
pipeline.addLast(new DelimiterBasedFrameDecoder(8*8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
// and then business logic.
pipeline.addLast(new NettySpoutServerHandler(spout));
}
}
| apache-2.0 |
kaedea/b-log | logger/src/main/java/moe/studio/log/Executor.java | 1315 | /*
* Copyright (c) 2017. Kaede <kidhaibara@gmail.com)>
*/
package moe.studio.log;
import moe.studio.dispatcher.Task;
/**
* @author kaede
* @version date 16/9/22
*/
@SuppressWarnings("WeakerAccess")
class Executor {
private static final int DELAY_MILLIS = 2000;
private static Task.Dispatcher sDispatcher;
private static void ensureHandler() {
if (sDispatcher == null) {
synchronized (Executor.class) {
if (sDispatcher == null) {
sDispatcher = Task.Dispatchers.newSimpleDispatcher();
sDispatcher.start();
}
}
}
}
public static void post(Runnable runnable) {
if (runnable == null) {
return;
}
ensureHandler();
sDispatcher.post(runnable);
}
public static void post(int what, Runnable runnable) {
if (runnable == null) {
return;
}
ensureHandler();
sDispatcher.postDelay(what, runnable, DELAY_MILLIS);
}
public static boolean has(int what) {
ensureHandler();
return sDispatcher.has(what);
}
public static void setDispatcher(Task.Dispatcher dispatcher) {
if (dispatcher != null) {
sDispatcher = dispatcher;
}
}
}
| apache-2.0 |
baart92/jgrades | jg-logging/src/main/java/org/jgrades/logging/service/LoggingServiceImpl.java | 948 | package org.jgrades.logging.service;
import org.jgrades.logging.dao.LoggingConfigurationDao;
import org.jgrades.logging.dao.LoggingConfigurationDaoFileImpl;
import org.jgrades.logging.model.LoggingConfiguration;
import org.jgrades.logging.utils.LogbackXmlEditor;
public class LoggingServiceImpl implements LoggingService {
private LogbackXmlEditor xmlEditor = new LogbackXmlEditor();
private LoggingConfigurationDao dao = new LoggingConfigurationDaoFileImpl();
@Override
public LoggingConfiguration getLoggingConfiguration() {
return dao.getCurrentConfiguration();
}
@Override
public void setLoggingConfiguration(LoggingConfiguration loggingConfiguration) {
dao.setConfiguration(loggingConfiguration);
}
@Override
public boolean isUsingDefaultConfiguration() {
return !xmlEditor.isXmlExists() ? true : dao.getDefaultConfiguration().equals(dao.getCurrentConfiguration());
}
}
| apache-2.0 |
mattxia/spring-2.5-analysis | test/org/springframework/jdbc/support/SQLExceptionSubclassTranslatorTests.java | 5457 | /*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import junit.framework.TestCase;
import java.sql.SQLException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.dao.*;
import org.springframework.core.JdkVersion;
/**
* @author Thomas Risberg
*/
public class SQLExceptionSubclassTranslatorTests extends TestCase {
private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes();
static {
ERROR_CODES.setBadSqlGrammarCodes(new String[] { "1" });
}
public void testErrorCodeTranslation() {
SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
if (JdkVersion.getMajorJavaVersion() >= JdkVersion.JAVA_16) {
SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 0);
DataIntegrityViolationException divex = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx);
assertEquals(dataIntegrityViolationEx, divex.getCause());
SQLException badSqlEx = SQLExceptionSubclassFactory.newSQLFeatureNotSupportedException("", "", 0);
BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
assertEquals("SQL", bsgex.getSql());
assertEquals(badSqlEx, bsgex.getSQLException());
SQLException dataIntegrityViolationEx2 = SQLExceptionSubclassFactory.newSQLIntegrityConstraintViolationException("", "", 0);
DataIntegrityViolationException divex2 = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx2);
assertEquals(dataIntegrityViolationEx2, divex2.getCause());
SQLException permissionDeniedEx = SQLExceptionSubclassFactory.newSQLInvalidAuthorizationSpecException("", "", 0);
PermissionDeniedDataAccessException pdaex = (PermissionDeniedDataAccessException) sext.translate("task", "SQL", permissionDeniedEx);
assertEquals(permissionDeniedEx, pdaex.getCause());
SQLException dataAccesResourceEx = SQLExceptionSubclassFactory.newSQLNonTransientConnectionException("", "", 0);
DataAccessResourceFailureException darex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataAccesResourceEx);
assertEquals(dataAccesResourceEx, darex.getCause());
SQLException badSqlEx2 = SQLExceptionSubclassFactory.newSQLSyntaxErrorException("", "", 0);
BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", badSqlEx2);
assertEquals("SQL2", bsgex2.getSql());
assertEquals(badSqlEx2, bsgex2.getSQLException());
SQLException tranRollbackEx = SQLExceptionSubclassFactory.newSQLTransactionRollbackException("", "", 0);
ConcurrencyFailureException cfex = (ConcurrencyFailureException) sext.translate("task", "SQL", tranRollbackEx);
assertEquals(tranRollbackEx, cfex.getCause());
SQLException transientConnEx = SQLExceptionSubclassFactory.newSQLTransientConnectionException("", "", 0);
TransientDataAccessResourceException tdarex = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx);
assertEquals(transientConnEx, tdarex.getCause());
SQLException transientConnEx2 = SQLExceptionSubclassFactory.newSQLTimeoutException("", "", 0);
TransientDataAccessResourceException tdarex2 = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx2);
assertEquals(transientConnEx2, tdarex2.getCause());
SQLException recoverableEx = SQLExceptionSubclassFactory.newSQLRecoverableException("", "", 0);
RecoverableDataAccessException rdaex2 = (RecoverableDataAccessException) sext.translate("task", "SQL", recoverableEx);
assertEquals(recoverableEx, rdaex2.getCause());
// Test classic error code translation. We should move there next if the exception we pass in is not one
// of the new sub-classes.
SQLException sexEct = new SQLException("", "", 1);
BadSqlGrammarException bsgEct = (BadSqlGrammarException) sext.translate("task", "SQL-ECT", sexEct);
assertEquals("SQL-ECT", bsgEct.getSql());
assertEquals(sexEct, bsgEct.getSQLException());
// Test fallback. We assume that no database will ever return this error code,
// but 07xxx will be bad grammar picked up by the fallback SQLState translator
SQLException sexFbt = new SQLException("", "07xxx", 666666666);
BadSqlGrammarException bsgFbt = (BadSqlGrammarException) sext.translate("task", "SQL-FBT", sexFbt);
assertEquals("SQL-FBT", bsgFbt.getSql());
assertEquals(sexFbt, bsgFbt.getSQLException());
// and 08xxx will be data resource failure (non-transient) picked up by the fallback SQLState translator
SQLException sexFbt2 = new SQLException("", "08xxx", 666666666);
DataAccessResourceFailureException darfFbt = (DataAccessResourceFailureException) sext.translate("task", "SQL-FBT2", sexFbt2);
assertEquals(sexFbt2, darfFbt.getCause());
}
}
}
| apache-2.0 |
river9/BGText | TextToday/src/com/river/texttoday/SectionsPagerAdapter.java | 864 | package com.river.texttoday;
import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class SectionsPagerAdapter extends FragmentPagerAdapter {
ArrayList<BGTextObject> data;
public SectionsPagerAdapter(FragmentManager fm, ArrayList<BGTextObject> data) {
super(fm);
this.data = data;
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).
return PlaceholderFragment.newInstance(
data.get(position).getDate(),
data.get(position).getCharacter(),
data.get(position).getBackground());
}
@Override
public int getCount() {
// Show total pages.
return data.size();
}
} | apache-2.0 |
yanfanvip/RedisClusterManager | RedisManager-Base/src/main/java/org/redis/manager/util/SystemUtil.java | 637 | package org.redis.manager.util;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class SystemUtil {
static InetAddress address;
static{
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static String ip() {
return address.getHostAddress();
}
public static String hostname(){
return address.getHostName();
}
public static void main(String[] args) throws UnknownHostException, SocketException {
System.out.println(ip());
System.out.println(hostname());
}
}
| apache-2.0 |
ufoscout/java-sample-projects | wicket-stateless/src/main/java/com/mycompany/ajax/AjaxCounterPage.java | 1208 | package com.mycompany.ajax;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import com.google.code.joliratools.StatelessAjaxFallbackLink;
import com.mycompany.StatelessWebPage;
public class AjaxCounterPage extends StatelessWebPage {
private static final long serialVersionUID = 1L;
public AjaxCounterPage(PageParameters pageParameters) {
final Model<Integer> model = new Model<Integer>() {
private static final long serialVersionUID = 1L;
private int counter = 0;
public Integer getObject() {
return counter++;
}
};
final Label label = new Label("counter", model);
label.setOutputMarkupId(true);
add(new StatelessAjaxFallbackLink<Integer>("link") {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
if (target != null) {
// target is only available in an Ajax request
target.add(label);
}
}
});
add(label);
}
}
| apache-2.0 |
jdgwartney/vsphere-ws | java/JAXWS/samples/com/vmware/vim25/CopyVirtualDiskTaskResponse.java | 1640 |
package com.vmware.vim25;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="returnval" type="{urn:vim25}ManagedObjectReference"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"returnval"
})
@XmlRootElement(name = "CopyVirtualDisk_TaskResponse")
public class CopyVirtualDiskTaskResponse {
@XmlElement(required = true)
protected ManagedObjectReference returnval;
/**
* Gets the value of the returnval property.
*
* @return
* possible object is
* {@link ManagedObjectReference }
*
*/
public ManagedObjectReference getReturnval() {
return returnval;
}
/**
* Sets the value of the returnval property.
*
* @param value
* allowed object is
* {@link ManagedObjectReference }
*
*/
public void setReturnval(ManagedObjectReference value) {
this.returnval = value;
}
}
| apache-2.0 |
pdrados/cas | support/cas-server-support-jdbc-authentication/src/test/java/org/apereo/cas/adaptors/jdbc/QueryDatabaseAuthenticationHandlerPostgresTests.java | 3970 | package org.apereo.cas.adaptors.jdbc;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.CoreAuthenticationUtils;
import org.apereo.cas.authentication.principal.PrincipalFactoryUtils;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.junit.EnabledIfPortOpen;
import org.apereo.cas.util.serialization.SerializationUtils;
import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.TestPropertySource;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.sql.DataSource;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* This is postgres tests for {@link QueryDatabaseAuthenticationHandler}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@TestPropertySource(properties = {
"database.user=postgres",
"database.password=password",
"database.driver-class=org.postgresql.Driver",
"database.name=postgres",
"database.url=jdbc:postgresql://localhost:5432/",
"database.dialect=org.hibernate.dialect.PostgreSQL95Dialect"
})
@EnabledIfPortOpen(port = 5432)
@Tag("Postgres")
public class QueryDatabaseAuthenticationHandlerPostgresTests extends BaseDatabaseAuthenticationHandlerTests {
private static final String SQL = "SELECT * FROM caspgusers where username=?";
private static final String PASSWORD_FIELD = "password";
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@BeforeEach
@SneakyThrows
public void initialize() {
try (val c = this.dataSource.getConnection()) {
c.setAutoCommit(true);
try (val pstmt = c.prepareStatement("insert into caspgusers (username, password, locations) values(?,?,?);")) {
val array = c.createArrayOf("text", new String[]{"usa", "uk"});
pstmt.setString(1, "casuser");
pstmt.setString(2, "Mellon");
pstmt.setArray(3, array);
pstmt.executeUpdate();
}
}
}
@AfterEach
@SneakyThrows
public void afterEachTest() {
try (val c = this.dataSource.getConnection()) {
try (val s = c.createStatement()) {
c.setAutoCommit(true);
s.execute("delete from caspgusers;");
}
}
}
@Test
@SneakyThrows
public void verifySuccess() {
val map = CoreAuthenticationUtils.transformPrincipalAttributesListIntoMultiMap(List.of("locations"));
val q = new QueryDatabaseAuthenticationHandler("DbHandler", null,
PrincipalFactoryUtils.newPrincipalFactory(), 0,
this.dataSource, SQL, PASSWORD_FIELD,
null, null, CollectionUtils.wrap(map));
val c = CoreAuthenticationTestUtils.getCredentialsWithDifferentUsernameAndPassword("casuser", "Mellon");
val result = q.authenticate(c);
assertNotNull(result);
assertNotNull(result.getPrincipal());
assertTrue(result.getPrincipal().getAttributes().containsKey("locations"));
assertNotNull(SerializationUtils.serialize(result));
}
@SuppressWarnings("unused")
@Entity(name = "caspgusers")
public static class UsersTable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String username;
@Column
private String password;
@Column(
name = "locations",
columnDefinition = "text[]"
)
private String[] locations;
}
}
| apache-2.0 |
web3j/web3j | besu/src/main/java/org/web3j/tx/response/PollingPrivateTransactionReceiptProcessor.java | 2562 | /*
* Copyright 2019 Web3 Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.web3j.tx.response;
import java.io.IOException;
import java.util.Optional;
import org.web3j.protocol.besu.Besu;
import org.web3j.protocol.besu.response.privacy.PrivateTransactionReceipt;
import org.web3j.protocol.exceptions.TransactionException;
public class PollingPrivateTransactionReceiptProcessor extends PrivateTransactionReceiptProcessor {
private final long sleepDuration;
private final int attempts;
public PollingPrivateTransactionReceiptProcessor(Besu besu, long sleepDuration, int attempts) {
super(besu);
this.sleepDuration = sleepDuration;
this.attempts = attempts;
}
@Override
public PrivateTransactionReceipt waitForTransactionReceipt(String transactionHash)
throws IOException, TransactionException {
return getTransactionReceipt(transactionHash, sleepDuration, attempts);
}
private PrivateTransactionReceipt getTransactionReceipt(
String transactionHash, long sleepDuration, int attempts)
throws IOException, TransactionException {
Optional<PrivateTransactionReceipt> receiptOptional =
sendTransactionReceiptRequest(transactionHash);
for (int i = 0; i < attempts; i++) {
if (!receiptOptional.isPresent()) {
try {
Thread.sleep(sleepDuration);
} catch (InterruptedException e) {
throw new TransactionException(e);
}
receiptOptional = sendTransactionReceiptRequest(transactionHash);
} else {
return receiptOptional.get();
}
}
throw new TransactionException(
"Transaction receipt was not generated after "
+ ((sleepDuration * attempts) / 1000
+ " seconds for transaction: "
+ transactionHash),
transactionHash);
}
}
| apache-2.0 |
mjsax/aeolus | monitoring/src/main/java/de/hub/cs/dbis/aeolus/monitoring/utils/AeolusConfig.java | 1414 | /*
* #!
* %
* Copyright (C) 2014 - 2016 Humboldt-Universität zu Berlin
* %
* 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 de.hub.cs.dbis.aeolus.monitoring.utils;
import java.util.HashMap;
/**
* {@link AeolusConfig} is a universal configuration object for the whole optimization package.
*
* @author mjsax
*/
public class AeolusConfig {
public final static String NIMBUS_HOST = "nimbus.host";
public final static String NIMBUS_PORT = "nimbus.port";
/** Contains the actual configuration key-value-pairs. */
final HashMap<String, Object> config = new HashMap<String, Object>();
public String getNimbusHost() {
return (String)this.config.get(NIMBUS_HOST);
}
public Integer getNimbusPort() {
return (Integer)this.config.get(NIMBUS_PORT);
}
public int getNimbusPortValue() {
return ((Integer)this.config.get(NIMBUS_PORT)).intValue();
}
}
| apache-2.0 |
nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201408/LineItemCreativeAssociationStatus.java | 3352 | /**
* LineItemCreativeAssociationStatus.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201408;
public class LineItemCreativeAssociationStatus implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected LineItemCreativeAssociationStatus(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _ACTIVE = "ACTIVE";
public static final java.lang.String _NOT_SERVING = "NOT_SERVING";
public static final java.lang.String _INACTIVE = "INACTIVE";
public static final java.lang.String _DELETED = "DELETED";
public static final LineItemCreativeAssociationStatus ACTIVE = new LineItemCreativeAssociationStatus(_ACTIVE);
public static final LineItemCreativeAssociationStatus NOT_SERVING = new LineItemCreativeAssociationStatus(_NOT_SERVING);
public static final LineItemCreativeAssociationStatus INACTIVE = new LineItemCreativeAssociationStatus(_INACTIVE);
public static final LineItemCreativeAssociationStatus DELETED = new LineItemCreativeAssociationStatus(_DELETED);
public java.lang.String getValue() { return _value_;}
public static LineItemCreativeAssociationStatus fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
LineItemCreativeAssociationStatus enumeration = (LineItemCreativeAssociationStatus)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static LineItemCreativeAssociationStatus fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(LineItemCreativeAssociationStatus.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "LineItemCreativeAssociation.Status"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| apache-2.0 |
mtaal/olingo-odata4-jpa | lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPrimitiveValueImpl.java | 7062 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.client.core.domain;
import java.math.BigDecimal;
import java.util.UUID;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.client.api.domain.AbstractClientValue;
import org.apache.olingo.client.api.domain.ClientEnumValue;
import org.apache.olingo.client.api.domain.ClientPrimitiveValue;
import org.apache.olingo.client.api.domain.ClientValue;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.edm.constants.EdmTypeKind;
import org.apache.olingo.commons.core.edm.primitivetype.EdmPrimitiveTypeFactory;
public class ClientPrimitiveValueImpl extends AbstractClientValue implements ClientValue, ClientPrimitiveValue {
public static class BuilderImpl implements Builder {
private final ClientPrimitiveValueImpl instance;
public BuilderImpl() {
instance = new ClientPrimitiveValueImpl();
}
@Override
public BuilderImpl setType(final EdmType type) {
EdmPrimitiveTypeKind primitiveTypeKind = null;
if (type != null) {
if (type.getKind() != EdmTypeKind.PRIMITIVE) {
throw new IllegalArgumentException(String.format("Provided type %s is not primitive", type));
}
primitiveTypeKind = EdmPrimitiveTypeKind.valueOf(type.getName());
}
return setType(primitiveTypeKind);
}
@Override
public BuilderImpl setType(final EdmPrimitiveTypeKind type) {
if (type == EdmPrimitiveTypeKind.Stream) {
throw new IllegalArgumentException(String.format(
"Cannot build a primitive value for %s", EdmPrimitiveTypeKind.Stream.toString()));
}
if (type == EdmPrimitiveTypeKind.Geography || type == EdmPrimitiveTypeKind.Geometry) {
throw new IllegalArgumentException(
type + "is not an instantiable type. "
+ "An entity can declare a property to be of type Geometry. "
+ "An instance of an entity MUST NOT have a value of type Geometry. "
+ "Each value MUST be of some subtype.");
}
instance.typeKind = type == null ? EdmPrimitiveTypeKind.String : type;
instance.type = EdmPrimitiveTypeFactory.getInstance(instance.typeKind);
return this;
}
@Override
public BuilderImpl setValue(final Object value) {
instance.value = value;
return this;
}
@Override
public ClientPrimitiveValue build() {
if (instance.type == null) {
setType(EdmPrimitiveTypeKind.String);
}
return instance;
}
@Override
public ClientPrimitiveValue buildBoolean(final Boolean value) {
return setType(EdmPrimitiveTypeKind.Boolean).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildInt16(final Short value) {
return setType(EdmPrimitiveTypeKind.Int16).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildInt32(final Integer value) {
return setType(EdmPrimitiveTypeKind.Int32).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildInt64(final Long value) {
return setType(EdmPrimitiveTypeKind.Int64).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildSingle(final Float value) {
return setType(EdmPrimitiveTypeKind.Single).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildDouble(final Double value) {
return setType(EdmPrimitiveTypeKind.Double).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildString(final String value) {
return setType(EdmPrimitiveTypeKind.String).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildGuid(final UUID value) {
return setType(EdmPrimitiveTypeKind.Guid).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildBinary(final byte[] value) {
return setType(EdmPrimitiveTypeKind.Binary).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildDecimal(BigDecimal value) {
return setType(EdmPrimitiveTypeKind.Decimal).setValue(value).build();
}
@Override
public ClientPrimitiveValue buildDuration(BigDecimal value) {
return setType(EdmPrimitiveTypeKind.Duration).setValue(value).build();
}
}
/**
* Type kind.
*/
private EdmPrimitiveTypeKind typeKind;
/**
* Type.
*/
private EdmPrimitiveType type;
/**
* Actual value.
*/
private Object value;
protected ClientPrimitiveValueImpl() {
super(null);
}
@Override
public String getTypeName() {
return typeKind.getFullQualifiedName().toString();
}
@Override
public EdmPrimitiveTypeKind getTypeKind() {
return typeKind;
}
@Override
public EdmPrimitiveType getType() {
return type;
}
@Override
public Object toValue() {
return value;
}
@Override
public <T> T toCastValue(final Class<T> reference) throws EdmPrimitiveTypeException {
if (value == null) {
return null;
} else if (typeKind.isGeospatial()) {
return reference.cast(value);
} else {
// TODO: set facets
return type.valueOfString(type.valueToString(value,
null, null, Constants.DEFAULT_PRECISION, Constants.DEFAULT_SCALE, null),
null, null, Constants.DEFAULT_PRECISION, Constants.DEFAULT_SCALE, null, reference);
}
}
@Override
public String toString() {
if (value == null) {
return "";
} else if (typeKind.isGeospatial()) {
return value.toString();
} else {
try {
// TODO: set facets
return type.valueToString(value, null, null, Constants.DEFAULT_PRECISION, Constants.DEFAULT_SCALE, null);
} catch (EdmPrimitiveTypeException e) {
throw new IllegalArgumentException(e);
}
}
}
@Override
public boolean isEnum() {
return false;
}
@Override
public ClientEnumValue asEnum() {
return null;
}
@Override
public boolean isComplex() {
return false;
}
}
| apache-2.0 |
CapsHil/GLPOO_ESIEA_1516_Eternity_Raby | eternity/src/main/java/org/esiea/glpoo/eternity/combat/PariJoueurView.java | 3294 | package org.esiea.glpoo.eternity.combat;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class PariJoueurView extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -8803521798359307611L;
private JoueurReel utilisateur;
private Joueur joueurHaut, joueurBas;
private JLabel montant;
private JLabel joueur;
private JLabel argent;
private JLabel argentJoueur;
private JTextField montantPari;
private JRadioButton haut;
private JRadioButton bas;
private ButtonGroup joueurPari;
private JButton okButton;
private boolean pret;
private int pari;
public PariJoueurView (JoueurReel utilisateur, Joueur joueurHaut, Joueur joueurBas) {
super("Pariez sur un joueur !");
this.pret = false;
this.utilisateur = utilisateur;
this.joueurHaut = joueurHaut;
this.joueurBas = joueurBas;
this.initGui();
}
public boolean isPret() {
return pret;
}
public void initGui() {
Container cont = this.getContentPane();
cont.add(this.getPanel(), BorderLayout.CENTER);
this.setContentPane(cont);
this.setBounds(1000,700,400,250);
this.setVisible(true);
}
public JPanel getPanel() {
JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
montant = new JLabel("Montant");
joueur = new JLabel("Joueur");
argent = new JLabel("Argent");
argentJoueur = new JLabel(this.utilisateur.getArgent() + " $");
montantPari = new JTextField();
haut = new JRadioButton("Haut");
bas = new JRadioButton("Bas");
haut.setSelected(true);
joueurPari = new ButtonGroup();
joueurPari.add(haut);
joueurPari.add(bas);
okButton = new JButton("OK");
okButton.addActionListener(this);
panel.add(argent);
panel.add(argentJoueur);
panel.add(montant);
panel.add(montantPari);
panel.add(joueur);
panel.add(haut);
panel.add(new JLabel());
panel.add(bas);
panel.add(new JLabel());
panel.add(okButton);
return panel;
}
public void actionPerformed(ActionEvent e) {
ArrayList<String> erreurs = new ArrayList<String>();
try {
this.pari = Integer.parseInt(montantPari.getText());
if (this.pari <= 0)
erreurs.add("Le montant doit être supérieur à zéro");
if (this.pari > this.utilisateur.getArgent())
erreurs.add("Le montant doit inférieur ou égal à votre argent");
}
catch (NumberFormatException e1) {
erreurs.add("Le montant doit être un nombre");
}
if (erreurs.size() == 0) {
if (this.haut.isSelected())
this.utilisateur.setJoueurPari(this.joueurHaut);
else
this.utilisateur.setJoueurPari(this.joueurBas);
this.pret = true;
}
else {
String erreurMsg = "";
for (String ch : erreurs) {
erreurMsg += ch + "\n";
}
JOptionPane.showMessageDialog(null, erreurMsg, "Erreur ...", JOptionPane.ERROR_MESSAGE);
}
}
public int getPari() {
return pari;
}
}
| apache-2.0 |
agwlvssainokuni/sqlapp | src/main/java/cherry/sqlapp/db/dto/SqltoolClause.java | 1503 | /*
* Copyright 2014,2015 agwlvssainokuni
*
* 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 cherry.sqlapp.db.dto;
import java.io.Serializable;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.joda.time.LocalDateTime;
import cherry.foundation.type.DeletedFlag;
@Setter
@Getter
@EqualsAndHashCode(callSuper = false)
@ToString(callSuper = false)
public class SqltoolClause implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String databaseName;
private String selectClause;
private String fromClause;
private String whereClause;
private String groupByClause;
private String havingClause;
private String orderByClause;
private String paramMap;
private LocalDateTime updatedAt;
private LocalDateTime createdAt;
private Integer lockVersion;
private DeletedFlag deletedFlg;
}
| apache-2.0 |
cnbcg/yummynoodlebar-project | src/test/java/com/yummynoodlebar/core/services/OrderEventHandlerUnitTest.java | 4798 | package com.yummynoodlebar.core.services;
import static com.yummynoodlebar.persistence.domain.fixture.PersistenceFixture.orderReceived;
import static com.yummynoodlebar.persistence.domain.fixture.PersistenceFixture.standardOrder;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.yummynoodlebar.events.orders.CreateOrderEvent;
import com.yummynoodlebar.events.orders.DeleteOrderEvent;
import com.yummynoodlebar.events.orders.OrderDeletedEvent;
import com.yummynoodlebar.events.orders.OrderDetails;
import com.yummynoodlebar.persistence.domain.Order;
import com.yummynoodlebar.persistence.domain.OrderStatus;
import com.yummynoodlebar.persistence.repository.OrderStatusRepository;
import com.yummynoodlebar.persistence.repository.OrdersRepository;
import com.yummynoodlebar.persistence.services.OrderPersistenceEventHandler;
public class OrderEventHandlerUnitTest {
OrderEventHandler uut;
@Mock
OrdersRepository mockOrdersRepository;
@Mock
OrderStatusRepository mockOrderStatusRepository;
@Before
public void setupUnitUnderTest() {
MockitoAnnotations.initMocks(this);
uut = new OrderEventHandler(new OrderPersistenceEventHandler(mockOrdersRepository, mockOrderStatusRepository));
}
@Test
public void addANewOrderToTheSystem() {
Order order = standardOrder();
OrderStatus orderStatus = orderReceived(order.getKey());
when(mockOrdersRepository.save(any(Order.class))).thenReturn(order);
when(mockOrderStatusRepository.save(any(OrderStatus.class))).thenReturn(orderStatus);
CreateOrderEvent ev = new CreateOrderEvent(order.toOrderDetails());
uut.createOrder(ev);
verify(mockOrdersRepository).save(any(Order.class));
verify(mockOrderStatusRepository).save(any(OrderStatus.class));
verifyNoMoreInteractions(mockOrdersRepository);
verifyNoMoreInteractions(mockOrderStatusRepository);
}
@Test
public void addTwoNewOrdersToTheSystem() {
Order order = standardOrder();
OrderStatus orderStatus = orderReceived(order.getKey());
when(mockOrdersRepository.save(any(Order.class))).thenReturn(order);
when(mockOrderStatusRepository.save(any(OrderStatus.class))).thenReturn(orderStatus);
CreateOrderEvent ev = new CreateOrderEvent(order.toOrderDetails());
uut.createOrder(ev);
uut.createOrder(ev);
verify(mockOrdersRepository, times(2)).save(any(Order.class));
verify(mockOrderStatusRepository, times(2)).save(any(OrderStatus.class));
verifyNoMoreInteractions(mockOrdersRepository);
verifyNoMoreInteractions(mockOrderStatusRepository);
}
@Test
public void removeAnOrderFromTheSystemFailsIfNotPresent() {
UUID key = UUID.randomUUID();
when(mockOrdersRepository.findOne(key)).thenReturn(null);
DeleteOrderEvent ev = new DeleteOrderEvent(key);
OrderDeletedEvent orderDeletedEvent = uut.deleteOrder(ev);
verify(mockOrdersRepository, never()).delete(ev.getKey());
assertFalse(orderDeletedEvent.isEntityFound());
assertFalse(orderDeletedEvent.isDeletionCompleted());
assertEquals(key, orderDeletedEvent.getKey());
}
@Test
public void removeAnOrderFromTheSystemFailsIfNotPermitted() {
OrderDetails orderDetails = new OrderDetails();
orderDetails.setCanBeDeleted(Boolean.FALSE);
Order order = Order.fromOrderDetails(orderDetails);
UUID key = order.getKey();
when(mockOrdersRepository.findOne(key)).thenReturn(order);
DeleteOrderEvent ev = new DeleteOrderEvent(key);
OrderDeletedEvent orderDeletedEvent = uut.deleteOrder(ev);
verify(mockOrdersRepository, never()).delete(ev.getKey());
assertTrue(orderDeletedEvent.isEntityFound());
assertFalse(orderDeletedEvent.isDeletionCompleted());
assertEquals(key, orderDeletedEvent.getKey());
}
@Test
public void removeAnOrderFromTheSystemWorksIfExists() {
OrderDetails orderDetails = new OrderDetails();
Order order = Order.fromOrderDetails(orderDetails);
order.setCanBeDeleted(Boolean.TRUE);
UUID key = order.getKey();
when(mockOrdersRepository.findOne(any(UUID.class))).thenReturn(order);
DeleteOrderEvent ev = new DeleteOrderEvent(key);
OrderDeletedEvent orderDeletedEvent = uut.deleteOrder(ev);
verify(mockOrdersRepository).delete(ev.getKey());
assertTrue(orderDeletedEvent.isEntityFound());
assertTrue(orderDeletedEvent.isDeletionCompleted());
assertEquals(key, orderDeletedEvent.getKey());
}
}
| apache-2.0 |
google-code-export/google-api-dfp-java | src/com/google/api/ads/dfp/v201302/LineItemCreativeAssociationAction.java | 5348 | /**
* LineItemCreativeAssociationAction.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.v201302;
/**
* Represents the actions that can be performed on
* {@link LineItemCreativeAssociation} objects.
*/
public abstract class LineItemCreativeAssociationAction implements java.io.Serializable {
/* Indicates that this instance is a subtype of LineItemCreativeAssociationAction.
* Although this field is returned in the response, it is ignored on
* input
* and cannot be selected. Specify xsi:type instead. */
private java.lang.String lineItemCreativeAssociationActionType;
public LineItemCreativeAssociationAction() {
}
public LineItemCreativeAssociationAction(
java.lang.String lineItemCreativeAssociationActionType) {
this.lineItemCreativeAssociationActionType = lineItemCreativeAssociationActionType;
}
/**
* Gets the lineItemCreativeAssociationActionType value for this LineItemCreativeAssociationAction.
*
* @return lineItemCreativeAssociationActionType * Indicates that this instance is a subtype of LineItemCreativeAssociationAction.
* Although this field is returned in the response, it is ignored on
* input
* and cannot be selected. Specify xsi:type instead.
*/
public java.lang.String getLineItemCreativeAssociationActionType() {
return lineItemCreativeAssociationActionType;
}
/**
* Sets the lineItemCreativeAssociationActionType value for this LineItemCreativeAssociationAction.
*
* @param lineItemCreativeAssociationActionType * Indicates that this instance is a subtype of LineItemCreativeAssociationAction.
* Although this field is returned in the response, it is ignored on
* input
* and cannot be selected. Specify xsi:type instead.
*/
public void setLineItemCreativeAssociationActionType(java.lang.String lineItemCreativeAssociationActionType) {
this.lineItemCreativeAssociationActionType = lineItemCreativeAssociationActionType;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof LineItemCreativeAssociationAction)) return false;
LineItemCreativeAssociationAction other = (LineItemCreativeAssociationAction) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.lineItemCreativeAssociationActionType==null && other.getLineItemCreativeAssociationActionType()==null) ||
(this.lineItemCreativeAssociationActionType!=null &&
this.lineItemCreativeAssociationActionType.equals(other.getLineItemCreativeAssociationActionType())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getLineItemCreativeAssociationActionType() != null) {
_hashCode += getLineItemCreativeAssociationActionType().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(LineItemCreativeAssociationAction.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "LineItemCreativeAssociationAction"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lineItemCreativeAssociationActionType");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "LineItemCreativeAssociationAction.Type"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
lobbin/tapestry-spring-security | src/test/java/nu/localhost/tapestry5/springsecurity/validator/PermissionValidatorTest.java | 3452 | package nu.localhost.tapestry5.springsecurity.validator;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import org.apache.tapestry5.Field;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.ioc.MessageFormatter;
import org.apache.tapestry5.services.FormSupport;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Tests for PermissionValidator validator.
*
* @author ferengra
*/
public class PermissionValidatorTest {
private static final String USER = "user";
private static final String PERMISSION = "permissionValue";
private static final String LABEL = "label";
private PermissionValidator victim;
private Field field;
private MessageFormatter formatter;
@BeforeMethod
public void setUp() {
victim = new PermissionValidator();
field = mock(Field.class);
when(field.getLabel()).thenReturn(LABEL);
formatter = mock(MessageFormatter.class);
when(formatter.format(PERMISSION, LABEL)).thenReturn(PermissionValidator.MESSAGE);
}
@AfterMethod
public void tearDown() {
SecurityContextHolder.clearContext();
}
@Test(expectedExceptions = {ValidationException.class})
public void validateNoAuthentication() throws ValidationException {
try {
victim.validate(field, PERMISSION, formatter, null);
fail("Expected exception");
} catch (ValidationException e) {
assertEquals(e.getMessage(), PermissionValidator.MESSAGE);
throw e;
}
}
@Test
public void validate() throws ValidationException {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(USER, null, PERMISSION));
victim.validate(field, PERMISSION, formatter, null);
}
@Test
public void validateList() throws ValidationException {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(USER, null, PERMISSION));
victim.validate(field, "dummy;" + PERMISSION, formatter, null);
}
@Test(expectedExceptions = {ValidationException.class})
public void validateException() throws ValidationException {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(USER, null));
try {
victim.validate(field, PERMISSION, formatter, null);
fail("Expected exception");
} catch (ValidationException e) {
assertEquals(e.getMessage(), PermissionValidator.MESSAGE);
verify(field).getLabel();
verify(formatter).format(PERMISSION, LABEL);
throw e;
}
}
@Test
public void render() throws ValidationException {
FormSupport formSupport = mock(FormSupport.class);
victim.render(field, PERMISSION, formatter, null, formSupport);
verify(field).getLabel();
verify(formatter).format(PERMISSION, LABEL);
verify(formSupport).addValidation(field, PermissionValidator.NAME, PermissionValidator.MESSAGE, PERMISSION);
}
}
| apache-2.0 |
eFaps/eFaps-Kernel-Install | src/main/efaps/ESJP/org/efaps/esjp/common/jasperreport/JasperFileResolver.java | 1115 | /*
* Copyright 2003 - 2020 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.efaps.esjp.common.jasperreport;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
/**
* This class must be replaced for customization, therefore it is left empty.
* Functional description can be found in the related "<code>_Base</code>"
* class.
*
* @author The eFaps Team
*/
@EFapsUUID("5e89e2ee-4247-4dab-a9e3-eacaefd9ae02")
@EFapsApplication("eFaps-Kernel")
public class JasperFileResolver
extends JasperFileResolver_Base
{
}
| apache-2.0 |
TakayukiKando/LoreLang | Lore/LoreAST/src/main/java/org/xgmtk/lore/ast/tree/ASTVisitor.java | 3824 | /*
* Copyright 2016 Inuyama-ya sanp <develop@xgmtk.org>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xgmtk.lore.ast.tree;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.function.Consumer;
/**
* AST(Abstract Syntax Tree) visitor class.
* This visitor visits nodes of the specified subtree of the AST,
* and it visits node with depth-first manner.
* User can register 2 actions.
* The 1st action is called in the time of the entering to a new node.
* The 2nd action is called in the time of the leaving from the node.
*
* @author Takayuki,Kando <develop@xgmtk.org>
*/
public class ASTVisitor {
/**
* This class is used to an entry of stack.
*/
private class Entry{
public final ASTNode node;
public int index;
public Entry(ASTNode node){
this.node = node;
this.index = 0;
}
}
/**
* Default action for entering/leaving the node.
* This action does nothing.
*/
public static final Consumer<ASTNode> DEFAULT_ACTION = n->{};
private Consumer<ASTNode> enterAction;
private Consumer<ASTNode> leaveAction;
private Deque<Entry> stack;
/**
* Initialize AST visitor.
*
* @param enterAction The action is called in the time of the entering to a new node.
* @param leaveAction The action is called in the time of the leaving from the node.
*/
public ASTVisitor(Consumer<ASTNode> enterAction, Consumer<ASTNode> leaveAction){
this.setEnterAction(enterAction);
this.setLeaveAction(leaveAction);
this.stack = new ArrayDeque<>();
}
/**
* Initialize AST visitor with default actions.
*/
public ASTVisitor(){
this(DEFAULT_ACTION, DEFAULT_ACTION);
}
/**
* Set the action which is called in the time of the entering to a new node.
*
* @param action The action is called in the time of the entering to a new node.
*/
public final void setEnterAction(Consumer<ASTNode> action){
this.enterAction = action;
}
/**
* Set the action which is called in the time of the leaving from the node.
*
* @param action The action is called in the time of the leaving from the node.
*/
public final void setLeaveAction(Consumer<ASTNode> action){
this.leaveAction = action;
}
/**
* Start visiting.
*
* @param root The root node of the visiting subtree.
*/
void start(ASTNode root) {
Entry current = new Entry(root);
this.enterAction.accept(current.node);
for(;;){
if(current.index < current.node.children().size()){
Entry next = new Entry(current.node.children().get(current.index));
++current.index;
this.stack.push(current);
current = next;
this.enterAction.accept(current.node);
continue;
}
this.leaveAction.accept(current.node);
if(this.stack.isEmpty()){
break;
}
current = this.stack.pop();
}
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_7215.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_7215 {
}
| apache-2.0 |
makeok/zhw-util | src/com/zhw/web/listener/StartTimerServletContextListener.java | 3805 | package com.zhw.web.listener;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.zhw.core.log.Syslog;
import sun.misc.Signal;
import sun.misc.SignalHandler;
/**
* @功能描述: 自动启动
* @开发人员:
* @创建日期: 2013-5-15 下午1:25:13
*/
@SuppressWarnings("restriction")
public class StartTimerServletContextListener implements ServletContextListener , SignalHandler {
private ServletContext context = null;
/*
* This method is invoked when the Web Application has been removed and is no
* longer able to accept requests
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
// Output a simple message to the server's console
Syslog.out("The Simple Web App. Has Been Removed");
Syslog.error("The Simple Web App. Has Been Removed");
this.context = null;
doExit();
}
// This method is invoked when the Web Application
// is ready to service requests
// WEB进程自动调用此过程启动作业调度
@Override
public void contextInitialized(ServletContextEvent event) {
try {
Syslog.info("启动成功!");
//获取serveletContent
this.context = event.getServletContext();
/*
* 注册JVM钩子,在JVM关闭之前做一些收尾的工作,当然也能阻止TOMCAT的关闭;必须放在contextInitialized中注册。
*/
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
doExit();
}
}));
//注册信号
StartTimerServletContextListener testSignalHandler = new StartTimerServletContextListener();
// install signals
Signal.handle(new Signal("TERM"), testSignalHandler);
Signal.handle(new Signal("ILL"), testSignalHandler);
Signal.handle(new Signal("ABRT"), testSignalHandler);
Signal.handle(new Signal("INT"), testSignalHandler);
Signal.handle(new Signal("TERM"), testSignalHandler);
}
catch (Exception ex) {
Syslog.error("启动失败");
ex.printStackTrace();
}
}
@Override
public void handle(Signal sn) {
// TODO Auto-generated method stub
System.out.println(sn.getName()+" is recevied.");
doExit();
}
/*
* webapp 退出函数
*/
public void doExit(){
int n = 0;
while (n < 10) {
Syslog.info(Thread.currentThread() + "," + n++);
System.out.println("ShutdownHook "+n++);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
StartTimerServletContextListener testSignalHandler = new StartTimerServletContextListener();
// install signals
Signal.handle(new Signal("TERM"), testSignalHandler);
Signal.handle(new Signal("ILL"), testSignalHandler);
Signal.handle(new Signal("ABRT"), testSignalHandler);
Signal.handle(new Signal("INT"), testSignalHandler);
Signal.handle(new Signal("TERM"), testSignalHandler);
// Signal.handle(new Signal("FPE"), testSignalHandler);
// Signal.handle(new Signal("BREAK"), testSignalHandler);
// Signal.handle(new Signal("USR1"), testSignalHandler);
// Signal.handle(new Signal("USR2"), testSignalHandler);
// SEGV, ILL, FPE, ABRT, INT, TERM, BREAK
// SEGV, , FPE, BUS, SYS, CPU, FSZ, ABRT, INT, TERM, HUP, USR1, USR2, QUIT, BREAK, TRAP, PIPE
for (;;) {
Thread.sleep(3000);
System.out.println("running......");
}
}
}
| apache-2.0 |
tosanboom/java-sdk | src/main/java/ir/boommarket/Json.java | 2829 | package ir.boommarket;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
/**
* Utilities for JSON serialization/de-serialization
*
* @author ALi Dehghani
*/
public class Json {
private static final ObjectMapper mapper = getObjectMapper();
private static final MediaType JSON_TYPE = MediaType.parse("application/json;charset=UTF-8");
private static ObjectMapper getObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));
mapper.setTimeZone(TimeZone.getTimeZone("UTC"));
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(ANY));
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
/**
* Create a JSON {@linkplain RequestBody} from the passed pojo
*
* @param pojo The pojo to convert to a JSON string
* @return A {@linkplain RequestBody} wrapping the jsonified pojo as its request body
* with a proper {@code Content-Type}
* @throws JsonException When something went wrong with json serialization
*/
public static RequestBody of(Object pojo) {
try {
return RequestBody.create(JSON_TYPE, mapper.writeValueAsString(pojo));
} catch (JsonProcessingException e) {
throw new JsonException("Couldn't generate a JSON string from " + pojo, e);
}
}
/**
* Convert the json string to a class specified by the given {@code clazz} parameter
*
* @param jsonStr String representation of a json
* @param clazz Encapsulates type information of the destination pojo
* @param <T> Type of the destination pojo
* @return An instance of {@linkplain T} corresponding to the given json string
* @throws JsonException When something went wrong with json de-serialization process
*/
public static <T> T read(String jsonStr, Class<T> clazz) {
try {
return mapper.readValue(jsonStr, clazz);
} catch (IOException e) {
throw new JsonException("Couldn't map the " + jsonStr + " to the " + clazz + " type", e);
}
}
} | apache-2.0 |
gawkermedia/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201602/ImageError.java | 4169 | /**
* ImageError.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201602;
/**
* Lists all errors associated with images.
*/
public class ImageError extends com.google.api.ads.dfp.axis.v201602.ApiError implements java.io.Serializable {
/* The error reason represented by an enum. */
private com.google.api.ads.dfp.axis.v201602.ImageErrorReason reason;
public ImageError() {
}
public ImageError(
java.lang.String fieldPath,
java.lang.String trigger,
java.lang.String errorString,
com.google.api.ads.dfp.axis.v201602.ImageErrorReason reason) {
super(
fieldPath,
trigger,
errorString);
this.reason = reason;
}
/**
* Gets the reason value for this ImageError.
*
* @return reason * The error reason represented by an enum.
*/
public com.google.api.ads.dfp.axis.v201602.ImageErrorReason getReason() {
return reason;
}
/**
* Sets the reason value for this ImageError.
*
* @param reason * The error reason represented by an enum.
*/
public void setReason(com.google.api.ads.dfp.axis.v201602.ImageErrorReason reason) {
this.reason = reason;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof ImageError)) return false;
ImageError other = (ImageError) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.reason==null && other.getReason()==null) ||
(this.reason!=null &&
this.reason.equals(other.getReason())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getReason() != null) {
_hashCode += getReason().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(ImageError.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "ImageError"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("reason");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "reason"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "ImageError.Reason"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
gchq/stroom | stroom-search/stroom-search-solr/src/main/java/stroom/search/solr/search/HasHighlights.java | 777 | /*
* Copyright 2016 Crown Copyright
*
* 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 stroom.search.solr.search;
import java.util.Set;
public interface HasHighlights {
Set<String> getHighlights();
void setHighlights(Set<String> highlights);
}
| apache-2.0 |
rPraml/org.openntf.domino | domino/deprecated/src/main/java/org/openntf/domino/helpers/ClientClockParser.java | 3205 | package org.openntf.domino.helpers;
import java.util.List;
/*
* @author Nathan T. Freeman
* Parser for console.log contents that trace NRPC API calls in Notes client
*
*/
@Deprecated
public class ClientClockParser {
/*
* Example console.log
*
[1C2C:0002-1084] (264-5929 [264]) DB_MODIFIED_TIME(REP80257839:005DE04A): 94 ms. [18+82=100]
[1C2C:0002-1084] (265-5929 [265]) OPEN_COLLECTION(REP80257839:005DE04A-NT0006C376,0000,0000): 105 ms. [46+38=84]
[1C2C:0002-1084] (266-5929 [266]) FIND_BY_KEY_EXTENDED2(REP80257839:005DE04A): 123 ms. [418+34=452] (Unsupported return flag(s))
[1C2C:0002-1084] (267-5929 [267]) FIND_BY_KEY(REP80257839:005DE04A): 168 ms. [416+42=458]
[1C2C:0002-1084] (268-5929 [268]) READ_ENTRIES(REP80257839:005DE04A-NT0006C376): 125 ms. [72+142=214]
[1C2C:0002-1084] (269-5929 [269]) OPEN_DB(CN=COMMONNAME/OU=OrgUnit/O=ACME CORP!!helpdesk\Knowledge Base.nsf): (Opened: REP80257839:005E0A6F) 138 ms. [126+182=308]
[1C2C:0002-1084] (270-5929 [270]) DB_MODIFIED_TIME(REP80257839:005E0A6F): 147 ms. [18+80=98]
[1C2C:0002-1084] (271-5930 [271]) ISDB2_RQST(REP80257839:005E0A6F): 176 ms. [18+20=38]
[1C2C:0002-1084] (272-5930 [272]) OPEN_COLLECTION(REP80257839:005E0A6F-NTFFFF0020,0000,1000): 132 ms. [50+606=656]
[1C2C:0002-1084] (273-5930 [273]) READ_ENTRIES(REP80257839:005E0A6F-NTFFFF0020,Since:06/25/2014 04:10:46 PM): 218 ms. [142+1418=1560]
[1C2C:0002-1084] (274-5930 [274]) CLOSE_COLLECTION(REP80257839:005E0A6F-NTFFFF0020): 0 ms. [16+0=16]
[1C2C:0002-1084] (275-5930 [275]) DB_MODIFIED_TIME(REP80257839:005E0A6F): 163 ms. [18+80=98]
[1C2C:0002-1084] (276-5930 [276]) GET_MULT_NOTE_INFO_BY_UNID(REP80257839:005E0A6F): 155 ms. [192+348=540]
[1C2C:0002-1084] (277-5930 [277]) DB_MODIFIED_TIME(REP80257839:005E0A6F): 80 ms. [18+80=98]
[1C2C:0002-1084] (278-5930 [278]) GET_UNREAD_NOTE_TABLE(REP80257839:005E0A6F): 79 ms. [78+122=200]
[1C2C:0002-1084] (279-5931 [279]) OPEN_NOTE(REP80257839:005E0A6F-NTFFFF0010,03000400): 74 ms. [52+2888=2940]
*/
public static enum Function {
DB_MODIFIED_TIME, OPEN_COLLECTION, FIND_BY_KEY_EXTENDED2, FIND_BY_KEY, READ_ENTRIES, OPEN_DB, ISDB2_RQST, CLOSE_COLLECTION,
GET_MULT_NOTE_INFO_BY_UNID, GET_UNREAD_NOTE_TABLE, OPEN_NOTE, GET_LAST_INDEX_TIME, GET_SPECIAL_NOTE_ID, GET_NAMED_OBJECT_ID,
DB_REPLINFO_GET, GET_NOTE_INFO, SERVER_AVAILABLE_LITE, GET_MODIFIED_NOTES, READ_OBJECT, GETOBJECT_RQST, CLOSE_DB, OPEN_SESSION,
POLL_DEL_SEQNUM
}
@SuppressWarnings("unused")
public static class APIOp {
private Function function_;
private String replicaid_;
private String noteid_;
private String threadId_;
private int txnId_;
private int clockcount_;
private int time_;
private int bytesSent_;
private int bytesReceived_;
private int bytesTotal_;
private String[] args_;
private String message_;
// [1C2C:0002-1084] [1C2C:0002-1084] (273-5930 [273]) READ_ENTRIES(REP80257839:005E0A6F-NTFFFF0020,Since:06/25/2014 04:10:46 PM): 218 ms. [142+1418=1560]
public APIOp(final String log) {
}
}
@SuppressWarnings("unused")
public static class APIOpGroup {
private int startClock_;
private int endClock_;
private List<APIOp> operations_;
}
public ClientClockParser() {
}
}
| apache-2.0 |
GregSaintJean/Beacon | src/com/therabbitmage/android/beacon/provider/MobileContactsQuery.java | 932 | package com.therabbitmage.android.beacon.provider;
import android.annotation.TargetApi;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import com.therabbitmage.android.beacon.utils.AndroidUtils;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public interface MobileContactsQuery{
final static int MOBILE_QUERY_ID = 1;
final static Uri CONTENT_URI = Data.CONTENT_URI;
final static String[] PROJECTION = {
Data._ID,
AndroidUtils.honeycombOrBetter() ? Data.DISPLAY_NAME_PRIMARY : Data.DISPLAY_NAME,
Phone.NUMBER,
Phone.TYPE,
Phone.LABEL
};
final static String SELECTION = Phone.TYPE + "='" + Phone.TYPE_MOBILE + "' AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'";
final static String SORT_ORDER = AndroidUtils.honeycombOrBetter() ? Phone.DISPLAY_NAME_PRIMARY : Phone.DISPLAY_NAME;
}
| apache-2.0 |
vespa-engine/vespa | vespa-http-client/src/main/java/com/yahoo/vespa/http/client/core/JsonReader.java | 9791 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.http.client.core;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonFactoryBuilder;
import com.fasterxml.jackson.core.JsonParser;
import com.yahoo.vespa.http.client.FeedClient;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Reads a stream of json documents and sends them to feedClient.
*
* @author dybis
*/
public class JsonReader {
/**
* Max size of documents. As we stream docs in for finding doc id, we buffer the data and later stream them to
* feedclient after doc id has been revealed.
*/
private final static int maxDocumentSizeChars = 50 * 1024 * 1024;
// Intended to be used as static.
private JsonReader() {}
/**
* Process one inputstream and send all documents to feedclient.
*
* @param inputStream source of array of json document.
* @param feedClient where data is sent.
* @param numSent counter to be incremented for every document streamed.
*/
public static void read(InputStream inputStream, FeedClient feedClient, AtomicInteger numSent) {
try (InputStreamJsonElementBuffer jsonElementBuffer = new InputStreamJsonElementBuffer(inputStream)) {
JsonFactory jfactory = new JsonFactoryBuilder().disable(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES).build();
JsonParser jParser = jfactory.createParser(jsonElementBuffer);
while (true) {
int documentStart = (int) jParser.getCurrentLocation().getCharOffset();
String docId = parseOneDocument(jParser);
if (docId == null) {
int documentEnd = (int) jParser.getCurrentLocation().getCharOffset();
int documentLength = documentEnd - documentStart;
int maxTruncatedLength = 500;
StringBuilder stringBuilder = new StringBuilder(maxTruncatedLength + 3);
for (int i = 0; i < Math.min(documentLength, maxTruncatedLength); i++)
stringBuilder.append(jsonElementBuffer.circular.get(documentStart + i));
if (documentLength > maxTruncatedLength)
stringBuilder.append("...");
throw new IllegalArgumentException("Document is missing ID: '" + stringBuilder.toString() + "'");
}
CharSequence data = jsonElementBuffer.getJsonAsArray(jParser.getCurrentLocation().getCharOffset());
feedClient.stream(docId, data);
numSent.incrementAndGet();
}
} catch (EOFException ignored) {
// No more documents
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
throw new UncheckedIOException(ioe);
}
}
/**
* This class is intended to be used with a json parser. The data is sent through this intermediate stream
* and to the parser. When the parser is done with a document, it calls postJsonAsArray which will
* stream the document up to the current position of the parser.
*/
private static class InputStreamJsonElementBuffer extends InputStreamReader {
/**
* Simple class implementing a circular array with some custom function used for finding start and end
* of json object. The reason this is needed is that the json parser reads more than it parses
* from the input stream (seems like about 8k). Using a ByteBuffer and manually moving data
* is an order of magnitude slower than this implementation.
*/
private class CircularCharBuffer {
int readPointer = 0;
int writePointer = 0;
final char[] data;
final int size;
public CircularCharBuffer(int chars) {
data = new char[chars];
size = chars;
}
/**
* This is for throwing away [ and spaces in front of a json object, and find the position of {.
* Not for parsing much text.
*
* @return position for {
*/
public int findNextObjectStart() {
int readerPos = 0;
while (get(readerPos) != '{') {
readerPos++;
assert(readerPos<=size);
}
return readerPos;
}
/**
* This is for throwing away comma and or ], and for finding the position of the last }.
* @param fromPos where to start searching
* @return position for }
*/
public int findLastObjectEnd(int fromPos) {
while (get(fromPos-1) != '}') {
fromPos--;
assert(fromPos >=0);
}
return fromPos;
}
public void put(char dataByte) {
data[writePointer] = dataByte;
writePointer++;
if (writePointer >= size) writePointer = 0;
assert(writePointer != readPointer);
}
public char get(int pos) {
int readPos = readPointer + pos;
if (readPos >= size) readPos -= size;
assert(readPos != writePointer);
return data[readPos];
}
public void advance(int end) {
readPointer += end;
if (readPointer >= size) readPointer -= size;
}
}
private final CircularCharBuffer circular = new CircularCharBuffer(maxDocumentSizeChars);
private int processedChars = 0;
public InputStreamJsonElementBuffer(InputStream inputStream) {
super(inputStream, StandardCharsets.UTF_8);
}
/**
* Removes comma, start/end array tag (last element), spaces etc that might be surrounding a json element.
* Then sends the element to the outputstream.
* @param parserPosition how far the parser has come. Please note that the parser might have processed
* more data from the input source as it is reading chunks of data.
* @throws IOException on errors
*/
public CharSequence getJsonAsArray(long parserPosition) throws IOException {
final int charSize = (int)parserPosition - processedChars;
final int endPosOfJson = circular.findLastObjectEnd(charSize);
final int startPosOfJson = circular.findNextObjectStart();
processedChars += charSize;
// This can be optimized since we rarely wrap the circular buffer.
StringBuilder dataBuffer = new StringBuilder(endPosOfJson - startPosOfJson);
for (int x = startPosOfJson; x < endPosOfJson; x++) {
dataBuffer.append(circular.get(x));
}
circular.advance(charSize);
return dataBuffer.toString();
}
@Override
public int read(char[] b, int off, int len) throws IOException {
int length = 0;
int value = 0;
while (length < len && value != -1) {
value = read();
if (value == -1) {
return length == 0 ? -1 : length;
}
b[off + length] = (char) value;
length++;
}
return length;
}
@Override
public int read() throws IOException {
int value = super.read();
if (value >= 0) circular.put((char)value);
return value;
}
}
/**
* Parse one document from the stream and return doc id.
*
* @param jParser parser with stream.
* @return doc id of document or null if no more docs.
* @throws IOException on problems
*/
private static String parseOneDocument(JsonParser jParser) throws IOException {
int objectLevel = 0;
String documentId = null;
boolean foundObject = false;
boolean valueIsDocumentId = false;
while (jParser.nextToken() != null) {
String tokenAsText = jParser.getText();
if (valueIsDocumentId) {
if (documentId != null) {
throw new RuntimeException("Several document ids");
}
documentId = tokenAsText;
valueIsDocumentId = false;
}
switch(jParser.getCurrentToken()) {
case START_OBJECT:
foundObject = true;
objectLevel++;
break;
case END_OBJECT:
objectLevel--;
if (objectLevel == 0) {
return documentId;
}
break;
case FIELD_NAME:
if (objectLevel == 1 &&
(tokenAsText.equals("put")
|| tokenAsText.endsWith("id")
|| tokenAsText.endsWith("update")
|| tokenAsText.equals("remove"))) {
valueIsDocumentId = true;
}
break;
default: // No operation on all other tags.
}
}
if (!foundObject)
throw new EOFException("No more documents");
return null;
}
}
| apache-2.0 |
trajano/maven | maven-embedder/src/main/java/org/apache/maven/cli/CLIManager.java | 10521 | package org.apache.maven.cli;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.PrintStream;
import java.io.PrintWriter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
/**
* @author Jason van Zyl
*/
public class CLIManager
{
public static final char ALTERNATE_POM_FILE = 'f';
public static final char BATCH_MODE = 'B';
public static final char SET_SYSTEM_PROPERTY = 'D';
public static final char OFFLINE = 'o';
public static final char QUIET = 'q';
public static final char DEBUG = 'X';
public static final char ERRORS = 'e';
public static final char HELP = 'h';
public static final char VERSION = 'v';
public static final char SHOW_VERSION = 'V';
public static final char NON_RECURSIVE = 'N';
public static final char UPDATE_SNAPSHOTS = 'U';
public static final char ACTIVATE_PROFILES = 'P';
public static final String SUPRESS_SNAPSHOT_UPDATES = "nsu";
public static final char CHECKSUM_FAILURE_POLICY = 'C';
public static final char CHECKSUM_WARNING_POLICY = 'c';
public static final char ALTERNATE_USER_SETTINGS = 's';
public static final String ALTERNATE_GLOBAL_SETTINGS = "gs";
public static final char ALTERNATE_USER_TOOLCHAINS = 't';
public static final String ALTERNATE_GLOBAL_TOOLCHAINS = "gt";
public static final String FAIL_FAST = "ff";
public static final String FAIL_AT_END = "fae";
public static final String FAIL_NEVER = "fn";
public static final String RESUME_FROM = "rf";
public static final String PROJECT_LIST = "pl";
public static final String ALSO_MAKE = "am";
public static final String ALSO_MAKE_DEPENDENTS = "amd";
public static final String LOG_FILE = "l";
public static final String ENCRYPT_MASTER_PASSWORD = "emp";
public static final String ENCRYPT_PASSWORD = "ep";
public static final String THREADS = "T";
public static final String LEGACY_LOCAL_REPOSITORY = "llr";
public static final String BUILDER = "b";
protected Options options;
@SuppressWarnings( { "static-access", "checkstyle:linelength" } )
public CLIManager()
{
options = new Options();
options.addOption( OptionBuilder.withLongOpt( "help" ).withDescription( "Display help information" ).create( HELP ) );
options.addOption( OptionBuilder.withLongOpt( "file" ).hasArg().withDescription( "Force the use of an alternate POM file (or directory with pom.xml, disables output color)" ).create( ALTERNATE_POM_FILE ) );
options.addOption( OptionBuilder.withLongOpt( "define" ).hasArg().withDescription( "Define a system property" ).create( SET_SYSTEM_PROPERTY ) );
options.addOption( OptionBuilder.withLongOpt( "offline" ).withDescription( "Work offline" ).create( OFFLINE ) );
options.addOption( OptionBuilder.withLongOpt( "version" ).withDescription( "Display version information" ).create( VERSION ) );
options.addOption( OptionBuilder.withLongOpt( "quiet" ).withDescription( "Quiet output - only show errors" ).create( QUIET ) );
options.addOption( OptionBuilder.withLongOpt( "debug" ).withDescription( "Produce execution debug output" ).create( DEBUG ) );
options.addOption( OptionBuilder.withLongOpt( "errors" ).withDescription( "Produce execution error messages" ).create( ERRORS ) );
options.addOption( OptionBuilder.withLongOpt( "non-recursive" ).withDescription( "Do not recurse into sub-projects" ).create( NON_RECURSIVE ) );
options.addOption( OptionBuilder.withLongOpt( "update-snapshots" ).withDescription( "Forces a check for missing releases and updated snapshots on remote repositories" ).create( UPDATE_SNAPSHOTS ) );
options.addOption( OptionBuilder.withLongOpt( "activate-profiles" ).withDescription( "Comma-delimited list of profiles to activate" ).hasArg().create( ACTIVATE_PROFILES ) );
options.addOption( OptionBuilder.withLongOpt( "batch-mode" ).withDescription( "Run in non-interactive (batch) mode (disables output color)" ).create( BATCH_MODE ) );
options.addOption( OptionBuilder.withLongOpt( "no-snapshot-updates" ).withDescription( "Suppress SNAPSHOT updates" ).create( SUPRESS_SNAPSHOT_UPDATES ) );
options.addOption( OptionBuilder.withLongOpt( "strict-checksums" ).withDescription( "Fail the build if checksums don't match" ).create( CHECKSUM_FAILURE_POLICY ) );
options.addOption( OptionBuilder.withLongOpt( "lax-checksums" ).withDescription( "Warn if checksums don't match" ).create( CHECKSUM_WARNING_POLICY ) );
options.addOption( OptionBuilder.withLongOpt( "settings" ).withDescription( "Alternate path for the user settings file" ).hasArg().create( ALTERNATE_USER_SETTINGS ) );
options.addOption( OptionBuilder.withLongOpt( "global-settings" ).withDescription( "Alternate path for the global settings file" ).hasArg().create( ALTERNATE_GLOBAL_SETTINGS ) );
options.addOption( OptionBuilder.withLongOpt( "toolchains" ).withDescription( "Alternate path for the user toolchains file" ).hasArg().create( ALTERNATE_USER_TOOLCHAINS ) );
options.addOption( OptionBuilder.withLongOpt( "global-toolchains" ).withDescription( "Alternate path for the global toolchains file" ).hasArg().create( ALTERNATE_GLOBAL_TOOLCHAINS ) );
options.addOption( OptionBuilder.withLongOpt( "fail-fast" ).withDescription( "Stop at first failure in reactorized builds" ).create( FAIL_FAST ) );
options.addOption( OptionBuilder.withLongOpt( "fail-at-end" ).withDescription( "Only fail the build afterwards; allow all non-impacted builds to continue" ).create( FAIL_AT_END ) );
options.addOption( OptionBuilder.withLongOpt( "fail-never" ).withDescription( "NEVER fail the build, regardless of project result" ).create( FAIL_NEVER ) );
options.addOption( OptionBuilder.withLongOpt( "resume-from" ).hasArg().withDescription( "Resume reactor from specified project" ).create( RESUME_FROM ) );
options.addOption( OptionBuilder.withLongOpt( "projects" ).withDescription( "Comma-delimited list of specified reactor projects to build instead of all projects. A project can be specified by [groupId]:artifactId or by its relative path." ).hasArg().create( PROJECT_LIST ) );
options.addOption( OptionBuilder.withLongOpt( "also-make" ).withDescription( "If project list is specified, also build projects required by the list" ).create( ALSO_MAKE ) );
options.addOption( OptionBuilder.withLongOpt( "also-make-dependents" ).withDescription( "If project list is specified, also build projects that depend on projects on the list" ).create( ALSO_MAKE_DEPENDENTS ) );
options.addOption( OptionBuilder.withLongOpt( "log-file" ).hasArg().withDescription( "Log file where all build output will go." ).create( LOG_FILE ) );
options.addOption( OptionBuilder.withLongOpt( "show-version" ).withDescription( "Display version information WITHOUT stopping build" ).create( SHOW_VERSION ) );
options.addOption( OptionBuilder.withLongOpt( "encrypt-master-password" ).hasOptionalArg().withDescription( "Encrypt master security password" ).create( ENCRYPT_MASTER_PASSWORD ) );
options.addOption( OptionBuilder.withLongOpt( "encrypt-password" ).hasOptionalArg().withDescription( "Encrypt server password" ).create( ENCRYPT_PASSWORD ) );
options.addOption( OptionBuilder.withLongOpt( "threads" ).hasArg().withDescription( "Thread count, for instance 2.0C where C is core multiplied" ).create( THREADS ) );
options.addOption( OptionBuilder.withLongOpt( "legacy-local-repository" ).withDescription( "Use Maven 2 Legacy Local Repository behaviour, ie no use of _remote.repositories. Can also be activated by using -Dmaven.legacyLocalRepo=true" ).create( LEGACY_LOCAL_REPOSITORY ) );
options.addOption( OptionBuilder.withLongOpt( "builder" ).hasArg().withDescription( "The id of the build strategy to use." ).create( BUILDER ) );
// Adding this back in for compatibility with the verifier that hard codes this option.
options.addOption( OptionBuilder.withLongOpt( "no-plugin-registry" ).withDescription( "Ineffective, only kept for backward compatibility" ).create( "npr" ) );
options.addOption( OptionBuilder.withLongOpt( "check-plugin-updates" ).withDescription( "Ineffective, only kept for backward compatibility" ).create( "cpu" ) );
options.addOption( OptionBuilder.withLongOpt( "update-plugins" ).withDescription( "Ineffective, only kept for backward compatibility" ).create( "up" ) );
options.addOption( OptionBuilder.withLongOpt( "no-plugin-updates" ).withDescription( "Ineffective, only kept for backward compatibility" ).create( "npu" ) );
}
public CommandLine parse( String[] args )
throws ParseException
{
// We need to eat any quotes surrounding arguments...
String[] cleanArgs = CleanArgument.cleanArgs( args );
CommandLineParser parser = new GnuParser();
return parser.parse( options, cleanArgs );
}
public void displayHelp( PrintStream stdout )
{
stdout.println();
PrintWriter pw = new PrintWriter( stdout );
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( pw, HelpFormatter.DEFAULT_WIDTH, "mvn [options] [<goal(s)>] [<phase(s)>]", "\nOptions:",
options, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, "\n", false );
pw.flush();
}
}
| apache-2.0 |
uchenm/CnChess | src/chess/utils/DeepClone.java | 1519 | package chess.utils;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Utility for making deep copies (vs. clone()'s shallow copies) of objects.
* Objects are first serialized and then deserialized. Error checking is fairly
* minimal in this implementation. If an object is encountered that cannot be
* serialized (or that references an object that cannot be serialized) an error
* is printed to System.err and null is returned. Depending on your specific
* application, it might make more sense to have copy(...) re-throw the
* exception.
*/
public class DeepClone {
/**
* Returns a copy of the object, or null if the object cannot be serialized.
*/
public static Object clone(Object orig) {
Object obj = null;
try {
// Write the object out to a byte array
FastByteArrayOutputStream fbos = new FastByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(fbos);
out.writeObject(orig);
out.flush();
out.close();
// Retrieve an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(fbos.getInputStream());
obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}
| apache-2.0 |
otto-de/edison-microservice | edison-validation/src/main/java/de/otto/edison/validation/validators/EnumValidator.java | 1273 | package de.otto.edison.validation.validators;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class EnumValidator implements ConstraintValidator<IsEnum, String> {
private Set<String> availableEnumNames;
private boolean ignoreCase;
private boolean allowNull;
@Override
@SuppressWarnings("rawtypes")
public void initialize(IsEnum annotation) {
Class<? extends Enum<?>> enumClass = annotation.enumClass();
availableEnumNames = Stream.of(enumClass.getEnumConstants())
.map(Enum::name)
.collect(Collectors.toSet());
ignoreCase = annotation.ignoreCase();
allowNull = annotation.allowNull();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return allowNull;
} else {
return availableEnumNames.stream().anyMatch(o -> {
if (ignoreCase) {
return o.equalsIgnoreCase(value);
} else {
return o.equals(value);
}
});
}
}
}
| apache-2.0 |
bobmcwhirter/drools | drools-guvnor/src/main/java/org/drools/guvnor/server/builder/ContentAssemblyError.java | 1281 | package org.drools.guvnor.server.builder;
/*
* Copyright 2005 JBoss 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.
*/
import org.drools.repository.VersionableItem;
/**
* This class is used to accumulate error reports for asset.
* This can then be used to feed back to the user where the problems are.
*
* @author Michael Neale
*/
public class ContentAssemblyError {
public ContentAssemblyError(VersionableItem it, String message) {
this.itemInError = it;
this.errorReport = message;
}
/**
* This may be null, if its not associated to any particular asset.
*/
public VersionableItem itemInError;
public String errorReport;
public String toString() {
return this.errorReport;
}
} | apache-2.0 |
DBCDK/fcrepo-3.5-patched | fcrepo-security/fcrepo-security-pep/src/main/java/org/fcrepo/server/security/xacml/pep/rest/objectshandlers/ListDatastreams.java | 17693 | /*
* File: ListDatastreams.java
*
* Copyright 2009 2DC
*
* 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.fcrepo.server.security.xacml.pep.rest.objectshandlers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import com.sun.xacml.attr.AnyURIAttribute;
import com.sun.xacml.attr.AttributeValue;
import com.sun.xacml.attr.DateTimeAttribute;
import com.sun.xacml.attr.StringAttribute;
import com.sun.xacml.ctx.RequestCtx;
import com.sun.xacml.ctx.ResponseCtx;
import com.sun.xacml.ctx.Result;
import com.sun.xacml.ctx.Status;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.tidy.Tidy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.fcrepo.common.Constants;
import org.fcrepo.server.security.xacml.MelcoeXacmlException;
import org.fcrepo.server.security.xacml.pep.PEPException;
import org.fcrepo.server.security.xacml.pep.rest.filters.AbstractFilter;
import org.fcrepo.server.security.xacml.pep.rest.filters.DataResponseWrapper;
import org.fcrepo.server.security.xacml.util.ContextUtil;
import org.fcrepo.server.security.xacml.util.LogUtil;
/**
* Handles the ListDatastreams operation.
*
* @author nish.naidoo@gmail.com
*/
public class ListDatastreams
extends AbstractFilter {
private static final Logger logger =
LoggerFactory.getLogger(ListDatastreams.class);
private ContextUtil contextUtil = null;
private Transformer xFormer = null;
private Tidy tidy = null;
/**
* Default constructor.
*
* @throws PEPException
*/
public ListDatastreams()
throws PEPException {
super();
contextUtil = ContextUtil.getInstance();
try {
TransformerFactory xFactory = TransformerFactory.newInstance();
xFormer = xFactory.newTransformer();
} catch (TransformerConfigurationException tce) {
throw new PEPException("Error initialising SearchFilter", tce);
}
tidy = new Tidy();
tidy.setShowWarnings(false);
tidy.setQuiet(true);
}
/*
* (non-Javadoc)
* @see
* org.fcrepo.server.security.xacml.pep.rest.filters.RESTFilter#handleRequest(javax.servlet
* .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public RequestCtx handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.debug(this.getClass().getName() + "/handleRequest!");
}
String path = request.getPathInfo();
String[] parts = path.split("/");
String pid = parts[1];
String asOfDateTime = request.getParameter("asOfDateTime");
if (!isDate(asOfDateTime)) {
asOfDateTime = null;
}
RequestCtx req = null;
Map<URI, AttributeValue> actions = new HashMap<URI, AttributeValue>();
Map<URI, AttributeValue> resAttr = new HashMap<URI, AttributeValue>();
try {
if (pid != null && !"".equals(pid)) {
resAttr.put(Constants.OBJECT.PID.getURI(),
new StringAttribute(pid));
}
if (pid != null && !"".equals(pid)) {
resAttr.put(new URI(XACML_RESOURCE_ID),
new AnyURIAttribute(new URI(pid)));
}
if (asOfDateTime != null && !"".equals(asOfDateTime)) {
resAttr.put(Constants.DATASTREAM.AS_OF_DATETIME.getURI(),
DateTimeAttribute.getInstance(asOfDateTime));
}
actions.put(Constants.ACTION.ID.getURI(),
new StringAttribute(Constants.ACTION.LIST_DATASTREAMS
.getURI().toASCIIString()));
actions.put(Constants.ACTION.API.getURI(),
new StringAttribute(Constants.ACTION.APIA.getURI()
.toASCIIString()));
req =
getContextHandler().buildRequest(getSubjects(request),
actions,
resAttr,
getEnvironment(request));
LogUtil.statLog(request.getRemoteUser(),
Constants.ACTION.LIST_DATASTREAMS.getURI()
.toASCIIString(),
pid,
null);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
return req;
}
/*
* (non-Javadoc)
* @see
* org.fcrepo.server.security.xacml.pep.rest.filters.RESTFilter#handleResponse(javax.servlet
* .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public RequestCtx handleResponse(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
DataResponseWrapper res = (DataResponseWrapper) response;
byte[] data = res.getData();
String result = null;
String body = new String(data);
if (body.startsWith("<html>")) {
if (logger.isDebugEnabled()) {
logger.debug("filtering html");
}
result = filterHTML(request, res);
} else if (body.startsWith("<?xml")) {
if (logger.isDebugEnabled()) {
logger.debug("filtering html");
}
result = filterXML(request, res);
} else {
if (logger.isDebugEnabled()) {
logger.debug("not filtering due to unexpected output: " + body);
}
result = body;
}
res.setData(result.getBytes());
return null;
}
/**
* Parses an HTML based response and removes the items that are not
* permitted.
*
* @param request
* the http servlet request
* @param response
* the http servlet response
* @return the new response body without non-permissable objects.
* @throws ServletException
*/
private String filterHTML(HttpServletRequest request,
DataResponseWrapper response)
throws ServletException {
String path = request.getPathInfo();
String[] parts = path.split("/");
String pid = parts[1];
String body = new String(response.getData());
InputStream is = new ByteArrayInputStream(body.getBytes());
Document doc = tidy.parseDOM(is, null);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList rows = null;
try {
rows =
(NodeList) xpath.evaluate("//table[2]/tr",
doc,
XPathConstants.NODESET);
if (logger.isDebugEnabled()) {
logger.debug("number of rows found: " + rows.getLength());
}
} catch (XPathExpressionException xpe) {
throw new ServletException("Error parsing HTML for search results: ",
xpe);
}
// only the header row, no results.
if (rows.getLength() < 2) {
if (logger.isDebugEnabled()) {
logger.debug("No results to filter.");
}
return body;
}
Map<String, Node> dsids = new HashMap<String, Node>();
for (int x = 1; x < rows.getLength(); x++) {
NodeList elements = rows.item(x).getChildNodes();
String dsid = elements.item(0).getFirstChild().getNodeValue();
if (logger.isDebugEnabled()) {
logger.debug("dsid: " + dsid);
}
dsids.put(dsid, rows.item(x));
}
Set<Result> results =
evaluatePids(dsids.keySet(), pid, request, response);
for (Result r : results) {
if (r.getResource() == null || "".equals(r.getResource())) {
logger.warn("This resource has no resource identifier in the xacml response results!");
} else if (logger.isDebugEnabled()) {
logger.debug("Checking: " + r.getResource());
}
String[] ridComponents = r.getResource().split("\\/");
String rid = ridComponents[ridComponents.length - 1];
if (r.getStatus().getCode().contains(Status.STATUS_OK)
&& r.getDecision() != Result.DECISION_PERMIT) {
Node node = dsids.get(rid);
node.getParentNode().removeChild(node);
if (logger.isDebugEnabled()) {
logger.debug("Removing: " + r.getResource() + "[" + rid + "]");
}
}
}
Source src = new DOMSource(doc);
ByteArrayOutputStream os = new ByteArrayOutputStream();
javax.xml.transform.Result dst = new StreamResult(os);
try {
xFormer.transform(src, dst);
} catch (TransformerException te) {
throw new ServletException("error generating output", te);
}
return new String(os.toByteArray());
}
/**
* Parses an XML based response and removes the items that are not
* permitted.
*
* @param request
* the http servlet request
* @param response
* the http servlet response
* @return the new response body without non-permissable objects.
* @throws ServletException
*/
private String filterXML(HttpServletRequest request,
DataResponseWrapper response)
throws ServletException {
String body = new String(response.getData());
DocumentBuilder docBuilder = null;
Document doc = null;
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
docBuilder =
docBuilderFactory.newDocumentBuilder();
doc =
docBuilder.parse(new ByteArrayInputStream(response
.getData()));
} catch (Exception e) {
throw new ServletException(e);
}
XPath xpath = XPathFactory.newInstance().newXPath();
String pid = null;
NodeList datastreams = null;
try {
pid = xpath.evaluate("/objectDatastreams/@pid", doc);
if (logger.isDebugEnabled()) {
logger.debug("filterXML: pid = [" + pid + "]");
}
datastreams =
(NodeList) xpath.evaluate("/objectDatastreams/datastream",
doc,
XPathConstants.NODESET);
} catch (XPathExpressionException xpe) {
throw new ServletException("Error parsing HTML for search results: ",
xpe);
}
if (datastreams.getLength() == 0) {
if (logger.isDebugEnabled()) {
logger.debug("No results to filter.");
}
return body;
}
Map<String, Node> dsids = new HashMap<String, Node>();
for (int x = 0; x < datastreams.getLength(); x++) {
String dsid =
datastreams.item(x).getAttributes().getNamedItem("dsid")
.getNodeValue();
dsids.put(dsid, datastreams.item(x));
}
Set<Result> results =
evaluatePids(dsids.keySet(), pid, request, response);
for (Result r : results) {
if (r.getResource() == null || "".equals(r.getResource())) {
logger.warn("This resource has no resource identifier in the xacml response results!");
} else if (logger.isDebugEnabled()) {
logger.debug("Checking: " + r.getResource());
}
String[] ridComponents = r.getResource().split("\\/");
String rid = ridComponents[ridComponents.length - 1];
if (r.getStatus().getCode().contains(Status.STATUS_OK)
&& r.getDecision() != Result.DECISION_PERMIT) {
Node node = dsids.get(rid);
node.getParentNode().removeChild(node);
if (logger.isDebugEnabled()) {
logger.debug("Removing: " + r.getResource() + "[" + rid + "]");
}
}
}
Source src = new DOMSource(doc);
ByteArrayOutputStream os = new ByteArrayOutputStream();
javax.xml.transform.Result dst = new StreamResult(os);
try {
xFormer.transform(src, dst);
} catch (TransformerException te) {
throw new ServletException("error generating output", te);
}
return new String(os.toByteArray());
}
/**
* Takes a given list of PID's and evaluates them.
*
* @param dsids
* the list of pids to check
* @param request
* the http servlet request
* @param response
* the http servlet resposne
* @return a set of XACML results.
* @throws ServletException
*/
private Set<Result> evaluatePids(Set<String> dsids,
String pid,
HttpServletRequest request,
DataResponseWrapper response)
throws ServletException {
Set<String> requests = new HashSet<String>();
for (String dsid : dsids) {
if (logger.isDebugEnabled()) {
logger.debug("Checking: " + pid + "/" + dsid);
}
Map<URI, AttributeValue> actions =
new HashMap<URI, AttributeValue>();
Map<URI, AttributeValue> resAttr =
new HashMap<URI, AttributeValue>();
try {
actions.put(Constants.ACTION.ID.getURI(),
new StringAttribute(Constants.ACTION.GET_DATASTREAM
.getURI().toASCIIString()));
resAttr.put(Constants.OBJECT.PID.getURI(),
new StringAttribute(pid));
resAttr.put(new URI(XACML_RESOURCE_ID),
new AnyURIAttribute(new URI(pid)));
resAttr.put(Constants.DATASTREAM.ID.getURI(),
new StringAttribute(dsid));
RequestCtx req =
getContextHandler()
.buildRequest(getSubjects(request),
actions,
resAttr,
getEnvironment(request));
String r = contextUtil.makeRequestCtx(req);
if (logger.isDebugEnabled()) {
logger.debug(r);
}
requests.add(r);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
String res = null;
ResponseCtx resCtx = null;
try {
if (logger.isDebugEnabled()) {
logger.debug("Number of requests: " + requests.size());
}
res =
getContextHandler().evaluateBatch(requests
.toArray(new String[requests.size()]));
if (logger.isDebugEnabled()) {
logger.debug("Response: " + res);
}
resCtx = contextUtil.makeResponseCtx(res);
} catch (MelcoeXacmlException pe) {
throw new ServletException("Error evaluating pids: "
+ pe.getMessage(), pe);
}
@SuppressWarnings("unchecked")
Set<Result> results = resCtx.getResults();
return results;
}
}
| apache-2.0 |
pinotlytics/pinot | pinot-core/src/test/java/com/linkedin/pinot/core/common/docidsets/BitmapDocIdSetTest.java | 4730 | /**
* Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.pinot.core.common.docidsets;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.TreeSet;
import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
import org.roaringbitmap.buffer.MutableRoaringBitmap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.linkedin.pinot.common.data.FieldSpec.DataType;
import com.linkedin.pinot.core.common.BlockDocIdIterator;
import com.linkedin.pinot.core.common.BlockMetadata;
import com.linkedin.pinot.core.common.Constants;
import com.linkedin.pinot.core.operator.docidsets.BitmapDocIdSet;
import com.linkedin.pinot.core.segment.index.readers.Dictionary;
public class BitmapDocIdSetTest {
private static final Logger LOGGER = LoggerFactory.getLogger(BitmapDocIdSetTest.class);
@Test
public void testSimple() throws IOException {
int numBitMaps = 5;
final int numDocs = 1000;
List<ImmutableRoaringBitmap> list = new ArrayList<ImmutableRoaringBitmap>();
Random r = new Random();
TreeSet<Integer> originalSet = new TreeSet<Integer>();
for (int i = 0; i < numBitMaps; i++) {
MutableRoaringBitmap mutableRoaringBitmap = new MutableRoaringBitmap();
int length = r.nextInt(numDocs);
for (int j = 0; j < length; j++) {
int docId = r.nextInt(numDocs);
originalSet.add(docId);
mutableRoaringBitmap.add(docId);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
// could call "rr1.runOptimize()" and "rr2.runOptimize" if there
// there were runs to compress
mutableRoaringBitmap.serialize(dos);
dos.close();
ByteBuffer bb = ByteBuffer.wrap(bos.toByteArray());
ImmutableRoaringBitmap immutableRoaringBitmap = new ImmutableRoaringBitmap(bb);
list.add(immutableRoaringBitmap);
}
ImmutableRoaringBitmap[] bitmaps = new ImmutableRoaringBitmap[list.size()];
list.toArray(bitmaps);
BlockMetadata blockMetadata = new BlockMetadata() {
@Override
public boolean isSparse() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isSorted() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isSingleValue() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean hasInvertedIndex() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean hasDictionary() {
// TODO Auto-generated method stub
return false;
}
@Override
public int getStartDocId() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getSize() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getMaxNumberOfMultiValues() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getLength() {
return numDocs;
}
@Override
public int getEndDocId() {
return numDocs;
}
@Override
public Dictionary getDictionary() {
// TODO Auto-generated method stub
return null;
}
@Override
public DataType getDataType() {
// TODO Auto-generated method stub
return null;
}
};
BitmapDocIdSet bitmapDocIdSet = new BitmapDocIdSet("testColumn", blockMetadata, bitmaps);
BlockDocIdIterator iterator = bitmapDocIdSet.iterator();
int docId;
TreeSet<Integer> result = new TreeSet<Integer>();
while ((docId = iterator.next()) != Constants.EOF) {
result.add(docId);
}
Assert.assertEquals(originalSet.size(), result.size());
Assert.assertEquals(originalSet, result);
}
}
| apache-2.0 |
deleidos/digitaledge-platform | master/src/main/java/com/deleidos/rtws/master/core/client/SecurityGroupClientException.java | 12595 | /**
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "{}"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright {yyyy} {name of copyright owner}
*
* 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.deleidos.rtws.master.core.client;
public class SecurityGroupClientException extends Exception {
private static final long serialVersionUID = 3889820978936911754L;
public SecurityGroupClientException() {
super();
// TODO Auto-generated constructor stub
}
public SecurityGroupClientException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public SecurityGroupClientException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public SecurityGroupClientException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
| apache-2.0 |
xiepengchong/FactoryZxing | src/com/alibaba/fastjson/util/Base64.java | 7930 | package com.alibaba.fastjson.util;
import java.util.Arrays;
/**
*
* @version 2.2
* @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11
*/
public class Base64 {
public static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
public static final int[] IA = new int[256];
static {
Arrays.fill(IA, -1);
for (int i = 0, iS = CA.length; i < iS; i++)
IA[CA[i]] = i;
IA['='] = 0;
}
/**
* Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as
* fast as #decode(char[]). The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within
* the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param chars The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(char[] chars, int offset, int charsLen) {
// Check special case
if (charsLen == 0) {
return new byte[0];
}
int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[chars[sIx]] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[chars[eIx]] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = chars[eIx] == '=' ? (chars[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = charsLen > 76 ? (chars[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] bytes = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[chars[sIx++]] << 18 | IA[chars[sIx++]] << 12 | IA[chars[sIx++]] << 6 | IA[chars[sIx++]];
// Add the bytes
bytes[d++] = (byte) (i >> 16);
bytes[d++] = (byte) (i >> 8);
bytes[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[chars[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
bytes[d++] = (byte) (i >> r);
}
return bytes;
}
public final static byte[] decodeFast(String chars, int offset, int charsLen) {
// Check special case
if (charsLen == 0) {
return new byte[0];
}
int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[chars.charAt(sIx)] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[chars.charAt(eIx)] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = chars.charAt(eIx) == '=' ? (chars.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = charsLen > 76 ? (chars.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] bytes = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[chars.charAt(sIx++)] << 18 | IA[chars.charAt(sIx++)] << 12 | IA[chars.charAt(sIx++)] << 6 | IA[chars.charAt(sIx++)];
// Add the bytes
bytes[d++] = (byte) (i >> 16);
bytes[d++] = (byte) (i >> 8);
bytes[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[chars.charAt(sIx++)] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
bytes[d++] = (byte) (i >> r);
}
return bytes;
}
/**
* Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as fast
* as decode(String). The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within
* the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(String s) {
// Check special case
int sLen = s.length();
if (sLen == 0) {
return new byte[0];
}
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6
| IA[s.charAt(sIx++)];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[s.charAt(sIx++)] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
}
| apache-2.0 |