repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
quarkusio/quarkus | extensions/smallrye-reactive-messaging-amqp/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/amqp/SecuredAmqpTest.java | 1273 | package io.quarkus.smallrye.reactivemessaging.amqp;
import static org.awaitility.Awaitility.await;
import org.apache.activemq.artemis.protocol.amqp.broker.ProtonProtocolManagerFactory;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
import io.restassured.RestAssured;
public class SecuredAmqpTest {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(ConsumingBean.class, ProducingBean.class, TestResource.class,
SecuredAmqpBroker.class, ProtonProtocolManagerFactory.class)
.addAsResource("broker.xml"))
.setBeforeAllCustomizer(SecuredAmqpBroker::start)
.setAfterAllCustomizer(SecuredAmqpBroker::stop)
.withConfigurationResource("application-secured.properties");
@Test
public void test() {
await().until(() -> {
String value = RestAssured.get("/last").asString();
return value.equalsIgnoreCase("20");
});
}
}
| apache-2.0 |
pravega/pravega | client/src/main/java/io/pravega/client/stream/notifications/notifier/EndOfDataNotifier.java | 2759 | /**
* Copyright Pravega 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 io.pravega.client.stream.notifications.notifier;
import java.util.concurrent.ScheduledExecutorService;
import com.google.common.annotations.VisibleForTesting;
import io.pravega.client.state.StateSynchronizer;
import io.pravega.client.stream.impl.ReaderGroupState;
import io.pravega.client.stream.notifications.EndOfDataNotification;
import io.pravega.client.stream.notifications.Listener;
import io.pravega.client.stream.notifications.NotificationSystem;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EndOfDataNotifier extends AbstractPollingNotifier<EndOfDataNotification> {
private static final int UPDATE_INTERVAL_SECONDS = Integer.parseInt(
System.getProperty("pravega.client.endOfDataNotification.poll.interval.seconds", String.valueOf(120)));
public EndOfDataNotifier(final NotificationSystem notifySystem,
final StateSynchronizer<ReaderGroupState> synchronizer,
final ScheduledExecutorService executor) {
super(notifySystem, executor, synchronizer);
}
/**
* Invokes the periodic processing now in the current thread.
*/
@VisibleForTesting
public void pollNow() {
this.checkAndTriggerEndOfStreamNotification();
}
@Override
@Synchronized
public void registerListener(final Listener<EndOfDataNotification> listener) {
notifySystem.addListeners(getType(), listener, this.executor);
//periodically check the for end of stream.
startPolling(this::checkAndTriggerEndOfStreamNotification, UPDATE_INTERVAL_SECONDS);
}
@Override
public String getType() {
return EndOfDataNotification.class.getSimpleName();
}
private void checkAndTriggerEndOfStreamNotification() {
this.synchronizer.fetchUpdates();
ReaderGroupState state = this.synchronizer.getState();
if (state == null) {
log.warn("Current state of StateSynchronizer {} is null, will try again.", synchronizer);
} else if (state.isEndOfData()) {
notifySystem.notify(new EndOfDataNotification());
}
}
}
| apache-2.0 |
vespa-engine/vespa | documentapi/src/main/java/com/yahoo/documentapi/messagebus/protocol/RoundRobinPolicy.java | 4030 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.documentapi.messagebus.protocol;
import com.yahoo.jrt.slobrok.api.Mirror;
import com.yahoo.messagebus.EmptyReply;
import com.yahoo.messagebus.Error;
import com.yahoo.messagebus.ErrorCode;
import com.yahoo.messagebus.Reply;
import com.yahoo.messagebus.routing.Hop;
import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.routing.RoutingContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This policy implements round-robin selection of the configured recipients that are currently registered in slobrok.
*
* @author Simon Thoresen Hult
*/
public class RoundRobinPolicy implements DocumentProtocolRoutingPolicy {
private final Map<String, CacheEntry> cache = new HashMap<String, CacheEntry>();
// Inherit doc from RoutingPolicy.
public void select(RoutingContext ctx) {
Hop hop = getRecipient(ctx);
if (hop != null) {
Route route = new Route(ctx.getRoute());
route.setHop(0, hop);
ctx.addChild(route);
} else {
Reply reply = new EmptyReply();
reply.addError(new Error(ErrorCode.NO_ADDRESS_FOR_SERVICE,
"None of the configured recipients are currently available."));
ctx.setReply(reply);
}
}
// Inherit doc from RoutingPolicy.
public void merge(RoutingContext ctx) {
DocumentProtocol.merge(ctx);
}
/**
* Returns the appropriate recipient hop for the given routing context. This method provides synchronized access to
* the internal cache.
*
* @param ctx The routing context.
* @return The recipient hop to use.
*/
private synchronized Hop getRecipient(RoutingContext ctx) {
CacheEntry entry = update(ctx);
if (entry.recipients.isEmpty()) {
return null;
}
if (++entry.offset >= entry.recipients.size()) {
entry.offset = 0;
}
return new Hop(entry.recipients.get(entry.offset));
}
/**
* Updates and returns the cache entry for the given routing context. This method assumes that synchronization is
* handled outside of it.
*
* @param ctx The routing context.
* @return The updated cache entry.
*/
private CacheEntry update(RoutingContext ctx) {
String key = getCacheKey(ctx);
CacheEntry entry = cache.get(key);
if (entry == null) {
entry = new CacheEntry();
cache.put(key, entry);
}
int upd = ctx.getMirror().updates();
if (entry.generation != upd) {
entry.generation = upd;
entry.recipients.clear();
for (int i = 0; i < ctx.getNumRecipients(); ++i) {
List<Mirror.Entry> arr = ctx.getMirror().lookup(ctx.getRecipient(i).getHop(0).toString());
for (Mirror.Entry item : arr) {
entry.recipients.add(Hop.parse(item.getName()));
}
}
}
return entry;
}
/**
* Returns a cache key for this instance of the policy. Because behaviour is based on the recipient list of this
* policy, the cache key is the concatenated string of recipient routes.
*
* @param ctx The routing context.
* @return The cache key.
*/
private String getCacheKey(RoutingContext ctx) {
StringBuilder ret = new StringBuilder();
for (int i = 0; i < ctx.getNumRecipients(); ++i) {
ret.append(ctx.getRecipient(i).getHop(0).toString()).append(" ");
}
return ret.toString();
}
/**
* Defines the necessary cache data.
*/
private class CacheEntry {
private final List<Hop> recipients = new ArrayList<Hop>();
private int generation = 0;
private int offset = 0;
}
public void destroy() {
}
}
| apache-2.0 |
vespa-engine/vespa | jrt/src/com/yahoo/jrt/XorCryptoSocket.java | 4167 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.security.SecureRandom;
import java.util.ArrayDeque;
import java.util.Queue;
/**
* A very simple CryptoSocket that performs connection handshaking and
* data transformation. Used to test encryption integration separate
* from TLS.
*
* @author havardpe
*/
public class XorCryptoSocket implements CryptoSocket {
private static final int CHUNK_SIZE = 4096;
enum OP { READ_KEY, WRITE_KEY }
private Queue<OP> opList = new ArrayDeque<>();
private byte myKey = genKey();
private byte peerKey;
private Buffer input = new Buffer(CHUNK_SIZE);
private Buffer output = new Buffer(CHUNK_SIZE);
private SocketChannel channel;
private static byte genKey() {
return (byte) new SecureRandom().nextInt(256);
}
private HandshakeResult readKey() throws IOException {
int res = channel.read(input.getWritable(1));
if (res > 0) {
peerKey = input.getReadable().get();
return HandshakeResult.DONE;
} else if (res == 0) {
return HandshakeResult.NEED_READ;
} else {
throw new IOException("EOF during handshake");
}
}
private HandshakeResult writeKey() throws IOException {
if (output.bytes() == 0) {
output.getWritable(1).put(myKey);
}
if (channel.write(output.getReadable()) == 0) {
return HandshakeResult.NEED_WRITE;
}
return HandshakeResult.DONE;
}
private HandshakeResult perform(OP op) throws IOException {
switch (op) {
case READ_KEY: return readKey();
case WRITE_KEY: return writeKey();
}
throw new IOException("invalid handshake operation");
}
public XorCryptoSocket(SocketChannel channel, boolean isServer) {
this.channel = channel;
if (isServer) {
opList.add(OP.READ_KEY);
opList.add(OP.WRITE_KEY);
} else {
opList.add(OP.WRITE_KEY);
opList.add(OP.READ_KEY);
}
}
@Override public SocketChannel channel() { return channel; }
@Override public HandshakeResult handshake() throws IOException {
while (!opList.isEmpty()) {
HandshakeResult partialResult = perform(opList.element());
if (partialResult != HandshakeResult.DONE) {
return partialResult;
}
opList.remove();
}
return HandshakeResult.DONE;
}
@Override public void doHandshakeWork() {}
@Override public int getMinimumReadBufferSize() { return 1; }
@Override public int read(ByteBuffer dst) throws IOException {
if (input.bytes() == 0) {
if (channel.read(input.getWritable(CHUNK_SIZE)) == -1) {
return -1; // EOF
}
}
return drain(dst);
}
@Override public int drain(ByteBuffer dst) throws IOException {
int cnt = 0;
ByteBuffer src = input.getReadable();
while (src.hasRemaining() && dst.hasRemaining()) {
dst.put((byte)(src.get() ^ myKey));
cnt++;
}
return cnt;
}
@Override public int write(ByteBuffer src) throws IOException {
int cnt = 0;
if (flush() == FlushResult.DONE) {
ByteBuffer dst = output.getWritable(CHUNK_SIZE);
while (src.hasRemaining() && dst.hasRemaining()) {
dst.put((byte)(src.get() ^ peerKey));
cnt++;
}
}
return cnt;
}
@Override public FlushResult flush() throws IOException {
ByteBuffer src = output.getReadable();
channel.write(src);
if (src.hasRemaining()) {
return FlushResult.NEED_WRITE;
} else {
return FlushResult.DONE;
}
}
@Override public void dropEmptyBuffers() {
input.shrink(0);
output.shrink(0);
}
}
| apache-2.0 |
qameta/rarc | rarc-core/src/main/java/ru/lanwen/raml/rarc/api/ra/ActionMethod.java | 2423 | package ru.lanwen.raml.rarc.api.ra;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeVariableName;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.raml.model.Action;
import ru.lanwen.raml.rarc.api.Method;
import javax.lang.model.element.Modifier;
import java.util.function.Function;
import static org.apache.commons.lang3.StringUtils.defaultIfEmpty;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;
/**
* @author lanwen (Merkushev Kirill)
*/
public class ActionMethod implements Method {
private String reqFieldName;
private String respFieldName;
private String httpMethod;
private String uriConst;
private String name;
private Action action;
public ActionMethod(ReqSpecField reqFieldName, RespSpecField respFieldName, UriConst uriConst, Action action) {
this.reqFieldName = reqFieldName.name();
this.respFieldName = respFieldName.name();
this.uriConst = uriConst.name();
this.action = action;
this.httpMethod = action.getType().name().toLowerCase();
this.name = defaultIfEmpty(action.getDisplayName(), httpMethod);
}
@Override
public MethodSpec methodSpec() {
ParameterSpec handler = ParameterSpec.builder(
ParameterizedTypeName.get(ClassName.get(Function.class),
ClassName.get(Response.class), ClassName.bestGuess("T")), "handler").build();
return MethodSpec.methodBuilder(isNotEmpty(name) ? name : httpMethod)
.addModifiers(Modifier.PUBLIC)
.addTypeVariable(TypeVariableName.get("T"))
.returns(ClassName.bestGuess("T"))
.addJavadoc("$L\n", trimToEmpty(action.getDescription()))
.addParameter(handler)
.addStatement("return $L.apply($T.given().spec($L.build()).expect().spec($L.build()).when().$L($L))",
handler.name,
RestAssured.class,
reqFieldName,
respFieldName,
httpMethod,
uriConst
).build();
}
}
| apache-2.0 |
adrobisch/brainslug | model/src/test/java/brainslug/flow/FlowBuilderTest.java | 12052 | package brainslug.flow;
import brainslug.flow.builder.FlowBuilder;
import brainslug.flow.definition.FlowDefinition;
import brainslug.flow.definition.Identifier;
import brainslug.flow.node.*;
import brainslug.flow.node.event.AbstractEventDefinition;
import brainslug.flow.node.event.EndEvent;
import brainslug.flow.node.event.IntermediateEvent;
import brainslug.flow.node.event.StartEvent;
import brainslug.flow.node.event.timer.StartTimerDefinition;
import brainslug.flow.node.task.GoalDefinition;
import brainslug.flow.node.task.GoalPredicate;
import brainslug.flow.node.task.RetryStrategy;
import brainslug.flow.node.task.Task;
import brainslug.util.IdUtil;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import static brainslug.util.FlowDefinitionAssert.assertThat;
import static brainslug.util.ID.*;
public class FlowBuilderTest {
interface MyService {
}
@Test
public void buildStartEndFlow() {
FlowBuilder flowBuilder = new FlowBuilder() {
@Override
public void define() {
start(event(id(StartEvent))).end(event(id(End)));
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(2)
.hasTotalEdges(1)
.hasNodesWithMarker(1, StartEvent.class)
.hasNodesWithMarker(1, EndEvent.class)
.hasEdge(StartEvent, End);
}
@Test
public void buildWaitEventFlow() {
FlowBuilder flowBuilder = new FlowBuilder() {
@Override
public void define() {
start(event(id(StartEvent))).waitFor(event(id(WaitEvent))).end(event(id(End)));
on(id(WaitEvent)).execute(task(id(Task6)).delegate(MyService.class));
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(4)
.hasTotalEdges(3)
.hasNodesWithMarker(1, IntermediateEvent.class)
.hasEdge(StartEvent, WaitEvent)
.hasEdge(WaitEvent, End)
.hasEdge(WaitEvent, Task6);
}
@Test
public void buildSingleTaskFlow() {
FlowBuilder flowBuilder = new FlowBuilder() {
@Override
public void define() {
start(event(id(StartEvent))).execute(task(id(TestTask))).end(event(id(End)));
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(3)
.hasTotalEdges(2)
.hasEdge(StartEvent, TestTask)
.hasEdge(TestTask, End);
}
@Test
public void buildTaskSequence() {
FlowBuilder flowBuilder = new FlowBuilder() {
@Override
public void define() {
start(event(id(StartEvent)))
.execute(task(id(TestTask)))
.execute(task(id(SecondTask)))
.end(event(id(End)));
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(4)
.hasTotalEdges(3)
.hasNodesWithType(2, TaskDefinition.class)
.hasNodesWithType(2, AbstractEventDefinition.class)
.hasEdge(StartEvent, TestTask)
.hasEdge(TestTask, SecondTask)
.hasEdge(SecondTask, End);
}
@Test
public void mergeWorksOnFlowNodeDefinitions() {
final TaskDefinition secondTask = FlowBuilder.task(FlowBuilder.id(SecondTask));
final TaskDefinition thirdTask = FlowBuilder.task(FlowBuilder.id(ThirdTask));
final Identifier mergeId = FlowBuilder.id(Merge);
FlowBuilder flowBuilder = new FlowBuilder() {
@Override
public void define() {
start(secondTask).execute(thirdTask);
merge(mergeId, secondTask, thirdTask);
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(3)
.hasNodesWithType(1, MergeDefinition.class)
.hasNodesWithType(2, TaskDefinition.class)
.hasEdge(secondTask.getId(), mergeId)
.hasEdge(thirdTask.getId(), mergeId);
}
@Test
public void joinWorksOnFlowNodeDefinitions() {
final TaskDefinition secondTask = FlowBuilder.task(FlowBuilder.id(SecondTask));
final TaskDefinition thirdTask = FlowBuilder.task(FlowBuilder.id(ThirdTask));
final Identifier joinId = FlowBuilder.id(Join);
FlowBuilder flowBuilder = new FlowBuilder() {
@Override
public void define() {
start(secondTask).execute(thirdTask);
join(joinId, secondTask, thirdTask);
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(3)
.hasNodesWithType(1, JoinDefinition.class)
.hasNodesWithType(2, TaskDefinition.class)
.hasEdge(secondTask.getId(), joinId)
.hasEdge(thirdTask.getId(), joinId);
}
@Test
public void buildChoiceWithMergeFlow() {
FlowBuilder flowBuilder = new FlowBuilder() {
Integer meaningOfLife = 42;
@Override
public void define() {
start(event(id(StartEvent)))
.choice(id(Choice))
.when(eq(constant(meaningOfLife), 42))
.execute(task(id(SecondTask)))
.or()
.when(eq(constant(meaningOfLife), 43))
.execute(task(id(ThirdTask)));
merge(id(Merge), id(SecondTask), id(ThirdTask)).end(event(id(EndEvent2)));
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(6)
.hasTotalEdges(6)
.hasNodesWithType(2, TaskDefinition.class)
.hasNodesWithType(2, AbstractEventDefinition.class)
.hasNodesWithType(1, ChoiceDefinition.class)
.hasNodesWithType(1, MergeDefinition.class)
.hasNodesWithMarker(1, EndEvent.class)
.hasNodesWithMarker(1, StartEvent.class)
.hasEdge(StartEvent, Choice)
.hasEdge(Choice, SecondTask)
.hasEdge(Choice, ThirdTask)
.hasEdge(SecondTask, Merge)
.hasEdge(ThirdTask, Merge)
.hasEdge(Merge, EndEvent2);
}
@Test
public void buildParallelWithJoinFlow() {
FlowBuilder flowBuilder = new FlowBuilder() {
@Override
public void define() {
start(event(id(StartEvent)))
.parallel(id(Parallel))
.execute(task(id(SecondTask)))
.and()
.execute(task(id(ThirdTask)));
join(id(Join), id(SecondTask), id(ThirdTask)).end(event(id(EndEvent2)));
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(6)
.hasTotalEdges(6)
.hasNodesWithType(2, TaskDefinition.class)
.hasNodesWithType(2, AbstractEventDefinition.class)
.hasNodesWithType(1, ParallelDefinition.class)
.hasNodesWithType(1, JoinDefinition.class)
.hasNodesWithMarker(1, EndEvent.class)
.hasNodesWithMarker(1, StartEvent.class)
.hasEdge(StartEvent, Parallel)
.hasEdge(Parallel, SecondTask)
.hasEdge(Parallel, ThirdTask)
.hasEdge(SecondTask, Join)
.hasEdge(ThirdTask, Join)
.hasEdge(Join, EndEvent2);
}
@Test
public void connectNodesWithAfter() {
FlowBuilder flowBuilder = new FlowBuilder() {
@Override
public void define() {
start(event(id(StartEvent))).execute(task(id(TestTask)));
after(id(TestTask)).execute(task(id(SecondTask)));
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(3)
.hasTotalEdges(2)
.hasNodesWithType(2, TaskDefinition.class)
.hasNodesWithType(1, AbstractEventDefinition.class)
.hasEdge(StartEvent, TestTask)
.hasEdge(TestTask, SecondTask);
}
@Test
public void buildComplexFlow() {
FlowBuilder flowBuilder = new FlowBuilder() {
Integer meaningOfLife = 42;
@Override
public void define() {
start(event(id(StartEvent))).execute(task(id(TestTask)));
after(id(TestTask))
.choice(id(Choice))
.when(eq(constant(meaningOfLife), 42))
.execute(task(id(SecondTask)))
.then()
.execute(task(id(FourthTask)))
.or()
.when(eq(constant(meaningOfLife), 43))
.execute(task(id(ThirdTask)))
.end(event(id(End)));
after(id(FourthTask))
.parallel(id(Parallel))
.execute(task(id(Task5))).end(event(id(EndEvent2)))
.and()
.waitFor(event(id(WaitEvent)));
on(id(WaitEvent)).execute(task(id(Task6)).delegate(MyService.class));
}
};
assertThat(flowBuilder.getDefinition())
.hasTotalNodes(12)
.hasTotalEdges(11)
.hasNodesWithType(6, TaskDefinition.class)
.hasNodesWithType(4, AbstractEventDefinition.class)
.hasNodesWithType(1, ParallelDefinition.class)
.hasNodesWithType(1, ChoiceDefinition.class)
.hasNodesWithMarker(2, EndEvent.class)
.hasNodesWithMarker(1, StartEvent.class)
.hasEdge(StartEvent, TestTask)
.hasEdge(TestTask, Choice)
.hasEdge(Choice, SecondTask)
.hasEdge(SecondTask, FourthTask)
.hasEdge(Choice, ThirdTask)
.hasEdge(ThirdTask, End)
.hasEdge(FourthTask, Parallel)
.hasEdge(Parallel, Task5)
.hasEdge(Task5, EndEvent2)
.hasEdge(Parallel, WaitEvent)
.hasEdge(WaitEvent, Task6);
}
@Test
public void buildFlowWithGoal() {
FlowDefinition goalFlow = new FlowBuilder() {
GoalDefinition taskExecutedGoal = goal(id("taskExecuted")).check(predicate(new GoalPredicate<Void>() {
@Override
public boolean isFulfilled(Void aVoid) {
return true;
}
}));
@Override
public void define() {
start(id("start"))
.execute(task(id("simpleTask"))
.retryAsync(true)
.goal(taskExecutedGoal))
.end(id("end"));
}
}.getDefinition();
TaskDefinition node = goalFlow.getNode(FlowBuilder.id("simpleTask"), TaskDefinition.class);
TaskDefinition taskNode = (TaskDefinition) node;
Assertions.assertThat(taskNode.isRetryAsync()).isTrue();
Assertions.assertThat(taskNode.getGoal().get().getId()).isEqualTo(FlowBuilder.id("taskExecuted"));
}
@Test
public void buildFlowWithInlineGoal() {
FlowDefinition goalFlow = new FlowBuilder() {
@Override
public void define() {
start(id("start"))
.execute(task(id("simpleTask"))
.goal(check(predicate(new GoalPredicate() {
@Override
public boolean isFulfilled(Object o) {
return false;
}
}))))
.end(id("end"));
}
}.getDefinition();
TaskDefinition taskNode = goalFlow.getNode(IdUtil.id("simpleTask"), TaskDefinition.class);
Assertions.assertThat(taskNode.getGoal()).isNotNull();
}
@Test
public void buildFlowWithRetryStrategy() {
FlowDefinition goalFlow = new FlowBuilder() {
@Override
public void define() {
RetryStrategy retryStrategy = new RetryStrategy() {
@Override
public Date nextRetry(long retryCount, Date baseDate) {
return new Date();
}
};
start(id("start"))
.execute(task(id("simpleTask")).retryAsync(true).retryStrategy(retryStrategy))
.end(id("end"));
}
}.getDefinition();
TaskDefinition taskNode = goalFlow.getNode(IdUtil.id("simpleTask"), TaskDefinition.class);
Assertions.assertThat(taskNode.isRetryAsync()).isTrue();
Assertions.assertThat(taskNode.getRetryStrategy()).isNotNull();
}
@Test
public void buildFlowWithRecurringTimer() {
FlowBuilder recurringTimerFlow = new FlowBuilder() {
@Override
public void define() {
flowId(id("recurringTimerFlow"));
Task callee = new Task<Void>() {
@Override
public void execute(Void o) {
}
};
start(event(id("start")), every(5, TimeUnit.SECONDS))
.execute(task(id("task"), callee));
}
};
assertThat(recurringTimerFlow.getDefinition())
.hasNodesWithMarker(1, StartEvent.class);
StartEvent startEvent = recurringTimerFlow.getDefinition().getNode(IdUtil.id("start"), EventDefinition.class).as(StartEvent.class);
Assertions.assertThat(startEvent.getStartTimerDefinition().get())
.isEqualTo(new StartTimerDefinition(5, TimeUnit.SECONDS));
}
}
| apache-2.0 |
roshanp/lucure-core | src/main/java/com/lucure/core/codec/LucureStoredFieldsFormat.java | 6873 | package com.lucure.core.codec;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.StoredFieldsFormat;
import org.apache.lucene.codecs.compressing.CompressionMode;
import org.apache.lucene.codecs.lucene40.Lucene40StoredFieldsFormat;
import org.apache.lucene.index.StoredFieldVisitor;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.util.packed.PackedInts;
/**
* Lucene 4.1 stored fields format.
*
* <p><b>Principle</b></p>
* <p>This {@link StoredFieldsFormat} compresses blocks of 16KB of documents in
* order to improve the compression ratio compared to document-level
* compression. It uses the <a href="http://code.google.com/p/lz4/">LZ4</a>
* compression algorithm, which is fast to compress and very fast to decompress
* data. Although the compression method that is used focuses more on speed
* than on compression ratio, it should provide interesting compression ratios
* for redundant inputs (such as log files, HTML or plain text).</p>
* <p><b>File formats</b></p>
* <p>Stored fields are represented by two files:</p>
* <ol>
* <li><a name="field_data" id="field_data"></a>
* <p>A fields data file (extension <tt>.fdt</tt>). This file stores a compact
* representation of documents in compressed blocks of 16KB or more. When
* writing a segment, documents are appended to an in-memory <tt>byte[]</tt>
* buffer. When its size reaches 16KB or more, some metadata about the documents
* is flushed to disk, immediately followed by a compressed representation of
* the buffer using the
* <a href="http://code.google.com/p/lz4/">LZ4</a>
* <a href="http://fastcompression.blogspot.fr/2011/05/lz4-explained.html">compression format</a>.</p>
* <p>Here is a more detailed description of the field data file format:</p>
* <ul>
* <li>FieldData (.fdt) --> <Header>, PackedIntsVersion, <Chunk><sup>ChunkCount</sup></li>
* <li>Header --> {@link CodecUtil#writeHeader CodecHeader}</li>
* <li>PackedIntsVersion --> {@link PackedInts#VERSION_CURRENT} as a {@link DataOutput#writeVInt VInt}</li>
* <li>ChunkCount is not known in advance and is the number of chunks necessary to store all document of the segment</li>
* <li>Chunk --> DocBase, ChunkDocs, DocFieldCounts, DocLengths, <CompressedDocs></li>
* <li>DocBase --> the ID of the first document of the chunk as a {@link DataOutput#writeVInt VInt}</li>
* <li>ChunkDocs --> the number of documents in the chunk as a {@link DataOutput#writeVInt VInt}</li>
* <li>DocFieldCounts --> the number of stored fields of every document in the chunk, encoded as followed:<ul>
* <li>if chunkDocs=1, the unique value is encoded as a {@link DataOutput#writeVInt VInt}</li>
* <li>else read a {@link DataOutput#writeVInt VInt} (let's call it <tt>bitsRequired</tt>)<ul>
* <li>if <tt>bitsRequired</tt> is <tt>0</tt> then all values are equal, and the common value is the following {@link DataOutput#writeVInt VInt}</li>
* <li>else <tt>bitsRequired</tt> is the number of bits required to store any value, and values are stored in a {@link PackedInts packed} array where every value is stored on exactly <tt>bitsRequired</tt> bits</li>
* </ul></li>
* </ul></li>
* <li>DocLengths --> the lengths of all documents in the chunk, encoded with the same method as DocFieldCounts</li>
* <li>CompressedDocs --> a compressed representation of <Docs> using the LZ4 compression format</li>
* <li>Docs --> <Doc><sup>ChunkDocs</sup></li>
* <li>Doc --> <FieldNumAndType, Value><sup>DocFieldCount</sup></li>
* <li>FieldNumAndType --> a {@link DataOutput#writeVLong VLong}, whose 3 last bits are Type and other bits are FieldNum</li>
* <li>Type --><ul>
* <li>0: Value is String</li>
* <li>1: Value is BinaryValue</li>
* <li>2: Value is Int</li>
* <li>3: Value is Float</li>
* <li>4: Value is Long</li>
* <li>5: Value is Double</li>
* <li>6, 7: unused</li>
* </ul></li>
* <li>FieldNum --> an ID of the field</li>
* <li>Value --> {@link DataOutput#writeString(String) String} | BinaryValue | Int | Float | Long | Double depending on Type</li>
* <li>BinaryValue --> ValueLength <Byte><sup>ValueLength</sup></li>
* </ul>
* <p>Notes</p>
* <ul>
* <li>If documents are larger than 16KB then chunks will likely contain only
* one document. However, documents can never spread across several chunks (all
* fields of a single document are in the same chunk).</li>
* <li>When at least one document in a chunk is large enough so that the chunk
* is larger than 32KB, the chunk will actually be compressed in several LZ4
* blocks of 16KB. This allows {@link StoredFieldVisitor}s which are only
* interested in the first fields of a document to not have to decompress 10MB
* of data if the document is 10MB, but only 16KB.</li>
* <li>Given that the original lengths are written in the metadata of the chunk,
* the decompressor can leverage this information to stop decoding as soon as
* enough data has been decompressed.</li>
* <li>In case documents are incompressible, CompressedDocs will be less than
* 0.5% larger than Docs.</li>
* </ul>
* </li>
* <li><a name="field_index" id="field_index"></a>
* <p>A fields index file (extension <tt>.fdx</tt>).</p>
* <ul>
* <li>FieldsIndex (.fdx) --> <Header>, <ChunkIndex></li>
* <li>Header --> {@link CodecUtil#writeHeader CodecHeader}</li>
* <li>ChunkIndex: See {@link CompressingStoredFieldsIndexWriter}</li>
* </ul>
* </li>
* </ol>
* <p><b>Known limitations</b></p>
* <p>This {@link StoredFieldsFormat} does not support individual documents
* larger than (<tt>2<sup>31</sup> - 2<sup>14</sup></tt>) bytes. In case this
* is a problem, you should use another format, such as
* {@link Lucene40StoredFieldsFormat}.</p>
* @lucene.experimental
*/
public final class LucureStoredFieldsFormat extends CompressingStoredFieldsFormat {
/** Sole constructor. */
public LucureStoredFieldsFormat() {
super("LucureStoredFields", CompressionMode.FAST, 1 << 14);
}
}
| apache-2.0 |
wangqi/gameserver | admin/src/main/java/com/xinqihd/sns/gameserver/admin/data/WeaponDataSaveAction.java | 1567 | package com.xinqihd.sns.gameserver.admin.data;
import java.awt.event.ActionEvent;
import java.util.Collection;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JDialog;
import com.xinqihd.sns.gameserver.admin.util.ImageUtil;
import com.xinqihd.sns.gameserver.config.equip.WeaponPojo;
import com.xinqihd.sns.gameserver.service.CopyMongoCollectionService;
/**
* 将生成的Weapon数据保存到new_equipments表中
* @author wangqi
*
*/
public class WeaponDataSaveAction extends AbstractAction {
private String targetDatabase;
private String targetNamespace;
private String targetCollection;
private Collection<WeaponPojo> weapons;
public WeaponDataSaveAction(
WeaponTableModel tableModel,
String targetDatabase, String targetNamespace, String targetCollection) {
super("", ImageUtil.createImageSmallIcon("Folder.png", "Save"));
this.weapons = tableModel.getWeaponList();
this.targetDatabase = targetDatabase;
this.targetNamespace = targetNamespace;
this.targetCollection = targetCollection;
}
public void setIcon(Icon icon) {
super.putValue(Action.SMALL_ICON, icon);
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
WeaponDataSaveService service = new WeaponDataSaveService(
this.weapons,
targetDatabase, targetNamespace, targetCollection
);
JDialog dialog = service.getDialog();
service.execute();
dialog.setVisible(true);
}
}
| apache-2.0 |
jqno/equalsverifier | equalsverifier-test-core/src/test/java/nl/jqno/equalsverifier/integration/basic_contract/ReflexivityTest.java | 7004 | package nl.jqno.equalsverifier.integration.basic_contract;
import static nl.jqno.equalsverifier.testhelpers.Util.defaultHashCode;
import java.util.Objects;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import nl.jqno.equalsverifier.testhelpers.ExpectedException;
import nl.jqno.equalsverifier.testhelpers.types.FinalPoint;
import nl.jqno.equalsverifier.testhelpers.types.Point;
import org.junit.jupiter.api.Test;
public class ReflexivityTest {
@Test
public void fail_whenReferencesAreNotEqual() {
ExpectedException
.when(() -> EqualsVerifier.forClass(ReflexivityIntentionallyBroken.class).verify())
.assertFailure()
.assertMessageContains(
"Reflexivity",
"object does not equal itself",
ReflexivityIntentionallyBroken.class.getSimpleName()
);
}
@Test
public void fail_whenTheWrongFieldsAreComparedInEquals() {
ExpectedException
.when(() -> EqualsVerifier.forClass(FieldsMixedUpInEquals.class).verify())
.assertFailure()
.assertMessageContains(
"Reflexivity",
"object does not equal an identical copy of itself",
FieldsMixedUpInEquals.class.getSimpleName()
);
}
@Test
public void fail_whenReferencesAreNotEqual_givenFieldsThatAreNull() {
ExpectedException
.when(() -> EqualsVerifier.forClass(ReflexivityBrokenOnNullFields.class).verify())
.assertFailure()
.assertMessageContains(
"Reflexivity",
ReflexivityBrokenOnNullFields.class.getSimpleName()
);
}
@Test
public void succeed_whenReferencesAreNotEqual_givenFieldsThatAreNullAndWarningIsSuppressed() {
EqualsVerifier
.forClass(ReflexivityBrokenOnNullFields.class)
.suppress(Warning.NULL_FIELDS)
.verify();
}
@Test
public void fail_whenObjectIsInstanceofCheckedWithWrongClass() {
ExpectedException
.when(() -> EqualsVerifier.forClass(WrongInstanceofCheck.class).verify())
.assertFailure()
.assertMessageContains(
"Reflexivity",
"object does not equal an identical copy of itself",
WrongInstanceofCheck.class.getSimpleName()
);
}
@Test
public void fail_whenEqualsReturnsFalse_givenObjectsThatAreIdentical() {
ExpectedException
.when(() -> EqualsVerifier.forClass(SuperCallerWithUnusedField.class).verify())
.assertFailure()
.assertMessageContains("Reflexivity", "identical copy");
}
@Test
public void succeed_whenEqualsReturnsFalse_givenObjectsThatAreIdenticalAndWarningIsSuppressed() {
EqualsVerifier
.forClass(SuperCallerWithUnusedField.class)
.suppress(Warning.IDENTICAL_COPY, Warning.ALL_FIELDS_SHOULD_BE_USED)
.verify();
}
@Test
public void fail_whenIdenticalCopyWarningIsSuppressedUnnecessarily() {
ExpectedException
.when(() ->
EqualsVerifier.forClass(FinalPoint.class).suppress(Warning.IDENTICAL_COPY).verify()
)
.assertFailure()
.assertMessageContains("Unnecessary suppression", "IDENTICAL_COPY");
}
static final class ReflexivityIntentionallyBroken extends Point {
// Instantiator.scramble will flip this boolean.
private boolean broken = false;
public ReflexivityIntentionallyBroken(int x, int y) {
super(x, y);
}
@Override
public boolean equals(Object obj) {
if (broken && this == obj) {
return false;
}
return super.equals(obj);
}
}
static final class FieldsMixedUpInEquals {
private final String one;
private final String two;
@SuppressWarnings("unused")
private final String unused;
public FieldsMixedUpInEquals(String one, String two, String unused) {
this.one = one;
this.two = two;
this.unused = unused;
}
@Override
public boolean equals(Object obj) {
// EV must also find the error when equals short-circuits.
if (obj == this) {
return true;
}
if (!(obj instanceof FieldsMixedUpInEquals)) {
return false;
}
FieldsMixedUpInEquals other = (FieldsMixedUpInEquals) obj;
return Objects.equals(two, other.one) && Objects.equals(two, other.two);
}
@Override
public int hashCode() {
return defaultHashCode(this);
}
}
static final class ReflexivityBrokenOnNullFields {
private final Object a;
public ReflexivityBrokenOnNullFields(Object a) {
this.a = a;
}
// This equals method was generated by Eclipse, except for the indicated line.
// CHECKSTYLE OFF: NeedBraces
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ReflexivityBrokenOnNullFields other = (ReflexivityBrokenOnNullFields) obj;
if (a == null) {
if (other.a != null) return false;
// The following line was added to cause equals to be broken on reflexivity.
return false;
} else if (!a.equals(other.a)) return false;
return true;
}
// CHECKSTYLE ON: NeedBraces
@Override
public int hashCode() {
return defaultHashCode(this);
}
}
static final class WrongInstanceofCheck {
private final int foo;
public WrongInstanceofCheck(int foo) {
this.foo = foo;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof SomethingCompletelyDifferent)) {
return false;
}
WrongInstanceofCheck other = (WrongInstanceofCheck) obj;
return foo == other.foo;
}
@Override
public int hashCode() {
return defaultHashCode(this);
}
}
static class SomethingCompletelyDifferent {}
static final class SuperCallerWithUnusedField {
@SuppressWarnings("unused")
private final int unused;
public SuperCallerWithUnusedField(int unused) {
this.unused = unused;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
}
| apache-2.0 |
gomaster-me/events_microservices | config-server/src/main/java/com/micro/configserver/ConfigServerApplication.java | 413 | package com.micro.configserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
| apache-2.0 |
wiesed/machine-learning | src/main/java/com/bm/classify/sampling/filter/impl/UnbiasedSpyFilter.java | 1745 | package com.bm.classify.sampling.filter.impl;
import com.bm.classify.sampling.Sampleable;
import com.bm.classify.sampling.filter.IFilter;
/**
* Diese Klasse dient zum "ausspionieren" des Flat files um zu bestimmen wo
* die validen beispiele sind (index).
* @param <T> - der typ
*/
public final class UnbiasedSpyFilter<T> implements IFilter<T> {
private final int[] examplesIndex;
private int index = -1;
private int end = -1;
/**
* Constructor.
* @param totalSize - die geammtgroesse der datenmenge.
*/
public UnbiasedSpyFilter(int totalSize) {
this.examplesIndex = new int[totalSize];
}
/**
* Prufet ob ein flat file objekt valide ist.
*
* @param object -
* des objekt was auf die validitaet geprueft werden soll.
* @return - true wenn valid
* @param index -
* der aktuell gelesene index, 0 basierend
* @author Daniel Wiese
* @since 18.08.2006
* @see com.bm.classify.sampling.Filter#isValid(java.lang.Object)
*/
public boolean isValid(T object, int index) {
this.index++;
if (object instanceof Sampleable) {
final Sampleable akt = (Sampleable) object;
if (akt.isSelectable()) {
end++;
examplesIndex[end] = index;
}
}
return false;
}
/**
* Liefert den end index im neg Ergebniss array.
* @return Returns the endFalse.
*/
public int getEnd() {
return end;
}
/**
* Liefert ein array mit allen negativen beipielen.
* @return Returns the falseExamplesIndex.
*/
public int[] getExamplesIndex() {
return examplesIndex;
}
} | apache-2.0 |
lgoldstein/communitychest | development/src/main/java/net/community/chest/net/proto/text/ssh/SSHDisconnectReason.java | 2028 | /*
*
*/
package net.community.chest.net.proto.text.ssh;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import net.community.chest.util.collection.CollectionsUtils;
/**
* <P>Copyright as per GPLv2</P>
*
* <P>SSH_MSG_DISCONNECT reason codes as per RFC 4250</P>
*
* @author Lyor G.
* @since Jul 2, 2009 7:44:17 AM
*/
public enum SSHDisconnectReason implements CodeValueEncapsulator {
SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT(1),
SSH_DISCONNECT_PROTOCOL_ERROR(2),
SSH_DISCONNECT_KEY_EXCHANGE_FAILED(3),
SSH_DISCONNECT_RESERVED(4),
SSH_DISCONNECT_MAC_ERROR(5),
SSH_DISCONNECT_COMPRESSION_ERROR(6),
SSH_DISCONNECT_SERVICE_NOT_AVAILABLE(7),
SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED(8),
SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE(9),
SSH_DISCONNECT_CONNECTION_LOST(10),
SSH_DISCONNECT_BY_APPLICATION(11),
SSH_DISCONNECT_TOO_MANY_CONNECTIONS(12),
SSH_DISCONNECT_AUTH_CANCELLED_BY_USER(13),
SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE(14),
SSH_DISCONNECT_ILLEGAL_USER_NAME(15);
private final int _code;
/*
* @see net.community.chest.net.proto.text.ssh.CodeValueEncapsulator#getCodeValue()
*/
@Override
public final int getCodeValue ()
{
return _code;
}
private final String _mn;
/*
* @see net.community.chest.net.proto.text.ssh.CodeValueEncapsulator#getMnemonic()
*/
@Override
public final String getMnemonic ()
{
return _mn;
}
SSHDisconnectReason (int code)
{
_code = code;
_mn = SSHProtocol.getMnemonicValue(name(), "SSH_DISCONNECT_");
}
public static final List<SSHDisconnectReason> VALUES=Collections.unmodifiableList(Arrays.asList(values()));
public static final SSHDisconnectReason fromString (final String s)
{
return CollectionsUtils.fromString(VALUES, s, false);
}
public static final SSHDisconnectReason fromReasonCode (final int c)
{
return SSHProtocol.fromReasonCode(c, VALUES);
}
public static final SSHDisconnectReason fromMnemonic (final String s)
{
return SSHProtocol.fromMnemonic(s, false, VALUES);
}
}
| apache-2.0 |
pieterverstraete/BeTrains-for-Android | BeTrains/src/main/java/tof/cv/mpp/CompensationFragment.java | 9888 | package tof.cv.mpp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.text.format.DateUtils;
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.webkit.WebView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import tof.cv.mpp.adapter.CompensationAdapter;
public class CompensationFragment extends ListFragment {
protected static final String TAG = "CompensationFragment";
CompensationAdapter a;
private TextView mTitleText;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_compensation, null);
}
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add(Menu.NONE, 0, Menu.NONE, "Web")
.setIcon(R.drawable.ic_menu_goto)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (0):
String url = getString(R.string.compensation_url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(getListView());
// getActivity().getActionBar().setIcon(R.drawable.ab_sncb);
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
boolean isTablet = this.getActivity().getResources().getBoolean(R.bool.tablet_layout);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(
!isTablet);
mTitleText = (TextView) getView().findViewById(R.id.title);
}
public void onResume() {
super.onResume();
updateList();
}
public void updateList() {
String[] f = getActivity().getDir("COMPENSATION", Context.MODE_PRIVATE).list();
Arrays.sort(f);
ArrayList<String> arraylist = new ArrayList<String>(Arrays.asList(f));
a = new CompensationAdapter(getActivity(),
android.R.layout.simple_list_item_1, arraylist);
setListAdapter(a);
if (f.length == 0) {
WebView mywebview = (WebView) getView().findViewById(android.R.id.empty);
String data = this.getActivity().getString(R.string.compensation_html);
mywebview.loadDataWithBaseURL("file:///android_asset/", data, "text/html", "UTF-8", null);
mTitleText.setVisibility(View.GONE);
} else {
mTitleText.setVisibility(View.VISIBLE);
try {
long elapsed = System.currentTimeMillis() - Long.valueOf(f[0].split(";")[0]);
mTitleText.setText(getResources().getQuantityString(R.plurals.compensation_days, (int) (elapsed / DateUtils.DAY_IN_MILLIS), (int) (elapsed / DateUtils.DAY_IN_MILLIS)));
//mTitleText.setText("Retards depuis le: "+Utils.formatDate(new Date(Long.valueOf(f[0].split(";")[0])-4*DateUtils.DAY_IN_MILLIS),"d MMMMM"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onListItemClick(ListView l, View v, final int position, long id) {
super.onListItemClick(l, v, position, id);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
String[] items = {getString(R.string.compensation_show_info), getString(R.string.compensation_edit_delay), getString(R.string.compensation_edit_text), getString(R.string.remove)};
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
switch (which) {
case 0:
String[] all=getListAdapter().getItem(position).toString().split(";");
Intent i = new Intent(getActivity(), InfoTrainActivity.class);
String id = getListAdapter().getItem(position).toString().split(";")[3];
i.putExtra("FileName", getListAdapter().getItem(position).toString());
i.putExtra("Name",all[all.length-1] );
startActivity(i);
break;
case 1:
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
input.setText(getListAdapter().getItem(position).toString().split(";")[1]);
alert.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
File directory = getActivity().getDir("COMPENSATION", Context.MODE_PRIVATE);
File from = new File(directory, getListAdapter().getItem(position).toString());
String newDate = getListAdapter().getItem(position).toString().split(";")[0];
String newDelay = input.getText().toString().replaceAll(";", ",");
String newText = getListAdapter().getItem(position).toString().split(";")[2];
String newId = getListAdapter().getItem(position).toString().split(";")[3];
File to = new File(directory, newDate + ";" + newDelay + ";" + newText + ";" + newId);
from.renameTo(to);
updateList();
}
});
alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
break;
case 2:
AlertDialog.Builder alert2 = new AlertDialog.Builder(getActivity());
final EditText input2 = new EditText(getActivity());
alert2.setView(input2);
input2.setText(getListAdapter().getItem(position).toString().split(";")[2]);
alert2.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
File directory = getActivity().getDir("COMPENSATION", Context.MODE_PRIVATE);
File from = new File(directory, getListAdapter().getItem(position).toString());
String newDate = getListAdapter().getItem(position).toString().split(";")[0];
String newDelay = getListAdapter().getItem(position).toString().split(";")[1];
String newText = input2.getText().toString().replaceAll(";", ",");
String newId = getListAdapter().getItem(position).toString().split(";")[3];
File to = new File(directory, newDate + ";" + newDelay + ";" + newText + ";" + newId);
from.renameTo(to);
updateList();
}
});
alert2.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert2.show();
break;
case 3:
File directory = getActivity().getDir("COMPENSATION", Context.MODE_PRIVATE);
new File(directory, getListAdapter().getItem(position).toString())
.delete();
updateList();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
builder.create().show();
}
}
| apache-2.0 |
lhong375/aura | aura-impl/src/main/java/org/auraframework/impl/java/BaseJavaDefFactory.java | 3950 | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.impl.java;
import java.util.List;
import org.auraframework.builder.DefBuilder;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.Definition;
import org.auraframework.impl.system.DefFactoryImpl;
import org.auraframework.system.CacheableDefFactory;
import org.auraframework.system.DefFactory;
import org.auraframework.system.Source;
import org.auraframework.system.SourceLoader;
import org.auraframework.throwable.quickfix.QuickFixException;
import com.google.common.collect.Lists;
/**
* Base class for {@link DefFactory} implementations for the java://
* pseudo-protocol.
*/
public abstract class BaseJavaDefFactory<D extends Definition> extends DefFactoryImpl<D> implements CacheableDefFactory<D> {
final List<SourceLoader> loaders;
public BaseJavaDefFactory(List<SourceLoader> sourceLoaders) {
loaders = (sourceLoaders == null || sourceLoaders.isEmpty()) ? null : Lists.newArrayList(sourceLoaders);
}
@Override
public Source<D> getSource(DefDescriptor<D> descriptor) {
if (loaders == null) {
return null;
}
for (SourceLoader loader : loaders) {
Source<D> source = loader.getSource(descriptor);
if (source != null && source.exists()) {
return source;
}
}
return null;
}
protected Class<?> getClazz(DefDescriptor<D> descriptor) throws QuickFixException {
Class<?> clazz;
try {
if (descriptor.getNamespace() == null) {
clazz = Class.forName(descriptor.getName());
} else {
clazz = Class.forName(String.format("%s.%s", descriptor.getNamespace(), descriptor.getName()));
}
} catch (ClassNotFoundException e) {
return null;
}
return clazz;
}
/**
* Get a builder for the def.
*
* This function must be implemented by all subclasses. It should return a
* builder from which only the 'build()' function will be executed. It is
* allowed to return a null, in which case the {@link #getDef(DefDescriptor)} function will return a null.
*
* Note that this can throw a QuickFixException as there are certain things
* that will cause a builder to fail early. It would be possible to force
* them to be lazy, but that doesn't really help anything. An example is a
* class that does not have the correct annotation on it.
*
* @param descriptor the incoming descriptor for which we need a builder.
* @return a builder for the Def or null if none could be found.
* @throws QuickFixException if the builder could not be created because of
* a defect.
*/
protected abstract DefBuilder<?, ? extends D> getBuilder(DefDescriptor<D> descriptor) throws QuickFixException;
@Override
public D getDef(DefDescriptor<D> descriptor) throws QuickFixException {
DefBuilder<?, ? extends D> builder;
D def;
builder = getBuilder(descriptor);
if (builder == null) {
return null;
}
// FIXME = "need md5 in builder";
def = builder.build();
return def;
}
@Override
public long getLastMod(DefDescriptor<D> descriptor) {
return 0;
}
}
| apache-2.0 |
jdahlstrom/vaadin.react | uitest/src/test/java/com/vaadin/tests/components/grid/SortableHeaderStylesTest.java | 1691 | /*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.tests.components.grid;
import org.junit.Assert;
import org.junit.Test;
import com.vaadin.testbench.elements.GridElement;
import com.vaadin.testbench.elements.OptionGroupElement;
import com.vaadin.tests.tb3.SingleBrowserTest;
public class SortableHeaderStylesTest extends SingleBrowserTest {
@Test
public void testSortableHeaderStyles() {
openTestURL();
Assert.assertFalse(hasSortableStyle(0));
for (int i = 1; i < 8; i++) {
Assert.assertTrue(hasSortableStyle(i));
}
OptionGroupElement sortableSelector = $(OptionGroupElement.class)
.first();
// Toggle sortability
sortableSelector.selectByText("lastName");
Assert.assertFalse(hasSortableStyle(3));
// Toggle back
sortableSelector.selectByText("lastName");
Assert.assertTrue(hasSortableStyle(3));
}
private boolean hasSortableStyle(int column) {
return $(GridElement.class).first().getHeaderCell(0, column)
.getAttribute("class").contains("sortable");
}
}
| apache-2.0 |
6kV/Wazza | wazza-poc/src/main/java/reindex/Reindex.java | 3711 | package reindex;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.search.SearchHit;
import runner.GeneratePharmacie;
/**
* User: nkefi
*/
public class Reindex {
public static final int BULK_SIZE = 500;
public static final String NEW_INDEX_NAME = "my_new_index";
public static final String TYPE_NAME = "pharmacie";
public static void main(String[] args) throws Exception {
new Reindex().reindex();
}
public void reindex() throws Exception {
Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", GeneratePharmacie.CLUSTER_NAME).build();
Client client = new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
SearchResponse scrollResp = client.prepareSearch("my_index_2")
.setSearchType(SearchType.SCAN)
.setScroll(new TimeValue(60000))
.setSize(100).execute().actionGet(); //100 hits per shard will be returned for each scroll
// Generate new Index using settings
String newIndexSettings = GeneratePharmacie.readFileInClasspath("/reindexSettings.json");
client.admin().indices().prepareCreate(NEW_INDEX_NAME).setSettings(newIndexSettings).execute().actionGet();
// Generate Mapping
String newMapping = GeneratePharmacie.readFileInClasspath("/reindexMapping.json");
client.admin().indices().preparePutMapping(new String[]{NEW_INDEX_NAME}).setType(TYPE_NAME).setSource(newMapping).execute().actionGet();
BulkProcessor bulkProcessor = BulkProcessor.builder(client, new BulkProcessor.Listener() {
@Override
public void beforeBulk(long executionId, BulkRequest request) {
System.out.print("Going to execute new bulk composed of " + request.numberOfActions() + " actions");
}
@Override
public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
System.out.println(" -> done");
}
@Override
public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
System.err.println("Error executing bulk: " + failure.getMessage());
}
}).setBulkActions(BULK_SIZE).
setConcurrentRequests(10).
build();
System.out.println(" Scroll ID "+scrollResp.getScrollId());
while (true) {
scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet();
for (SearchHit hit : scrollResp.getHits()) {
bulkProcessor.add(new IndexRequest(NEW_INDEX_NAME, TYPE_NAME).source(hit.source()));
}
if (scrollResp.getHits().getHits().length == 0) {
break;
}
}
bulkProcessor.close();
client.admin().indices().prepareAliases().removeAlias("my_index", "index").addAlias("my_new_index", "index").execute();
client.close();
}
}
| apache-2.0 |
jackycaojiaqi/FuBang_Live | app/src/main/java/com/fubang/live/util/GiftUtil.java | 3468 | package com.fubang.live.util;
import com.fubang.live.R;
import com.fubang.live.entities.GiftEntity;
import java.util.ArrayList;
import java.util.List;
/**
* ┏┓ ┏┓
* ┏┛┻━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
* ━━━━━━神兽出没━━━━━━
* <p/>
* 项目名称:fubangzhibo
* 类描述:
* 创建人:dell
* 创建时间:2016-05-25 14:22
* 修改人:dell
* 修改时间:2016-05-25 14:22
* 修改备注:添加礼物的工具类
*/
public class GiftUtil {
public static List<GiftEntity> getGifts() {
List<GiftEntity> list = new ArrayList<>();
list.clear();
list.add(new GiftEntity(21, R.drawable.ic_gift_21, "爱心(100)", 100));
list.add(new GiftEntity(22, R.drawable.ic_gift_22, "荧光棒(100)", 100));
list.add(new GiftEntity(23, R.drawable.ic_gift_23, "啤酒(100)", 100));
list.add(new GiftEntity(24, R.drawable.ic_gift_24, "鲜花(100)", 100));
list.add(new GiftEntity(25, R.drawable.ic_gift_25, "黄瓜(100)", 100));
list.add(new GiftEntity(26, R.drawable.ic_gift_26, "花(100)", 100));
list.add(new GiftEntity(27, R.drawable.ic_gift_27, "皮鞭(100)", 100));
list.add(new GiftEntity(28, R.drawable.ic_gift_28, "香蕉(100)", 100));
list.add(new GiftEntity(29, R.drawable.ic_gift_29, "亲吻(100)", 100));
list.add(new GiftEntity(30, R.drawable.ic_gift_30, "抱抱(100)", 100));
list.add(new GiftEntity(31, R.drawable.ic_gift_31, "冰棍(100)", 100));
list.add(new GiftEntity(32, R.drawable.ic_gift_32, "红包(100)", 100));
list.add(new GiftEntity(33, R.drawable.ic_gift_33, "烟花(100)", 100));
list.add(new GiftEntity(34, R.drawable.ic_gift_34, "钻戒(100)", 100));
list.add(new GiftEntity(35, R.drawable.ic_gift_35, "天使(100)", 100));
list.add(new GiftEntity(36, R.drawable.ic_gift_36, "豪华游轮(100)", 100));
list.add(new GiftEntity(37, R.drawable.ic_gift_37, "超级跑车(100)", 100));
list.add(new GiftEntity(38, R.drawable.ic_gift_38, "热气球(100)", 100));
list.add(new GiftEntity(39, R.drawable.ic_gift_39, "飞机(100)", 100));
list.add(new GiftEntity(40, R.drawable.ic_gift_40, "城堡(100)", 100));
return list;
}
}
| apache-2.0 |
ctripcorp/dal | dao-gen-core/src/main/java/com/ctrip/platform/dal/daogen/dao/DaoByFreeSql.java | 11567 | package com.ctrip.platform.dal.daogen.dao;
import com.ctrip.platform.dal.dao.DalHints;
import com.ctrip.platform.dal.dao.DalRowMapper;
import com.ctrip.platform.dal.dao.DalTableDao;
import com.ctrip.platform.dal.dao.StatementParameters;
import com.ctrip.platform.dal.dao.helper.DalDefaultJpaMapper;
import com.ctrip.platform.dal.dao.helper.DalDefaultJpaParser;
import com.ctrip.platform.dal.dao.sqlbuilder.FreeSelectSqlBuilder;
import com.ctrip.platform.dal.dao.sqlbuilder.FreeUpdateSqlBuilder;
import com.ctrip.platform.dal.dao.sqlbuilder.SelectSqlBuilder;
import com.ctrip.platform.dal.daogen.entity.GenTaskByFreeSql;
import com.ctrip.platform.dal.daogen.enums.DbModeTypeEnum;
import com.ctrip.platform.dal.daogen.utils.DatabaseSetUtils;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DaoByFreeSql extends BaseDao {
private DalTableDao<GenTaskByFreeSql> client;
private DalRowMapper<GenTaskByFreeSql> genTaskByFreeSqlRowMapper = null;
public DaoByFreeSql() throws SQLException {
client = new DalTableDao<>(new DalDefaultJpaParser<>(GenTaskByFreeSql.class));
genTaskByFreeSqlRowMapper = new DalDefaultJpaMapper<>(GenTaskByFreeSql.class);
}
public List<GenTaskByFreeSql> getAllTasks() throws SQLException {
DalHints hints = DalHints.createIfAbsent(null);
SelectSqlBuilder builder = new SelectSqlBuilder().selectAll();
List<GenTaskByFreeSql> list = client.query(builder, hints);
processList(list);
return list;
}
private void processList(List<GenTaskByFreeSql> list) throws SQLException {
if (list == null || list.size() == 0)
return;
for (GenTaskByFreeSql entity : list) {
processGenTaskByFreeSql(entity);
}
}
private void processGenTaskByFreeSql(GenTaskByFreeSql entity) throws SQLException {
if (entity.getApproved() != null) {
if (entity.getApproved() == 1) {
entity.setStr_approved("未审批");
} else if (entity.getApproved() == 2) {
entity.setStr_approved("通过");
} else if (entity.getApproved() == 3) {
entity.setStr_approved("未通过");
} else {
entity.setStr_approved("通过");
}
}
if (entity.getUpdate_time() != null) {
Date date = new Date(entity.getUpdate_time().getTime());
entity.setStr_update_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
}
if (DbModeTypeEnum.Cluster.getDes().equals(entity.getMode_type())) {
entity.setAllInOneName(entity.getDatabaseSetName());
} else {
entity.setAllInOneName(DatabaseSetUtils.getAllInOneName(entity.getDatabaseSetName()));
}
}
public int getVersionById(int id) throws SQLException {
DalHints hints = DalHints.createIfAbsent(null);
GenTaskByFreeSql entity = client.queryByPk(id, hints);
if (entity == null)
return 0;
return entity.getVersion();
}
public List<GenTaskByFreeSql> getTasksByProjectId(int projectId) throws SQLException {
FreeSelectSqlBuilder<List<GenTaskByFreeSql>> builder = new FreeSelectSqlBuilder<>(dbCategory);
StringBuilder sb = new StringBuilder();
sb.append(
"SELECT id, project_id, mode_type, db_name, class_name,pojo_name,method_name,crud_type,sql_content,parameters,`generated`,version,update_user_no,update_time,comment,scalarType,pojoType,pagination,sql_style,approved,approveMsg,hints ");
sb.append("FROM task_sql WHERE project_id=? order by id");
builder.setTemplate(sb.toString());
StatementParameters parameters = new StatementParameters();
int i = 1;
parameters.set(i++, "project_id", Types.INTEGER, projectId);
builder.mapWith(genTaskByFreeSqlRowMapper);
DalHints hints = DalHints.createIfAbsent(null).allowPartial();
List<GenTaskByFreeSql> list = queryDao.query(builder, parameters, hints);
processList(list);
return list;
}
public GenTaskByFreeSql getTasksByTaskId(int id) throws SQLException {
DalHints hints = DalHints.createIfAbsent(null);
return client.queryByPk(id, hints);
}
public List<GenTaskByFreeSql> updateAndGetAllTasks(int projectId) throws SQLException {
List<GenTaskByFreeSql> result = new ArrayList<>();
List<GenTaskByFreeSql> list = getTasksByProjectId(projectId);
if (list == null || list.size() == 0)
return result;
for (GenTaskByFreeSql entity : list) {
entity.setGenerated(true);
if (updateTask(entity) > 0) {
result.add(entity);
}
}
return result;
}
public List<GenTaskByFreeSql> updateAndGetTasks(int projectId) throws SQLException {
FreeSelectSqlBuilder<List<GenTaskByFreeSql>> builder = new FreeSelectSqlBuilder<>(dbCategory);
StringBuilder sb = new StringBuilder();
sb.append(
"SELECT id, project_id, db_name, class_name,pojo_name,method_name,crud_type,sql_content,parameters,`generated`,version,update_user_no,update_time,comment,scalarType,pojoType,pagination,sql_style,approved,approveMsg,hints ");
sb.append("FROM task_sql WHERE project_id=? AND `generated`=FALSE");
builder.setTemplate(sb.toString());
StatementParameters parameters = new StatementParameters();
int i = 1;
parameters.set(i++, "project_id", Types.INTEGER, projectId);
builder.mapWith(genTaskByFreeSqlRowMapper);
DalHints hints = DalHints.createIfAbsent(null).allowPartial();
List<GenTaskByFreeSql> list = queryDao.query(builder, parameters, hints);
List<GenTaskByFreeSql> result = new ArrayList<>();
if (list == null || list.size() == 0)
return result;
processList(list);
for (GenTaskByFreeSql entity : list) {
entity.setGenerated(true);
if (updateTask(entity) > 0) {
result.add(entity);
}
}
return result;
}
public int insertTask(GenTaskByFreeSql task) throws SQLException {
if (null == task)
return 0;
DalHints hints = DalHints.createIfAbsent(null);
return client.insert(hints, task);
}
public int updateTask(GenTaskByFreeSql task) throws SQLException {
{
FreeSelectSqlBuilder<GenTaskByFreeSql> builder = new FreeSelectSqlBuilder<>(dbCategory);
builder.setTemplate(
"SELECT * FROM task_sql WHERE id != ? AND project_id=? AND db_name=? AND class_name=? AND method_name=? LIMIT 1");
StatementParameters parameters = new StatementParameters();
int i = 1;
parameters.set(i++, "id", Types.INTEGER, task.getId());
parameters.set(i++, "project_id", Types.INTEGER, task.getProject_id());
parameters.set(i++, "db_name", Types.VARCHAR, task.getDatabaseSetName());
parameters.set(i++, "class_name", Types.VARCHAR, task.getClass_name());
parameters.set(i++, "method_name", Types.VARCHAR, task.getMethod_name());
builder.mapWith(genTaskByFreeSqlRowMapper).requireFirst().nullable();
DalHints hints = DalHints.createIfAbsent(null).allowPartial();
GenTaskByFreeSql entity = queryDao.query(builder, parameters, hints);
if (entity != null)
return 0;
}
FreeUpdateSqlBuilder builder = new FreeUpdateSqlBuilder(dbCategory);
StringBuilder sb = new StringBuilder();
sb.append("UPDATE task_sql SET project_id=?, db_name=?,class_name=?,pojo_name=?,");
sb.append("method_name=?,crud_type=?,sql_content=?,parameters=?,`generated`=?,");
sb.append("version=version+1,update_user_no=?,update_time=?,comment=?,");
sb.append("scalarType=?,pojoType=?,pagination=?,sql_style=?,approved=?,approveMsg=?,hints=? ");
sb.append(" WHERE id=? AND version=?");
builder.setTemplate(sb.toString());
StatementParameters parameters = new StatementParameters();
int i = 1;
parameters.set(i++, "project_id", Types.INTEGER, task.getProject_id());
parameters.set(i++, "db_name", Types.VARCHAR, task.getDatabaseSetName());
parameters.set(i++, "class_name", Types.VARCHAR, task.getClass_name());
parameters.set(i++, "pojo_name", Types.VARCHAR, task.getPojo_name());
parameters.set(i++, "method_name", Types.VARCHAR, task.getMethod_name());
parameters.set(i++, "crud_type", Types.VARCHAR, task.getCrud_type());
parameters.set(i++, "sql_content", Types.LONGVARCHAR, task.getSql_content());
parameters.set(i++, "parameters", Types.LONGVARCHAR, task.getParameters());
parameters.set(i++, "generated", Types.BIT, task.getGenerated());
parameters.set(i++, "update_user_no", Types.VARCHAR, task.getUpdate_user_no());
parameters.set(i++, "update_time", Types.TIMESTAMP, task.getUpdate_time());
parameters.set(i++, "comment", Types.LONGVARCHAR, task.getComment());
parameters.set(i++, "scalarType", Types.VARCHAR, task.getScalarType());
parameters.set(i++, "pojoType", Types.VARCHAR, task.getPojoType());
parameters.set(i++, "pagination", Types.BIT, task.getPagination());
parameters.set(i++, "sql_style", Types.VARCHAR, task.getSql_style());
parameters.set(i++, "approved", Types.INTEGER, task.getApproved());
parameters.set(i++, "approveMsg", Types.LONGVARCHAR, task.getApproveMsg());
parameters.set(i++, "hints", Types.VARCHAR, task.getHints());
// parameters.set(i++, "length", Types.TINYINT, task.getLength());
parameters.set(i++, "id", Types.INTEGER, task.getId());
parameters.set(i++, "version", Types.INTEGER, task.getVersion());
DalHints hints = DalHints.createIfAbsent(null);
return queryDao.update(builder, parameters, hints);
}
public int updateTask(int id, int approved, String approveMsg) throws SQLException {
FreeUpdateSqlBuilder builder = new FreeUpdateSqlBuilder(dbCategory);
builder.setTemplate("UPDATE task_sql SET approved=?, approveMsg=? WHERE id=?");
StatementParameters parameters = new StatementParameters();
int i = 1;
parameters.set(i++, "approved", Types.INTEGER, approved);
parameters.set(i++, "approveMsg", Types.VARCHAR, approveMsg);
parameters.set(i++, "id", Types.INTEGER, id);
DalHints hints = DalHints.createIfAbsent(null);
return queryDao.update(builder, parameters, hints);
}
public int deleteTask(GenTaskByFreeSql task) throws SQLException {
if (null == task)
return 0;
DalHints hints = DalHints.createIfAbsent(null);
return client.delete(hints, task);
}
public int deleteByProjectId(int projectId) throws SQLException {
FreeUpdateSqlBuilder builder = new FreeUpdateSqlBuilder(dbCategory);
builder.setTemplate("DELETE FROM task_sql WHERE project_id=?");
StatementParameters parameters = new StatementParameters();
int i = 1;
parameters.set(i++, "project_id", Types.INTEGER, projectId);
DalHints hints = DalHints.createIfAbsent(null);
return queryDao.update(builder, parameters, hints);
}
}
| apache-2.0 |
ChiangC/FMTech | GooglePlay6.0.5/app/src/main/java/okio/Buffer.java | 25756 | package okio;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class Buffer
implements Cloneable, BufferedSink, BufferedSource
{
Segment head;
public long size;
private void readFully(byte[] paramArrayOfByte)
throws EOFException
{
int i = 0;
while (i < paramArrayOfByte.length)
{
int j = read(paramArrayOfByte, i, paramArrayOfByte.length - i);
if (j == -1) {
throw new EOFException();
}
i += j;
}
}
private String readUtf8(long paramLong)
throws EOFException
{
Charset localCharset = Util.UTF_8;
Util.checkOffsetAndCount(this.size, 0L, paramLong);
if (localCharset == null) {
throw new IllegalArgumentException("charset == null");
}
if (paramLong > 2147483647L) {
throw new IllegalArgumentException("byteCount > Integer.MAX_VALUE: " + paramLong);
}
String str;
if (paramLong == 0L) {
str = "";
}
Segment localSegment;
do
{
return str;
localSegment = this.head;
if (paramLong + localSegment.pos > localSegment.limit) {
return new String(readByteArray(paramLong), localCharset);
}
str = new String(localSegment.data, localSegment.pos, (int)paramLong, localCharset);
localSegment.pos = ((int)(paramLong + localSegment.pos));
this.size -= paramLong;
} while (localSegment.pos != localSegment.limit);
this.head = localSegment.pop();
SegmentPool.INSTANCE.recycle(localSegment);
return str;
}
public final Buffer buffer()
{
return this;
}
public final void clear()
{
try
{
skip(this.size);
return;
}
catch (EOFException localEOFException)
{
throw new AssertionError(localEOFException);
}
}
public final Buffer clone()
{
Buffer localBuffer = new Buffer();
if (this.size == 0L) {}
for (;;)
{
return localBuffer;
localBuffer.write(this.head.data, this.head.pos, this.head.limit - this.head.pos);
for (Segment localSegment = this.head.next; localSegment != this.head; localSegment = localSegment.next) {
localBuffer.write(localSegment.data, localSegment.pos, localSegment.limit - localSegment.pos);
}
}
}
public final void close() {}
public final Buffer copyTo(OutputStream paramOutputStream, long paramLong1, long paramLong2)
throws IOException
{
Util.checkOffsetAndCount(this.size, 0L, paramLong2);
if (paramLong2 == 0L) {}
for (;;)
{
return this;
for (Segment localSegment = this.head; paramLong1 >= localSegment.limit - localSegment.pos; localSegment = localSegment.next) {
paramLong1 -= localSegment.limit - localSegment.pos;
}
while (paramLong2 > 0L)
{
int i = (int)(paramLong1 + localSegment.pos);
int j = (int)Math.min(localSegment.limit - i, paramLong2);
paramOutputStream.write(localSegment.data, i, j);
paramLong2 -= j;
paramLong1 = 0L;
localSegment = localSegment.next;
}
}
}
public final Buffer copyTo(Buffer paramBuffer, long paramLong1, long paramLong2)
{
if (paramBuffer == null) {
throw new IllegalArgumentException("out == null");
}
Util.checkOffsetAndCount(this.size, paramLong1, paramLong2);
if (paramLong2 == 0L) {}
for (;;)
{
return this;
Segment localSegment1 = this.head;
Segment localSegment2 = paramBuffer.writableSegment(1);
paramBuffer.size = (paramLong2 + paramBuffer.size);
while (paramLong2 > 0L)
{
while (paramLong1 >= localSegment1.limit - localSegment1.pos)
{
paramLong1 -= localSegment1.limit - localSegment1.pos;
localSegment1 = localSegment1.next;
}
if (localSegment2.limit == 2048) {
localSegment2 = localSegment2.push(SegmentPool.INSTANCE.take());
}
int i = (int)Math.min(Math.min(localSegment1.limit - (paramLong1 + localSegment1.pos), paramLong2), 2048 - localSegment2.limit);
System.arraycopy(localSegment1.data, localSegment1.pos + (int)paramLong1, localSegment2.data, localSegment2.limit, i);
paramLong1 += i;
localSegment2.limit = (i + localSegment2.limit);
paramLong2 -= i;
}
}
}
public final BufferedSink emit()
throws IOException
{
return this;
}
public final boolean equals(Object paramObject)
{
if (this == paramObject) {
return true;
}
if (!(paramObject instanceof Buffer)) {
return false;
}
Buffer localBuffer = (Buffer)paramObject;
if (this.size != localBuffer.size) {
return false;
}
if (this.size == 0L) {
return true;
}
Segment localSegment1 = this.head;
Segment localSegment2 = localBuffer.head;
int i = localSegment1.pos;
int j = localSegment2.pos;
long l1 = 0L;
long l2;
int m;
int n;
if (l1 < this.size)
{
l2 = Math.min(localSegment1.limit - i, localSegment2.limit - j);
int k = 0;
m = j;
int i1;
for (n = i; k < l2; n = i1)
{
byte[] arrayOfByte1 = localSegment1.data;
i1 = n + 1;
int i2 = arrayOfByte1[n];
byte[] arrayOfByte2 = localSegment2.data;
int i3 = m + 1;
if (i2 != arrayOfByte2[m]) {
return false;
}
k++;
m = i3;
}
if (n != localSegment1.limit) {
break label245;
}
localSegment1 = localSegment1.next;
}
label245:
for (i = localSegment1.pos;; i = n)
{
if (m == localSegment2.limit) {
localSegment2 = localSegment2.next;
}
for (j = localSegment2.pos;; j = m)
{
l1 += l2;
break;
return true;
}
}
}
public final boolean exhausted()
{
return this.size == 0L;
}
public final void flush() {}
public final byte getByte(long paramLong)
{
Util.checkOffsetAndCount(this.size, paramLong, 1L);
for (Segment localSegment = this.head;; localSegment = localSegment.next)
{
int i = localSegment.limit - localSegment.pos;
if (paramLong < i) {
return localSegment.data[(localSegment.pos + (int)paramLong)];
}
paramLong -= i;
}
}
public final int hashCode()
{
Segment localSegment = this.head;
if (localSegment == null) {
return 0;
}
int i = 1;
do
{
int j = localSegment.pos;
int k = localSegment.limit;
while (j < k)
{
i = i * 31 + localSegment.data[j];
j++;
}
localSegment = localSegment.next;
} while (localSegment != this.head);
return i;
}
public final long indexOf(byte paramByte)
{
return indexOf(paramByte, 0L);
}
public final long indexOf(byte paramByte, long paramLong)
{
if (paramLong < 0L) {
throw new IllegalArgumentException("fromIndex < 0");
}
Segment localSegment = this.head;
if (localSegment == null) {
return -1L;
}
long l1 = 0L;
int i = localSegment.limit - localSegment.pos;
if (paramLong >= i) {}
for (paramLong -= i;; paramLong = 0L)
{
l1 += i;
localSegment = localSegment.next;
if (localSegment != this.head) {
break;
}
return -1L;
byte[] arrayOfByte = localSegment.data;
long l2 = paramLong + localSegment.pos;
long l3 = localSegment.limit;
while (l2 < l3)
{
if (arrayOfByte[((int)l2)] == paramByte) {
return l1 + l2 - localSegment.pos;
}
l2 += 1L;
}
}
}
public final InputStream inputStream()
{
new InputStream()
{
public final int available()
{
return (int)Math.min(Buffer.this.size, 2147483647L);
}
public final void close() {}
public final int read()
{
if (Buffer.this.size > 0L) {
return 0xFF & Buffer.this.readByte();
}
return -1;
}
public final int read(byte[] paramAnonymousArrayOfByte, int paramAnonymousInt1, int paramAnonymousInt2)
{
return Buffer.this.read(paramAnonymousArrayOfByte, paramAnonymousInt1, paramAnonymousInt2);
}
public final String toString()
{
return Buffer.this + ".inputStream()";
}
};
}
public final int read(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
Util.checkOffsetAndCount(paramArrayOfByte.length, paramInt1, paramInt2);
Segment localSegment = this.head;
int i;
if (localSegment == null) {
i = -1;
}
do
{
return i;
i = Math.min(paramInt2, localSegment.limit - localSegment.pos);
System.arraycopy(localSegment.data, localSegment.pos, paramArrayOfByte, paramInt1, i);
localSegment.pos = (i + localSegment.pos);
this.size -= i;
} while (localSegment.pos != localSegment.limit);
this.head = localSegment.pop();
SegmentPool.INSTANCE.recycle(localSegment);
return i;
}
public final long read(Buffer paramBuffer, long paramLong)
{
if (paramBuffer == null) {
throw new IllegalArgumentException("sink == null");
}
if (paramLong < 0L) {
throw new IllegalArgumentException("byteCount < 0: " + paramLong);
}
if (this.size == 0L) {
return -1L;
}
if (paramLong > this.size) {
paramLong = this.size;
}
paramBuffer.write(this, paramLong);
return paramLong;
}
public final byte readByte()
{
if (this.size == 0L) {
throw new IllegalStateException("size == 0");
}
Segment localSegment = this.head;
int i = localSegment.pos;
int j = localSegment.limit;
byte[] arrayOfByte = localSegment.data;
int k = i + 1;
byte b = arrayOfByte[i];
this.size -= 1L;
if (k == j)
{
this.head = localSegment.pop();
SegmentPool.INSTANCE.recycle(localSegment);
return b;
}
localSegment.pos = k;
return b;
}
public final byte[] readByteArray()
{
try
{
byte[] arrayOfByte = readByteArray(this.size);
return arrayOfByte;
}
catch (EOFException localEOFException)
{
throw new AssertionError(localEOFException);
}
}
public final byte[] readByteArray(long paramLong)
throws EOFException
{
Util.checkOffsetAndCount(this.size, 0L, paramLong);
if (paramLong > 2147483647L) {
throw new IllegalArgumentException("byteCount > Integer.MAX_VALUE: " + paramLong);
}
byte[] arrayOfByte = new byte[(int)paramLong];
readFully(arrayOfByte);
return arrayOfByte;
}
public final ByteString readByteString()
{
return new ByteString(readByteArray());
}
public final ByteString readByteString(long paramLong)
throws EOFException
{
return new ByteString(readByteArray(paramLong));
}
public final int readInt()
{
if (this.size < 4L) {
throw new IllegalStateException("size < 4: " + this.size);
}
Segment localSegment = this.head;
int i = localSegment.pos;
int j = localSegment.limit;
if (j - i < 4) {
return (0xFF & readByte()) << 24 | (0xFF & readByte()) << 16 | (0xFF & readByte()) << 8 | 0xFF & readByte();
}
byte[] arrayOfByte = localSegment.data;
int k = i + 1;
int m = (0xFF & arrayOfByte[i]) << 24;
int n = k + 1;
int i1 = m | (0xFF & arrayOfByte[k]) << 16;
int i2 = n + 1;
int i3 = i1 | (0xFF & arrayOfByte[n]) << 8;
int i4 = i2 + 1;
int i5 = i3 | 0xFF & arrayOfByte[i2];
this.size -= 4L;
if (i4 == j)
{
this.head = localSegment.pop();
SegmentPool.INSTANCE.recycle(localSegment);
return i5;
}
localSegment.pos = i4;
return i5;
}
public final int readIntLe()
{
return Util.reverseBytesInt(readInt());
}
public final short readShort()
{
if (this.size < 2L) {
throw new IllegalStateException("size < 2: " + this.size);
}
Segment localSegment = this.head;
int i = localSegment.pos;
int j = localSegment.limit;
if (j - i < 2) {
return (short)((0xFF & readByte()) << 8 | 0xFF & readByte());
}
byte[] arrayOfByte = localSegment.data;
int k = i + 1;
int m = (0xFF & arrayOfByte[i]) << 8;
int n = k + 1;
int i1 = m | 0xFF & arrayOfByte[k];
this.size -= 2L;
if (n == j)
{
this.head = localSegment.pop();
SegmentPool.INSTANCE.recycle(localSegment);
}
for (;;)
{
return (short)i1;
localSegment.pos = n;
}
}
public final short readShortLe()
{
return Util.reverseBytesShort(readShort());
}
final String readUtf8Line(long paramLong)
throws EOFException
{
if ((paramLong > 0L) && (getByte(paramLong - 1L) == 13))
{
String str2 = readUtf8(paramLong - 1L);
skip(2L);
return str2;
}
String str1 = readUtf8(paramLong);
skip(1L);
return str1;
}
public final String readUtf8LineStrict()
throws EOFException
{
long l = indexOf((byte)10, 0L);
if (l == -1L)
{
Buffer localBuffer = new Buffer();
copyTo(localBuffer, 0L, Math.min(32L, this.size));
throw new EOFException("\\n not found: size=" + this.size + " content=" + localBuffer.readByteString().hex() + "...");
}
return readUtf8Line(l);
}
public final void require(long paramLong)
throws EOFException
{
if (this.size < paramLong) {
throw new EOFException();
}
}
public final void skip(long paramLong)
throws EOFException
{
while (paramLong > 0L)
{
if (this.head == null) {
throw new EOFException();
}
int i = (int)Math.min(paramLong, this.head.limit - this.head.pos);
this.size -= i;
paramLong -= i;
Segment localSegment1 = this.head;
localSegment1.pos = (i + localSegment1.pos);
if (this.head.pos == this.head.limit)
{
Segment localSegment2 = this.head;
this.head = localSegment2.pop();
SegmentPool.INSTANCE.recycle(localSegment2);
}
}
}
public final Timeout timeout()
{
return Timeout.NONE;
}
public final String toString()
{
if (this.size == 0L) {
return "Buffer[size=0]";
}
if (this.size <= 16L)
{
ByteString localByteString = clone().readByteString();
Object[] arrayOfObject2 = new Object[2];
arrayOfObject2[0] = Long.valueOf(this.size);
arrayOfObject2[1] = localByteString.hex();
return String.format("Buffer[size=%s data=%s]", arrayOfObject2);
}
try
{
MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
localMessageDigest.update(this.head.data, this.head.pos, this.head.limit - this.head.pos);
for (Segment localSegment = this.head.next; localSegment != this.head; localSegment = localSegment.next) {
localMessageDigest.update(localSegment.data, localSegment.pos, localSegment.limit - localSegment.pos);
}
Object[] arrayOfObject1 = new Object[2];
arrayOfObject1[0] = Long.valueOf(this.size);
arrayOfObject1[1] = ByteString.of(localMessageDigest.digest()).hex();
String str = String.format("Buffer[size=%s md5=%s]", arrayOfObject1);
return str;
}
catch (NoSuchAlgorithmException localNoSuchAlgorithmException)
{
throw new AssertionError();
}
}
final Segment writableSegment(int paramInt)
{
if ((paramInt <= 0) || (paramInt > 2048)) {
throw new IllegalArgumentException();
}
Segment localSegment1;
if (this.head == null)
{
this.head = SegmentPool.INSTANCE.take();
Segment localSegment2 = this.head;
Segment localSegment3 = this.head;
localSegment1 = this.head;
localSegment3.prev = localSegment1;
localSegment2.next = localSegment1;
}
do
{
return localSegment1;
localSegment1 = this.head.prev;
} while (paramInt + localSegment1.limit <= 2048);
return localSegment1.push(SegmentPool.INSTANCE.take());
}
public final Buffer write(ByteString paramByteString)
{
if (paramByteString == null) {
throw new IllegalArgumentException("byteString == null");
}
return write(paramByteString.data, 0, paramByteString.data.length);
}
public final Buffer write(byte[] paramArrayOfByte)
{
if (paramArrayOfByte == null) {
throw new IllegalArgumentException("source == null");
}
return write(paramArrayOfByte, 0, paramArrayOfByte.length);
}
public final Buffer write(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
if (paramArrayOfByte == null) {
throw new IllegalArgumentException("source == null");
}
Util.checkOffsetAndCount(paramArrayOfByte.length, paramInt1, paramInt2);
int i = paramInt1 + paramInt2;
while (paramInt1 < i)
{
Segment localSegment = writableSegment(1);
int j = Math.min(i - paramInt1, 2048 - localSegment.limit);
System.arraycopy(paramArrayOfByte, paramInt1, localSegment.data, localSegment.limit, j);
paramInt1 += j;
localSegment.limit = (j + localSegment.limit);
}
this.size += paramInt2;
return this;
}
public final void write(Buffer paramBuffer, long paramLong)
{
if (paramBuffer == null) {
throw new IllegalArgumentException("source == null");
}
if (paramBuffer == this) {
throw new IllegalArgumentException("source == this");
}
Util.checkOffsetAndCount(paramBuffer.size, 0L, paramLong);
Segment localSegment6;
Segment localSegment7;
int i;
int j;
Segment localSegment9;
label236:
Segment localSegment1;
long l;
if (paramLong > 0L) {
if (paramLong < paramBuffer.head.limit - paramBuffer.head.pos)
{
if (this.head != null) {}
for (localSegment6 = this.head.prev;; localSegment6 = null)
{
if ((localSegment6 != null) && (paramLong + (localSegment6.limit - localSegment6.pos) <= 2048L)) {
break label423;
}
localSegment7 = paramBuffer.head;
i = (int)paramLong;
j = localSegment7.limit - localSegment7.pos - i;
if ((i > 0) && (j > 0)) {
break;
}
throw new IllegalArgumentException();
}
if (i < j)
{
localSegment9 = SegmentPool.INSTANCE.take();
System.arraycopy(localSegment7.data, localSegment7.pos, localSegment9.data, localSegment9.pos, i);
localSegment7.pos = (i + localSegment7.pos);
localSegment9.limit = (i + localSegment9.limit);
localSegment7.prev.push(localSegment9);
paramBuffer.head = localSegment9;
}
}
else
{
localSegment1 = paramBuffer.head;
l = localSegment1.limit - localSegment1.pos;
paramBuffer.head = localSegment1.pop();
if (this.head != null) {
break label455;
}
this.head = localSegment1;
Segment localSegment3 = this.head;
Segment localSegment4 = this.head;
Segment localSegment5 = this.head;
localSegment4.prev = localSegment5;
localSegment3.next = localSegment5;
}
}
for (;;)
{
paramBuffer.size -= l;
this.size = (l + this.size);
paramLong -= l;
break;
Segment localSegment8 = SegmentPool.INSTANCE.take();
System.arraycopy(localSegment7.data, i + localSegment7.pos, localSegment8.data, localSegment8.pos, j);
localSegment7.limit -= j;
localSegment8.limit = (j + localSegment8.limit);
localSegment7.push(localSegment8);
localSegment9 = localSegment7;
break label236;
label423:
paramBuffer.head.writeTo(localSegment6, (int)paramLong);
paramBuffer.size -= paramLong;
this.size = (paramLong + this.size);
return;
label455:
Segment localSegment2 = this.head.prev.push(localSegment1);
if (localSegment2.prev == localSegment2) {
throw new IllegalStateException();
}
if (localSegment2.prev.limit - localSegment2.prev.pos + (localSegment2.limit - localSegment2.pos) <= 2048)
{
localSegment2.writeTo(localSegment2.prev, localSegment2.limit - localSegment2.pos);
localSegment2.pop();
SegmentPool.INSTANCE.recycle(localSegment2);
}
}
}
public final long writeAll(Source paramSource)
throws IOException
{
if (paramSource == null) {
throw new IllegalArgumentException("source == null");
}
long l2;
for (long l1 = 0L;; l1 += l2)
{
l2 = paramSource.read(this, 2048L);
if (l2 == -1L) {
break;
}
}
return l1;
}
public final Buffer writeByte(int paramInt)
{
Segment localSegment = writableSegment(1);
byte[] arrayOfByte = localSegment.data;
int i = localSegment.limit;
localSegment.limit = (i + 1);
arrayOfByte[i] = ((byte)paramInt);
this.size = (1L + this.size);
return this;
}
public final Buffer writeInt(int paramInt)
{
Segment localSegment = writableSegment(4);
byte[] arrayOfByte = localSegment.data;
int i = localSegment.limit;
int j = i + 1;
arrayOfByte[i] = ((byte)(0xFF & paramInt >>> 24));
int k = j + 1;
arrayOfByte[j] = ((byte)(0xFF & paramInt >>> 16));
int m = k + 1;
arrayOfByte[k] = ((byte)(0xFF & paramInt >>> 8));
int n = m + 1;
arrayOfByte[m] = ((byte)(paramInt & 0xFF));
localSegment.limit = n;
this.size = (4L + this.size);
return this;
}
public final Buffer writeShort(int paramInt)
{
Segment localSegment = writableSegment(2);
byte[] arrayOfByte = localSegment.data;
int i = localSegment.limit;
int j = i + 1;
arrayOfByte[i] = ((byte)(0xFF & paramInt >>> 8));
int k = j + 1;
arrayOfByte[j] = ((byte)(paramInt & 0xFF));
localSegment.limit = k;
this.size = (2L + this.size);
return this;
}
public final Buffer writeTo(OutputStream paramOutputStream, long paramLong)
throws IOException
{
Util.checkOffsetAndCount(this.size, 0L, paramLong);
Segment localSegment1 = this.head;
while (paramLong > 0L)
{
int i = (int)Math.min(paramLong, localSegment1.limit - localSegment1.pos);
paramOutputStream.write(localSegment1.data, localSegment1.pos, i);
localSegment1.pos = (i + localSegment1.pos);
this.size -= i;
paramLong -= i;
if (localSegment1.pos == localSegment1.limit)
{
Segment localSegment2 = localSegment1;
localSegment1 = localSegment2.pop();
this.head = localSegment1;
SegmentPool.INSTANCE.recycle(localSegment2);
}
}
return this;
}
public final Buffer writeUtf8(String paramString)
{
if (paramString == null) {
throw new IllegalArgumentException("string == null");
}
int i = paramString.length();
int j = 0;
while (j < i)
{
int k = paramString.charAt(j);
if (k < 128)
{
Segment localSegment = writableSegment(1);
byte[] arrayOfByte = localSegment.data;
int i1 = localSegment.limit - j;
int i2 = Math.min(i, 2048 - i1);
int i3 = j + 1;
arrayOfByte[(i1 + j)] = ((byte)k);
int i6;
for (j = i3; j < i2; j = i6)
{
int i5 = paramString.charAt(j);
if (i5 >= 128) {
break;
}
i6 = j + 1;
arrayOfByte[(i1 + j)] = ((byte)i5);
}
int i4 = j + i1 - localSegment.limit;
localSegment.limit = (i4 + localSegment.limit);
this.size += i4;
}
else if (k < 2048)
{
writeByte(0xC0 | k >> 6);
writeByte(0x80 | k & 0x3F);
j++;
}
else if ((k < 55296) || (k > 57343))
{
writeByte(0xE0 | k >> 12);
writeByte(0x80 | 0x3F & k >> 6);
writeByte(0x80 | k & 0x3F);
j++;
}
else
{
if (j + 1 < i) {}
for (int m = paramString.charAt(j + 1);; m = 0)
{
if ((k <= 56319) && (m >= 56320) && (m <= 57343)) {
break label345;
}
writeByte(63);
j++;
break;
}
label345:
int n = 65536 + ((0xFFFF27FF & k) << 10 | 0xFFFF23FF & m);
writeByte(0xF0 | n >> 18);
writeByte(0x80 | 0x3F & n >> 12);
writeByte(0x80 | 0x3F & n >> 6);
writeByte(0x80 | n & 0x3F);
j += 2;
}
}
return this;
}
}
/* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar
* Qualified Name: okio.Buffer
* JD-Core Version: 0.7.0.1
*/ | apache-2.0 |
hortonworks/cloudbreak | datalake/src/main/java/com/sequenceiq/datalake/flow/diagnostics/SdxDiagnosticsActions.java | 6409 | package com.sequenceiq.datalake.flow.diagnostics;
import static com.sequenceiq.datalake.flow.diagnostics.SdxDiagnosticsEvent.SDX_DIAGNOSTICS_COLLECTION_FAILED_HANDLED_EVENT;
import static com.sequenceiq.datalake.flow.diagnostics.SdxDiagnosticsEvent.SDX_DIAGNOSTICS_COLLECTION_FINALIZED_EVENT;
import static com.sequenceiq.datalake.flow.diagnostics.SdxDiagnosticsEvent.SDX_DIAGNOSTICS_COLLECTION_IN_PROGRESS_EVENT;
import java.util.Map;
import java.util.Optional;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.action.Action;
import com.sequenceiq.datalake.flow.SdxContext;
import com.sequenceiq.datalake.flow.diagnostics.event.SdxDiagnosticsFailedEvent;
import com.sequenceiq.datalake.flow.diagnostics.event.SdxDiagnosticsCollectionEvent;
import com.sequenceiq.datalake.flow.diagnostics.event.SdxDiagnosticsSuccessEvent;
import com.sequenceiq.datalake.flow.diagnostics.event.SdxDiagnosticsWaitRequest;
import com.sequenceiq.datalake.service.AbstractSdxAction;
import com.sequenceiq.flow.api.model.FlowIdentifier;
import com.sequenceiq.flow.core.FlowEvent;
import com.sequenceiq.flow.core.FlowParameters;
import com.sequenceiq.flow.core.FlowState;
@Configuration
public class SdxDiagnosticsActions {
private static final Logger LOGGER = LoggerFactory.getLogger(SdxDiagnosticsActions.class);
private static final String DIAGNOSTICS_UUID_PARAM = "uuid";
@Inject
private SdxDiagnosticsFlowService diagnosticsFlowService;
@Bean(name = "DIAGNOSTICS_COLLECTION_START_STATE")
public Action<?, ?> startDiagnosticsCollection() {
return new AbstractSdxAction<>(SdxDiagnosticsCollectionEvent.class) {
@Override
protected SdxContext createFlowContext(FlowParameters flowParameters,
StateContext<FlowState, FlowEvent> stateContext, SdxDiagnosticsCollectionEvent payload) {
return SdxContext.from(flowParameters, payload);
}
@Override
protected void doExecute(SdxContext context, SdxDiagnosticsCollectionEvent payload, Map<Object, Object> variables) {
LOGGER.debug("Start diagnostics collection for sdx cluster with id: {}", context.getSdxId());
payload.getProperties().put(DIAGNOSTICS_UUID_PARAM, context.getFlowId());
FlowIdentifier flowIdentifier = diagnosticsFlowService.startDiagnosticsCollection(payload.getProperties());
SdxDiagnosticsCollectionEvent event = new SdxDiagnosticsCollectionEvent(payload.getResourceId(),
payload.getUserId(), payload.getProperties(), flowIdentifier);
sendEvent(context, SDX_DIAGNOSTICS_COLLECTION_IN_PROGRESS_EVENT.event(), event);
}
@Override
protected Object getFailurePayload(SdxDiagnosticsCollectionEvent payload, Optional<SdxContext> flowContext, Exception ex) {
return SdxDiagnosticsFailedEvent.from(payload, ex);
}
};
}
@Bean("DIAGNOSTICS_COLLECTION_IN_PROGRESS_STATE")
public Action<?, ?> startDiagnosticsCollectionInProgress() {
return new AbstractSdxAction<>(SdxDiagnosticsCollectionEvent.class) {
@Override
protected SdxContext createFlowContext(FlowParameters flowParameters,
StateContext<FlowState, FlowEvent> stateContext, SdxDiagnosticsCollectionEvent payload) {
return SdxContext.from(flowParameters, payload);
}
@Override
protected void doExecute(SdxContext context, SdxDiagnosticsCollectionEvent payload, Map<Object, Object> variables) {
LOGGER.debug("Diagnostics collection is in progress for sdx cluster");
sendEvent(context, SdxDiagnosticsWaitRequest.from(context, payload));
}
@Override
protected Object getFailurePayload(SdxDiagnosticsCollectionEvent payload, Optional<SdxContext> flowContext, Exception ex) {
return SdxDiagnosticsFailedEvent.from(payload, ex);
}
};
}
@Bean("DIAGNOSTICS_COLLECTION_FINISHED_STATE")
public Action<?, ?> diagnosticsCollectionFinished() {
return new AbstractSdxAction<>(SdxDiagnosticsSuccessEvent.class) {
@Override
protected SdxContext createFlowContext(FlowParameters flowParameters,
StateContext<FlowState, FlowEvent> stateContext, SdxDiagnosticsSuccessEvent payload) {
return SdxContext.from(flowParameters, payload);
}
@Override
protected void doExecute(SdxContext context, SdxDiagnosticsSuccessEvent payload, Map<Object, Object> variables) {
LOGGER.debug("Diagnostics collection is finished for sdx cluster");
sendEvent(context, SDX_DIAGNOSTICS_COLLECTION_FINALIZED_EVENT.event(), payload);
}
@Override
protected Object getFailurePayload(SdxDiagnosticsSuccessEvent payload, Optional<SdxContext> flowContext, Exception ex) {
return SdxDiagnosticsFailedEvent.from(payload, ex);
}
};
}
@Bean("DIAGNOSTICS_COLLECTION_FAILED_STATE")
public Action<?, ?> diagnosticsCollectionFailed() {
return new AbstractSdxAction<>(SdxDiagnosticsFailedEvent.class) {
@Override
protected SdxContext createFlowContext(FlowParameters flowParameters,
StateContext<FlowState, FlowEvent> stateContext, SdxDiagnosticsFailedEvent payload) {
return SdxContext.from(flowParameters, payload);
}
@Override
protected void doExecute(SdxContext context, SdxDiagnosticsFailedEvent payload, Map<Object, Object> variables) {
LOGGER.debug("Diagnostics collection failed for sdx cluster");
sendEvent(context, SDX_DIAGNOSTICS_COLLECTION_FAILED_HANDLED_EVENT.event(), payload);
}
@Override
protected Object getFailurePayload(SdxDiagnosticsFailedEvent payload, Optional<SdxContext> flowContext, Exception ex) {
return null;
}
};
}
}
| apache-2.0 |
vhl8281/coolweather | app/src/main/java/com/example/wangmingxin/coolweather/activity/WeatherActivity.java | 6796 | package com.example.wangmingxin.coolweather.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.wangmingxin.coolweather.R;
import com.example.wangmingxin.coolweather.service.AutoUpdateService;
import com.example.wangmingxin.coolweather.util.HttpCallbackListener;
import com.example.wangmingxin.coolweather.util.HttpUtil;
import com.example.wangmingxin.coolweather.util.Utility;
import org.w3c.dom.Text;
/**
* Created by wangmingxin on 15/11/18.
*/
public class WeatherActivity extends Activity implements View.OnClickListener{
private LinearLayout weatherInfoLayout;
/**
* 用于显示城市名
*/
private TextView cityNameText;
/**
* 用于显示发布时间
*/
private TextView publishText;
/**
* 用于显示天气描述
*/
private TextView weatherDespText;
/**
* 用于显示气温1
*/
private TextView temp1Text;
/**
* 用于显示气温2
*/
private TextView temp2Text;
/**
* 用于显示当前日期
*/
private TextView currentDateText;
/**
* 切换城市按钮
*/
private Button switchCity;
/**
* 更新天气按钮
*/
private Button refreshWeather;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.weather_layout);
//初始化各控件
weatherInfoLayout = (LinearLayout) findViewById(R.id.weather_info_layout);
cityNameText = (TextView) findViewById(R.id.city_name);
publishText = (TextView) findViewById(R.id.publish_text);
weatherDespText = (TextView) findViewById(R.id.weather_desp);
temp1Text = (TextView) findViewById(R.id.temp1);
temp2Text = (TextView) findViewById(R.id.temp2);
currentDateText = (TextView) findViewById(R.id.current_date);
switchCity = (Button) findViewById(R.id.switch_city);
refreshWeather = (Button) findViewById(R.id.refresh_weather);
String countyCode = getIntent().getStringExtra("county_code");
if(!TextUtils.isEmpty(countyCode)){
//有县级代号时就去查询天气
publishText.setText("同步中");
weatherInfoLayout.setVisibility(View.VISIBLE);
cityNameText.setVisibility(View.INVISIBLE);
queryWeatherCode(countyCode);
} else{
//没有县级代号时就显示本地天气
showWeather();
}
switchCity.setOnClickListener(this);
refreshWeather.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.switch_city:
Intent intent = new Intent(this , ChooseAreaActivity.class);
intent.putExtra("from_weather_activity", true);
startActivity(intent);
finish();
break;
case R.id.refresh_weather:
publishText.setText("同步中...");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherCode = prefs.getString("weather_code" , "");
if(!TextUtils.isEmpty(weatherCode)){
queryWeatherInfo(weatherCode);
}
break;
default:
break;
}
}
/**
* 查询县级代号所对应的天气代号
*/
private void queryWeatherCode(String countyCode){
String address = "http://www.weather.com.cn/data/list3/city" + countyCode + ".xml";
queryFromServer(address , "countyCode");
}
/**
* 查询天气代号所对应的天气
*/
private void queryWeatherInfo(String weatherCode){
String address = "http://www.weather.com.cn/data/cityinfo/" + weatherCode + ".html";
queryFromServer(address , "weatherCode");
}
/**
* 根据传入的地址和类型去向服务器查询天气代号或者天气信息。
*/
private void queryFromServer(final String address , final String type){
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(final String response) {
if ("countyCode".equals(type)) {
if (!TextUtils.isEmpty(response)) {
//从服务器返回的数据中解析出天气代号
String[] array = response.split("\\|");
if (array != null && array.length == 2) {
String weatherCode = array[1];
queryWeatherInfo(weatherCode);
}
}
} else if ("weatherCode".equals(type)) {
//处理服务器返回的天气信息
Utility.handleWeatherResponse(WeatherActivity.this, response);
runOnUiThread(new Runnable() {
@Override
public void run() {
showWeather();
}
});
}
}
@Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
publishText.setText("同步失败");
}
});
}
});
}
/**
* 从SharePreferences文件中读取存储的天气信息,并显示在界面上。
*/
private void showWeather(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
cityNameText.setText(prefs.getString("city_name" , ""));
temp1Text.setText(prefs.getString("temp1" , ""));
temp2Text.setText(prefs.getString("temp2" , ""));
weatherDespText.setText(prefs.getString("weather_desp" , ""));
publishText.setText("今天" + prefs.getString("publish_time" , "") + "发布");
currentDateText.setText(prefs.getString("current_date", ""));
weatherInfoLayout.setVisibility(View.VISIBLE);
cityNameText.setVisibility(View.VISIBLE);
Intent intent = new Intent(this , AutoUpdateService.class);
startService(intent);
}
}
| apache-2.0 |
itgeeker/jdk | src/com/sun/org/apache/xml/internal/resolver/tools/ResolvingParser.java | 13284 | /*
* Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
// ResolvingParser.java - An interface for reading catalog files
/*
* Copyright 2001-2004 The Apache Software Foundation or its licensors,
* as applicable.
*
* 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.sun.org.apache.xml.internal.resolver.tools;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Locale;
import org.xml.sax.Parser;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.DocumentHandler;
import org.xml.sax.AttributeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl;
import com.sun.org.apache.xml.internal.resolver.Catalog;
import com.sun.org.apache.xml.internal.resolver.CatalogManager;
import com.sun.org.apache.xml.internal.resolver.helpers.FileURL;
/**
* A SAX Parser that performs catalog-based entity resolution.
*
* <p>This class implements a SAX Parser that performs entity resolution
* using the CatalogResolver. The actual, underlying parser is obtained
* from a SAXParserFactory.</p>
* </p>
*
* @deprecated This interface has been replaced by the
* {@link com.sun.org.apache.xml.internal.resolver.tools.ResolvingXMLReader} for SAX2.
* @see CatalogResolver
* @see org.xml.sax.Parser
*
* @author Norman Walsh
* <a href="mailto:Norman.Walsh@Sun.COM">Norman.Walsh@Sun.COM</a>
*
* @version 1.0
*/
public class ResolvingParser
implements Parser, DTDHandler, DocumentHandler, EntityResolver {
/** Make the parser Namespace aware? */
public static boolean namespaceAware = true;
/** Make the parser validating? */
public static boolean validating = false;
/** Suppress explanatory message?
*
* @see #parse(InputSource)
*/
public static boolean suppressExplanation = false;
/** The underlying parser. */
private SAXParser saxParser = null;
/** The underlying reader. */
private Parser parser = null;
/** The underlying DocumentHandler. */
private DocumentHandler documentHandler = null;
/** The underlying DTDHandler. */
private DTDHandler dtdHandler = null;
/** The manager for the underlying resolver. */
private CatalogManager catalogManager = CatalogManager.getStaticManager();
/** The underlying catalog resolver. */
private CatalogResolver catalogResolver = null;
/** A separate resolver for oasis-xml-pi catalogs. */
private CatalogResolver piCatalogResolver = null;
/** Are we in the prolog? Is an oasis-xml-catalog PI valid now? */
private boolean allowXMLCatalogPI = false;
/** Has an oasis-xml-catalog PI been seen? */
private boolean oasisXMLCatalogPI = false;
/** The base URI of the input document, if known. */
private URL baseURL = null;
/** Constructor. */
public ResolvingParser() {
initParser();
}
/** Constructor. */
public ResolvingParser(CatalogManager manager) {
catalogManager = manager;
initParser();
}
/** Initialize the parser. */
private void initParser() {
catalogResolver = new CatalogResolver(catalogManager);
SAXParserFactory spf = catalogManager.useServicesMechanism() ?
SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
spf.setNamespaceAware(namespaceAware);
spf.setValidating(validating);
try {
saxParser = spf.newSAXParser();
parser = saxParser.getParser();
documentHandler = null;
dtdHandler = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** Return the Catalog being used. */
public Catalog getCatalog() {
return catalogResolver.getCatalog();
}
/**
* SAX Parser API.
*
* <p>Note that the JAXP 1.1ea2 parser crashes with an InternalError if
* it encounters a system identifier that appears to be a relative URI
* that begins with a slash. For example, the declaration:</p>
*
* <pre>
* <!DOCTYPE book SYSTEM "/path/to/dtd/on/my/system/docbookx.dtd">
* </pre>
*
* <p>would cause such an error. As a convenience, this method catches
* that error and prints an explanation. (Unfortunately, it's not possible
* to identify the particular system identifier that causes the problem.)
* </p>
*
* <p>The underlying error is forwarded after printing the explanatory
* message. The message is only every printed once and if
* <code>suppressExplanation</code> is set to <code>false</code> before
* parsing, it will never be printed.</p>
*/
public void parse(InputSource input)
throws IOException,
SAXException {
setupParse(input.getSystemId());
try {
parser.parse(input);
} catch (InternalError ie) {
explain(input.getSystemId());
throw ie;
}
}
/** SAX Parser API.
*
* @see #parse(InputSource)
*/
public void parse(String systemId)
throws IOException,
SAXException {
setupParse(systemId);
try {
parser.parse(systemId);
} catch (InternalError ie) {
explain(systemId);
throw ie;
}
}
/** SAX Parser API. */
public void setDocumentHandler(DocumentHandler handler) {
documentHandler = handler;
}
/** SAX Parser API. */
public void setDTDHandler(DTDHandler handler) {
dtdHandler = handler;
}
/**
* SAX Parser API.
*
* <p>The purpose of this class is to implement an entity resolver.
* Attempting to set a different one is pointless (and ignored).</p>
*/
public void setEntityResolver(EntityResolver resolver) {
// nop
}
/** SAX Parser API. */
public void setErrorHandler(ErrorHandler handler) {
parser.setErrorHandler(handler);
}
/** SAX Parser API. */
public void setLocale(Locale locale) throws SAXException {
parser.setLocale(locale);
}
/** SAX DocumentHandler API. */
public void characters(char[] ch, int start, int length)
throws SAXException {
if (documentHandler != null) {
documentHandler.characters(ch,start,length);
}
}
/** SAX DocumentHandler API. */
public void endDocument() throws SAXException {
if (documentHandler != null) {
documentHandler.endDocument();
}
}
/** SAX DocumentHandler API. */
public void endElement(String name) throws SAXException {
if (documentHandler != null) {
documentHandler.endElement(name);
}
}
/** SAX DocumentHandler API. */
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
if (documentHandler != null) {
documentHandler.ignorableWhitespace(ch,start,length);
}
}
/** SAX DocumentHandler API. */
public void processingInstruction(String target, String pidata)
throws SAXException {
if (target.equals("oasis-xml-catalog")) {
URL catalog = null;
String data = pidata;
int pos = data.indexOf("catalog=");
if (pos >= 0) {
data = data.substring(pos+8);
if (data.length() > 1) {
String quote = data.substring(0,1);
data = data.substring(1);
pos = data.indexOf(quote);
if (pos >= 0) {
data = data.substring(0, pos);
try {
if (baseURL != null) {
catalog = new URL(baseURL, data);
} else {
catalog = new URL(data);
}
} catch (MalformedURLException mue) {
// nevermind
}
}
}
}
if (allowXMLCatalogPI) {
if (catalogManager.getAllowOasisXMLCatalogPI()) {
catalogManager.debug.message(4,"oasis-xml-catalog PI", pidata);
if (catalog != null) {
try {
catalogManager.debug.message(4,"oasis-xml-catalog", catalog.toString());
oasisXMLCatalogPI = true;
if (piCatalogResolver == null) {
piCatalogResolver = new CatalogResolver(true);
}
piCatalogResolver.getCatalog().parseCatalog(catalog.toString());
} catch (Exception e) {
catalogManager.debug.message(3, "Exception parsing oasis-xml-catalog: "
+ catalog.toString());
}
} else {
catalogManager.debug.message(3, "PI oasis-xml-catalog unparseable: " + pidata);
}
} else {
catalogManager.debug.message(4,"PI oasis-xml-catalog ignored: " + pidata);
}
} else {
catalogManager.debug.message(3, "PI oasis-xml-catalog occurred in an invalid place: "
+ pidata);
}
} else {
if (documentHandler != null) {
documentHandler.processingInstruction(target, pidata);
}
}
}
/** SAX DocumentHandler API. */
public void setDocumentLocator(Locator locator) {
if (documentHandler != null) {
documentHandler.setDocumentLocator(locator);
}
}
/** SAX DocumentHandler API. */
public void startDocument() throws SAXException {
if (documentHandler != null) {
documentHandler.startDocument();
}
}
/** SAX DocumentHandler API. */
public void startElement(String name, AttributeList atts)
throws SAXException {
allowXMLCatalogPI = false;
if (documentHandler != null) {
documentHandler.startElement(name,atts);
}
}
/** SAX DTDHandler API. */
public void notationDecl (String name, String publicId, String systemId)
throws SAXException {
allowXMLCatalogPI = false;
if (dtdHandler != null) {
dtdHandler.notationDecl(name,publicId,systemId);
}
}
/** SAX DTDHandler API. */
public void unparsedEntityDecl (String name,
String publicId,
String systemId,
String notationName)
throws SAXException {
allowXMLCatalogPI = false;
if (dtdHandler != null) {
dtdHandler.unparsedEntityDecl (name, publicId, systemId, notationName);
}
}
/**
* Implements the <code>resolveEntity</code> method
* for the SAX interface, using an underlying CatalogResolver
* to do the real work.
*/
public InputSource resolveEntity (String publicId, String systemId) {
allowXMLCatalogPI = false;
String resolved = catalogResolver.getResolvedEntity(publicId, systemId);
if (resolved == null && piCatalogResolver != null) {
resolved = piCatalogResolver.getResolvedEntity(publicId, systemId);
}
if (resolved != null) {
try {
InputSource iSource = new InputSource(resolved);
iSource.setPublicId(publicId);
// Ideally this method would not attempt to open the
// InputStream, but there is a bug (in Xerces, at least)
// that causes the parser to mistakenly open the wrong
// system identifier if the returned InputSource does
// not have a byteStream.
//
// It could be argued that we still shouldn't do this here,
// but since the purpose of calling the entityResolver is
// almost certainly to open the input stream, it seems to
// do little harm.
//
URL url = new URL(resolved);
InputStream iStream = url.openStream();
iSource.setByteStream(iStream);
return iSource;
} catch (Exception e) {
catalogManager.debug.message(1, "Failed to create InputSource", resolved);
return null;
}
} else {
return null;
}
}
/** Setup for parsing. */
private void setupParse(String systemId) {
allowXMLCatalogPI = true;
parser.setEntityResolver(this);
parser.setDocumentHandler(this);
parser.setDTDHandler(this);
URL cwd = null;
try {
cwd = FileURL.makeURL("basename");
} catch (MalformedURLException mue) {
cwd = null;
}
try {
baseURL = new URL(systemId);
} catch (MalformedURLException mue) {
if (cwd != null) {
try {
baseURL = new URL(cwd, systemId);
} catch (MalformedURLException mue2) {
// give up
baseURL = null;
}
} else {
// give up
baseURL = null;
}
}
}
/** Provide one possible explanation for an InternalError. */
private void explain(String systemId) {
if (!suppressExplanation) {
System.out.println("Parser probably encountered bad URI in " + systemId);
System.out.println("For example, replace '/some/uri' with 'file:/some/uri'.");
}
}
}
| apache-2.0 |
Petikoch/feedback_control_bookexamples_in_java | src/main/java/ch/petikoch/examples/feedbackControlInJava/ui/util/SwingUtils.java | 1664 | /**
* Copyright 2015 Peti Koch, All rights reserved.
*
* Project Info:
* https://github.com/Petikoch/feedback_control_bookexamples_in_java
*
* 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 ch.petikoch.examples.feedbackControlInJava.ui.util;
import com.google.common.base.Throwables;
import javax.swing.*;
import java.lang.reflect.InvocationTargetException;
public class SwingUtils {
public static void executeBlockingOnEdt(Runnable runnable) throws InvocationTargetException, InterruptedException {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
SwingUtilities.invokeAndWait(runnable);
}
}
public static void printStackTraceAndDisplayToUser(Throwable ex) {
ex.printStackTrace();
SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(
null,
Throwables.getStackTraceAsString(ex),
"Opps...",
JOptionPane.ERROR_MESSAGE));
}
// for testing
public static void main(String[] args) {
printStackTraceAndDisplayToUser(new NullPointerException());
}
}
| apache-2.0 |
marques-work/gocd | server/src/test-fast/java/com/thoughtworks/go/server/service/BuildAssignmentServiceTest.java | 36954 | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.service;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.elastic.ClusterProfile;
import com.thoughtworks.go.config.elastic.ElasticProfile;
import com.thoughtworks.go.config.materials.PackageMaterial;
import com.thoughtworks.go.config.materials.PluggableSCMMaterial;
import com.thoughtworks.go.config.materials.ScmMaterial;
import com.thoughtworks.go.config.materials.git.GitMaterial;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.domain.config.ConfigurationValue;
import com.thoughtworks.go.domain.exception.IllegalArtifactLocationException;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.helper.*;
import com.thoughtworks.go.plugin.access.exceptions.SecretResolutionFailureException;
import com.thoughtworks.go.remote.work.BuildAssignment;
import com.thoughtworks.go.remote.work.BuildWork;
import com.thoughtworks.go.server.domain.ElasticAgentMetadata;
import com.thoughtworks.go.server.exceptions.RulesViolationException;
import com.thoughtworks.go.server.messaging.JobStatusMessage;
import com.thoughtworks.go.server.messaging.JobStatusTopic;
import com.thoughtworks.go.server.service.builders.BuilderFactory;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.springframework.transaction.PlatformTransactionManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import static com.thoughtworks.go.helper.MaterialsMother.packageMaterial;
import static com.thoughtworks.go.helper.MaterialsMother.pluggableSCMMaterial;
import static com.thoughtworks.go.server.service.BuildAssignmentService.GO_AGENT_RESOURCES;
import static com.thoughtworks.go.server.service.BuildAssignmentService.GO_PIPELINE_GROUP_NAME;
import static com.thoughtworks.go.util.command.EnvironmentVariableContext.GO_ENVIRONMENT_NAME;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
class BuildAssignmentServiceTest {
@Mock
private GoConfigService goConfigService;
@Mock
private JobInstanceService jobInstanceService;
@Mock
private ScheduleService scheduleService;
@Mock
private ElasticAgentPluginService elasticAgentPluginService;
@Mock
private SystemEnvironment systemEnvironment;
@Mock
private BuilderFactory builderFactory;
@Mock
private PipelineService pipelineService;
@Mock
private MaintenanceModeService maintenanceModeService;
@Mock
private ScheduledPipelineLoader scheduledPipelineLoader;
@Mock
private EnvironmentConfigService environmentConfigService;
@Mock
private AgentService agentService;
@Mock
private SecretParamResolver secretParamResolver;
@Mock
private JobStatusTopic jobStatusTopic;
@Mock
private ConsoleService consoleService;
private BuildAssignmentService buildAssignmentService;
private TransactionTemplate transactionTemplate;
private SchedulingContext schedulingContext;
private ArrayList<JobPlan> jobPlans;
private Agent elasticAgent;
private AgentInstance elasticAgentInstance;
private ElasticProfile elasticProfile1;
private ElasticProfile elasticProfile2;
private String elasticProfileId1;
private String elasticProfileId2;
private AgentInstance regularAgentInstance;
@BeforeEach
void setUp() throws Exception {
initMocks(this);
transactionTemplate = dummy();
buildAssignmentService = new BuildAssignmentService(goConfigService, jobInstanceService, scheduleService, agentService,
environmentConfigService, transactionTemplate, scheduledPipelineLoader, pipelineService, builderFactory,
maintenanceModeService, elasticAgentPluginService, systemEnvironment, secretParamResolver,
jobStatusTopic, consoleService);
elasticProfileId1 = "elastic.profile.id.1";
elasticProfileId2 = "elastic.profile.id.2";
elasticAgent = AgentMother.elasticAgent();
elasticAgentInstance = AgentInstance.createFromAgent(elasticAgent, new SystemEnvironment(), null);
regularAgentInstance = AgentInstance.createFromAgent(AgentMother.approvedAgent(), new SystemEnvironment(), null);
elasticProfile1 = new ElasticProfile(elasticProfileId1, "prod-cluster");
elasticProfile2 = new ElasticProfile(elasticProfileId2, "prod-cluster");
jobPlans = new ArrayList<>();
HashMap<String, ElasticProfile> profiles = new HashMap<>();
profiles.put(elasticProfile1.getId(), elasticProfile1);
profiles.put(elasticProfile2.getId(), elasticProfile2);
schedulingContext = new DefaultSchedulingContext("me", new Agents(elasticAgent), profiles);
when(jobInstanceService.orderedScheduledBuilds()).thenReturn(jobPlans);
when(environmentConfigService.filterJobsByAgent(ArgumentMatchers.eq(jobPlans), any(String.class))).thenReturn(jobPlans);
when(environmentConfigService.envForPipeline(any(String.class))).thenReturn("");
when(maintenanceModeService.isMaintenanceMode()).thenReturn(false);
}
@Test
void shouldMatchAnElasticJobToAnElasticAgentOnlyIfThePluginAgreesToTheAssignment() {
PipelineConfig pipelineWithElasticJob = PipelineConfigMother.pipelineWithElasticJob(elasticProfileId1);
JobPlan jobPlan = new InstanceFactory().createJobPlan(pipelineWithElasticJob.first().getJobs().first(), schedulingContext);
jobPlans.add(jobPlan);
when(elasticAgentPluginService.shouldAssignWork(elasticAgentInstance.elasticAgentMetadata(), null, jobPlan.getElasticProfile(), jobPlan.getClusterProfile(), jobPlan.getIdentifier())).thenReturn(true);
buildAssignmentService.onTimer();
JobPlan matchingJob = buildAssignmentService.findMatchingJob(elasticAgentInstance);
assertThat(matchingJob).isEqualTo(jobPlan);
assertThat(buildAssignmentService.jobPlans().size()).isEqualTo(0);
}
@Test
void shouldNotMatchAnElasticJobToAnElasticAgentOnlyIfThePluginIdMatches() {
PipelineConfig pipelineWithElasticJob = PipelineConfigMother.pipelineWithElasticJob(elasticProfileId1);
JobPlan jobPlan1 = new InstanceFactory().createJobPlan(pipelineWithElasticJob.first().getJobs().first(), schedulingContext);
jobPlans.add(jobPlan1);
when(elasticAgentPluginService.shouldAssignWork(elasticAgentInstance.elasticAgentMetadata(), null, jobPlan1.getElasticProfile(), jobPlan1.getClusterProfile(), null)).thenReturn(false);
buildAssignmentService.onTimer();
JobPlan matchingJob = buildAssignmentService.findMatchingJob(elasticAgentInstance);
assertThat(matchingJob).isNull();
assertThat(buildAssignmentService.jobPlans().size()).isEqualTo(1);
}
@Test
void shouldMatchAnElasticJobToAnElasticAgentOnlyIfThePluginAgreesToTheAssignmentWhenMultipleElasticJobsRequiringTheSamePluginAreScheduled() {
PipelineConfig pipelineWith2ElasticJobs = PipelineConfigMother.pipelineWithElasticJob(elasticProfileId1, elasticProfileId2);
JobPlan jobPlan1 = new InstanceFactory().createJobPlan(pipelineWith2ElasticJobs.first().getJobs().first(), schedulingContext);
JobPlan jobPlan2 = new InstanceFactory().createJobPlan(pipelineWith2ElasticJobs.first().getJobs().last(), schedulingContext);
jobPlans.add(jobPlan1);
jobPlans.add(jobPlan2);
when(elasticAgentPluginService.shouldAssignWork(elasticAgentInstance.elasticAgentMetadata(), null, jobPlan1.getElasticProfile(), jobPlan1.getClusterProfile(), jobPlan1.getIdentifier())).thenReturn(false);
when(elasticAgentPluginService.shouldAssignWork(elasticAgentInstance.elasticAgentMetadata(), null, jobPlan2.getElasticProfile(), jobPlan2.getClusterProfile(), jobPlan2.getIdentifier())).thenReturn(true);
buildAssignmentService.onTimer();
JobPlan matchingJob = buildAssignmentService.findMatchingJob(elasticAgentInstance);
assertThat(matchingJob).isEqualTo(jobPlan2);
assertThat(buildAssignmentService.jobPlans().size()).isEqualTo(1);
}
@Test
void shouldMatchNonElasticJobToNonElasticAgentIfResourcesMatch() {
PipelineConfig pipeline = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
pipeline.first().getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
pipeline.first().getJobs().add(JobConfigMother.elasticJob(elasticProfileId1));
JobPlan elasticJobPlan = new InstanceFactory().createJobPlan(pipeline.first().getJobs().last(), schedulingContext);
JobPlan regularJobPlan = new InstanceFactory().createJobPlan(pipeline.first().getJobs().first(), schedulingContext);
jobPlans.add(elasticJobPlan);
jobPlans.add(regularJobPlan);
buildAssignmentService.onTimer();
JobPlan matchingJob = buildAssignmentService.findMatchingJob(regularAgentInstance);
assertThat(matchingJob).isEqualTo(regularJobPlan);
assertThat(buildAssignmentService.jobPlans().size()).isEqualTo(1);
verify(elasticAgentPluginService, never()).shouldAssignWork(any(ElasticAgentMetadata.class), any(String.class), any(ElasticProfile.class), any(ClusterProfile.class), any(JobIdentifier.class));
}
@Test
void shouldNotMatchJobsDuringMaintenanceMode() {
when(maintenanceModeService.isMaintenanceMode()).thenReturn(true);
PipelineConfig pipeline = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
pipeline.first().getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
pipeline.first().getJobs().add(JobConfigMother.elasticJob(elasticProfileId1));
JobPlan elasticJobPlan = new InstanceFactory().createJobPlan(pipeline.first().getJobs().last(), schedulingContext);
JobPlan regularJobPlan = new InstanceFactory().createJobPlan(pipeline.first().getJobs().first(), schedulingContext);
jobPlans.add(elasticJobPlan);
jobPlans.add(regularJobPlan);
buildAssignmentService.onTimer();
JobPlan matchingJob = buildAssignmentService.findMatchingJob(regularAgentInstance);
assertThat(matchingJob).isNull();
assertThat(buildAssignmentService.jobPlans().size()).isEqualTo(0);
verify(elasticAgentPluginService, never()).shouldAssignWork(any(ElasticAgentMetadata.class), any(String.class), any(ElasticProfile.class), any(ClusterProfile.class), any(JobIdentifier.class));
}
@Test
void shouldGetMismatchingJobPlansInCaseOfPipelineHasUpdated() {
StageConfig second = StageConfigMother.stageConfig("second");
second.getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
PipelineConfig pipeline = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
pipeline.get(0).getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
pipeline.add(second);
PipelineConfig irrelevantPipeline = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
irrelevantPipeline.get(0).getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
JobPlan jobPlan1 = getJobPlan(pipeline.getName(), pipeline.get(0).name(), pipeline.get(0).getJobs().last());
JobPlan jobPlan2 = getJobPlan(pipeline.getName(), pipeline.get(1).name(), pipeline.get(1).getJobs().first());
JobPlan jobPlan3 = getJobPlan(irrelevantPipeline.getName(), irrelevantPipeline.get(0).name(), irrelevantPipeline.get(0).getJobs().first());
//need to get hold of original jobPlans in the tests
jobPlans = (ArrayList<JobPlan>) buildAssignmentService.jobPlans();
jobPlans.add(jobPlan1);
jobPlans.add(jobPlan2);
jobPlans.add(jobPlan3);
//delete a stage
pipeline.remove(1);
assertThat(jobPlans.size()).isEqualTo(3);
when(goConfigService.hasPipelineNamed(pipeline.getName())).thenReturn(true);
buildAssignmentService.pipelineConfigChangedListener().onEntityConfigChange(pipeline);
assertThat(jobPlans.size()).isEqualTo(2);
assertThat(jobPlans.get(0)).isEqualTo(jobPlan1);
assertThat(jobPlans.get(1)).isEqualTo(jobPlan3);
}
@Test
void shouldGetMismatchingJobPlansInCaseOfPipelineHasBeenDeleted() {
StageConfig second = StageConfigMother.stageConfig("second");
second.getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
PipelineConfig pipeline = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
pipeline.get(0).getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
pipeline.add(second);
PipelineConfig irrelevantPipeline = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
irrelevantPipeline.get(0).getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
JobPlan jobPlan1 = getJobPlan(pipeline.getName(), pipeline.get(0).name(), pipeline.get(0).getJobs().last());
JobPlan jobPlan2 = getJobPlan(pipeline.getName(), pipeline.get(1).name(), pipeline.get(1).getJobs().first());
JobPlan jobPlan3 = getJobPlan(irrelevantPipeline.getName(), irrelevantPipeline.get(0).name(), irrelevantPipeline.get(0).getJobs().first());
//need to get hold of original jobPlans in the tests
jobPlans = (ArrayList<JobPlan>) buildAssignmentService.jobPlans();
jobPlans.add(jobPlan1);
jobPlans.add(jobPlan2);
jobPlans.add(jobPlan3);
when(goConfigService.hasPipelineNamed(pipeline.getName())).thenReturn(false);
buildAssignmentService.pipelineConfigChangedListener().onEntityConfigChange(pipeline);
assertThat(jobPlans.size()).isEqualTo(1);
assertThat(jobPlans.get(0)).isEqualTo(jobPlan3);
}
@Nested
class AssignWorkToAgent {
@Test
void shouldResolveSecretParamsFromEnvironmentConfig() {
BasicEnvironmentConfig environmentConfig = new BasicEnvironmentConfig();
environmentConfig.addEnvironmentVariable("GIT_USERNAME", "bob");
environmentConfig.addEnvironmentVariable("GIT_TOKEN", "{{SECRET:[secret_config_id][GIT_TOKEN]}}");
final PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
pipelineConfig.get(0).getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
final AgentInstance agentInstance = mock(AgentInstance.class);
when(agentInstance.getResourceConfigs()).thenReturn(mock(ResourceConfigs.class));
agentInstance.getResourceConfigs().add(new ResourceConfig("resource-1"));
agentInstance.getResourceConfigs().add(new ResourceConfig("resource-2"));
final Pipeline pipeline = mock(Pipeline.class);
final JobPlan jobPlan1 = getJobPlan(pipelineConfig.getName(), pipelineConfig.get(0).name(), pipelineConfig.get(0).getJobs().last());
when(agentInstance.isRegistered()).thenReturn(true);
when(agentInstance.getAgent()).thenReturn(mock(Agent.class));
when(agentInstance.firstMatching(anyList())).thenReturn(jobPlan1);
when(pipeline.getBuildCause()).thenReturn(BuildCause.createNeverRun());
when(environmentConfigService.filterJobsByAgent(any(), any())).thenReturn(singletonList(jobPlan1));
when(scheduledPipelineLoader.pipelineWithPasswordAwareBuildCauseByBuildId(anyLong())).thenReturn(pipeline);
when(scheduleService.updateAssignedInfo(anyString(), any())).thenReturn(false);
when(goConfigService.artifactStores()).thenReturn(new ArtifactStores());
when(environmentConfigService.environmentForPipeline(anyString())).thenReturn(environmentConfig);
doAnswer(invocation -> {
BasicEnvironmentConfig config = invocation.getArgument(0);
config.getSecretParams().findFirst("GIT_TOKEN").ifPresent(param -> param.setValue("some-token"));
return config;
}).when(secretParamResolver).resolve(environmentConfig);
BuildWork work = (BuildWork) buildAssignmentService.assignWorkToAgent(agentInstance);
EnvironmentVariableContext environmentVariableContext = work.getAssignment().initialEnvironmentVariableContext();
assertThat(environmentVariableContext.getProperty("GIT_USERNAME")).isEqualTo("bob");
assertThat(environmentVariableContext.getProperty("GIT_TOKEN")).isEqualTo("some-token");
assertThat(environmentVariableContext.getProperty(GO_AGENT_RESOURCES)).isEqualTo(agentInstance.getResourceConfigs().getCommaSeparatedResourceNames());
assertThat(environmentVariableContext.getSecureEnvironmentVariables())
.contains(new EnvironmentVariableContext.EnvironmentVariable("GIT_TOKEN", "some-token"));
}
@Test
void shouldResolveSecretParamsInMaterials() {
final GitMaterial gitMaterial = MaterialsMother.gitMaterial("http://foo.com");
gitMaterial.setUserName("bob");
gitMaterial.setPassword("{{SECRET:[secret_config_id][GIT_PASSWORD]}}");
final Modification modification = new Modification("user", null, null, null, "rev1");
final MaterialRevisions materialRevisions = new MaterialRevisions(new MaterialRevision(gitMaterial, modification));
final PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
pipelineConfig.get(0).getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
final AgentInstance agentInstance = mock(AgentInstance.class);
final Pipeline pipeline = mock(Pipeline.class);
final JobPlan jobPlan1 = getJobPlan(pipelineConfig.getName(), pipelineConfig.get(0).name(), pipelineConfig.get(0).getJobs().last());
when(agentInstance.isRegistered()).thenReturn(true);
when(agentInstance.getAgent()).thenReturn(mock(Agent.class));
when(agentInstance.firstMatching(anyList())).thenReturn(jobPlan1);
when(pipeline.getBuildCause()).thenReturn(BuildCause.createWithModifications(materialRevisions, "bob"));
when(environmentConfigService.filterJobsByAgent(any(), any())).thenReturn(singletonList(jobPlan1));
when(scheduledPipelineLoader.pipelineWithPasswordAwareBuildCauseByBuildId(anyLong())).thenReturn(pipeline);
when(scheduleService.updateAssignedInfo(anyString(), any())).thenReturn(false);
when(goConfigService.artifactStores()).thenReturn(new ArtifactStores());
doAnswer(invocation -> {
BuildAssignment assignment = invocation.getArgument(0);
assignment.getSecretParams().findFirst("GIT_PASSWORD").ifPresent(param -> param.setValue("some-password"));
return assignment;
}).when(secretParamResolver).resolve(any(BuildAssignment.class));
BuildWork work = (BuildWork) buildAssignmentService.assignWorkToAgent(agentInstance);
assertThat(gitMaterial.hasSecretParams()).isTrue();
verify(scheduleService, never()).failJob(any(JobInstance.class));
verifyZeroInteractions(consoleService);
verifyZeroInteractions(jobStatusTopic);
ScmMaterial material = (ScmMaterial) work.getAssignment().materialRevisions().getMaterialRevision(0).getMaterial();
assertThat(material.passwordForCommandLine()).isEqualTo("some-password");
assertThat(work.getAssignment().initialEnvironmentVariableContext().hasProperty(GO_AGENT_RESOURCES)).isFalse();
}
@Test
void shouldFailJobIfSecretsResolutionFails() throws Exception {
final MaterialRevisions materialRevisions = new MaterialRevisions();
final PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
pipelineConfig.get(0).getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
final AgentInstance agentInstance = mock(AgentInstance.class);
final Pipeline pipeline = mock(Pipeline.class);
final JobPlan jobPlan1 = getJobPlan(pipelineConfig.getName(), pipelineConfig.get(0).name(), pipelineConfig.get(0).getJobs().last());
JobInstance jobInstance = mock(JobInstance.class);
when(agentInstance.isRegistered()).thenReturn(true);
when(agentInstance.firstMatching(anyList())).thenReturn(jobPlan1);
when(pipeline.getBuildCause()).thenReturn(BuildCause.createWithModifications(materialRevisions, "bob"));
when(scheduledPipelineLoader.pipelineWithPasswordAwareBuildCauseByBuildId(anyLong())).thenReturn(pipeline);
when(goConfigService.artifactStores()).thenReturn(new ArtifactStores());
when(jobInstanceService.buildById(jobPlan1.getJobId())).thenReturn(jobInstance);
when(agentInstance.getUuid()).thenReturn("agent_uuid");
when(jobInstance.getState()).thenReturn(JobState.Completed);
doThrow(new SecretResolutionFailureException("Failed resolving params for keys: 'key1'"))
.when(secretParamResolver).resolve(any(BuildAssignment.class));
assertThatCode(() -> buildAssignmentService.assignWorkToAgent(agentInstance))
.isInstanceOf(SecretResolutionFailureException.class);
InOrder inOrder = inOrder(scheduleService, jobStatusTopic, consoleService);
inOrder.verify(consoleService, times(2)).appendToConsoleLog(eq(jobPlan1.getIdentifier()), anyString());
inOrder.verify(scheduleService).failJob(jobInstance);
inOrder.verify(jobStatusTopic).post(new JobStatusMessage(jobPlan1.getIdentifier(), JobState.Completed, "agent_uuid"));
}
@Test
void shouldFailJobIfEnvironmentVariableInEnvironmentConfigCanNotReferToSecretConfig() throws Exception {
final PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
pipelineConfig.get(0).getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
final AgentInstance agentInstance = mock(AgentInstance.class);
final Pipeline pipeline = mock(Pipeline.class);
final JobPlan jobPlan1 = getJobPlan(pipelineConfig.getName(), pipelineConfig.get(0).name(), pipelineConfig.get(0).getJobs().last());
JobInstance jobInstance = mock(JobInstance.class);
when(jobInstance.getState()).thenReturn(JobState.Completed);
when(agentInstance.isRegistered()).thenReturn(true);
when(agentInstance.getUuid()).thenReturn("agent_uuid");
when(agentInstance.getAgent()).thenReturn(mock(Agent.class));
when(agentInstance.firstMatching(anyList())).thenReturn(jobPlan1);
when(pipeline.getBuildCause()).thenReturn(BuildCause.createNeverRun());
when(environmentConfigService.filterJobsByAgent(any(), any())).thenReturn(singletonList(jobPlan1));
when(scheduledPipelineLoader.pipelineWithPasswordAwareBuildCauseByBuildId(anyLong())).thenReturn(pipeline);
when(scheduleService.updateAssignedInfo(anyString(), any())).thenReturn(false);
when(goConfigService.artifactStores()).thenReturn(new ArtifactStores());
when(environmentConfigService.environmentForPipeline(anyString())).thenReturn(new BasicEnvironmentConfig());
when(jobInstanceService.buildById(anyLong())).thenReturn(jobInstance);
doThrow(new RulesViolationException("Failed resolving params for keys: 'key1'"))
.when(secretParamResolver).resolve(any(EnvironmentConfig.class));
assertThatCode(() -> buildAssignmentService.assignWorkToAgent(agentInstance))
.isInstanceOf(RulesViolationException.class);
InOrder inOrder = inOrder(scheduleService, jobStatusTopic, consoleService);
inOrder.verify(consoleService, times(1)).appendToConsoleLog(eq(jobPlan1.getIdentifier()), anyString());
inOrder.verify(scheduleService).failJob(jobInstance);
inOrder.verify(jobStatusTopic).post(new JobStatusMessage(jobPlan1.getIdentifier(), JobState.Completed, "agent_uuid"));
}
@Test
void shouldResolveSecretsInPluggableScmMaterialAndPackageMaterialBeforeCreatingAssignment() {
final GitMaterial gitMaterial = MaterialsMother.gitMaterial("http://foo.com");
gitMaterial.setUserName("bob");
gitMaterial.setPassword("{{SECRET:[secret_config_id][GIT_PASSWORD]}}");
PluggableSCMMaterial pluggableSCMMaterial = pluggableSCMMaterial();
pluggableSCMMaterial.getScmConfig().getConfiguration().get(0).setConfigurationValue(new ConfigurationValue("{{SECRET:[secret_config_id][SCM_PASSWORD]}}"));
PackageMaterial packageMaterial = packageMaterial();
packageMaterial.getPackageDefinition().getConfiguration().get(0).setConfigurationValue(new ConfigurationValue("{{SECRET:[secret_config_id][PKG_PASSWORD]}}"));
final Modification modification = new Modification("user", null, null, null, "rev1");
final MaterialRevisions materialRevisions = new MaterialRevisions(new MaterialRevision(gitMaterial, modification));
materialRevisions.addRevision(new MaterialRevision(pluggableSCMMaterial, new Modification("user2", null, null, null, "rev")));
materialRevisions.addRevision(new MaterialRevision(packageMaterial, new Modification("user3", null, null, null, "rev-pkg")));
final PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig(UUID.randomUUID().toString());
pipelineConfig.get(0).getJobs().add(JobConfigMother.jobWithNoResourceRequirement());
final AgentInstance agentInstance = mock(AgentInstance.class);
final Pipeline pipeline = mock(Pipeline.class);
final JobPlan jobPlan1 = getJobPlan(pipelineConfig.getName(), pipelineConfig.get(0).name(), pipelineConfig.get(0).getJobs().last());
when(agentInstance.isRegistered()).thenReturn(true);
when(agentInstance.getAgent()).thenReturn(mock(Agent.class));
when(agentInstance.firstMatching(anyList())).thenReturn(jobPlan1);
when(pipeline.getBuildCause()).thenReturn(BuildCause.createWithModifications(materialRevisions, "bob"));
when(environmentConfigService.filterJobsByAgent(any(), any())).thenReturn(singletonList(jobPlan1));
when(scheduledPipelineLoader.pipelineWithPasswordAwareBuildCauseByBuildId(anyLong())).thenReturn(pipeline);
when(scheduleService.updateAssignedInfo(anyString(), any())).thenReturn(false);
when(goConfigService.artifactStores()).thenReturn(new ArtifactStores());
doAnswer(invocation -> {
BuildAssignment assignment = invocation.getArgument(0);
assignment.getSecretParams().findFirst("GIT_PASSWORD").ifPresent(param -> param.setValue("some-password"));
return assignment;
}).when(secretParamResolver).resolve(any(BuildAssignment.class));
doAnswer(invocation -> {
List<Material> materials = invocation.getArgument(0);
((PluggableSCMMaterial) materials.get(0)).getScmConfig().getConfiguration().get(0).getSecretParams().get(0).setValue("some-scm-password");
((PackageMaterial) materials.get(1)).getPackageDefinition().getConfiguration().get(0).getSecretParams().get(0).setValue("some-pkg-password");
return materials;
}).when(secretParamResolver).resolve(anyList());
InOrder inOrder = inOrder(goConfigService, secretParamResolver);
BuildWork work = (BuildWork) buildAssignmentService.assignWorkToAgent(agentInstance);
inOrder.verify(secretParamResolver).resolve(asList(pluggableSCMMaterial, packageMaterial));
inOrder.verify(goConfigService).artifactStores();
inOrder.verify(secretParamResolver).resolve(any(BuildAssignment.class));
assertThat(gitMaterial.hasSecretParams()).isTrue();
ScmMaterial material = (ScmMaterial) work.getAssignment().materialRevisions().getMaterialRevision(0).getMaterial();
assertThat(material.passwordForCommandLine()).isEqualTo("some-password");
PluggableSCMMaterial material1 = (PluggableSCMMaterial) work.getAssignment().materialRevisions().getMaterialRevision(1).getMaterial();
assertThat(material1.getScmConfig().getConfiguration().get(0).getResolvedValue()).isEqualTo("some-scm-password");
PackageMaterial material2 = (PackageMaterial) work.getAssignment().materialRevisions().getMaterialRevision(2).getMaterial();
assertThat(material2.getPackageDefinition().getConfiguration().get(0).getResolvedValue()).isEqualTo("some-pkg-password");
}
}
@Test
void shouldGetEnvironmentVariableContextIncludingGO_ENVIRONMENT_NAMEVariable() {
String pipelineName = "pipeline1";
String environmentName = "uat_environment";
when(environmentConfigService.environmentForPipeline(pipelineName)).thenReturn(new BasicEnvironmentConfig(new CaseInsensitiveString(environmentName)));
EnvironmentVariableContext context = buildAssignmentService.buildEnvVarContext(pipelineName);
assertThat(context.getProperties().size()).isEqualTo(2);
assertThat(context.getProperty(GO_ENVIRONMENT_NAME)).isEqualTo(environmentName);
}
@Test
void shouldSetEnvironmentVariableContextIncludingGO_PIPELINE_GROUP_NAMEVariable() {
String pipelineName = "pipeline1";
String pipelineGroupName = "pipeline-group1";
String environmentName = "uat_environment";
when(goConfigService.findGroupNameByPipeline(new CaseInsensitiveString(pipelineName))).thenReturn(pipelineGroupName);
when(environmentConfigService.environmentForPipeline(pipelineName)).thenReturn(new BasicEnvironmentConfig(new CaseInsensitiveString(environmentName)));
EnvironmentVariableContext context = buildAssignmentService.buildEnvVarContext(pipelineName);
assertThat(context.getProperties().size()).isEqualTo(2);
assertThat(context.getProperty(GO_PIPELINE_GROUP_NAME)).isEqualTo(pipelineGroupName);
}
@Test
void shouldNotSetEnvPropertyWhenNoEnvironmentBelongingToSpecifiedPipelineExists() {
String pipelineName = "pipeline1";
when(environmentConfigService.environmentForPipeline(pipelineName)).thenReturn(null);
EnvironmentVariableContext context = buildAssignmentService.buildEnvVarContext(pipelineName);
assertThat(context.getProperties().size()).isEqualTo(1);
assertThat(context.getProperty(GO_ENVIRONMENT_NAME)).isNullOrEmpty();
}
@Test
void shouldFailTheJobWhenRulesViolationErrorOccursForElasticConfiguration() throws IOException, IllegalArtifactLocationException {
PipelineConfig pipelineWithElasticJob = PipelineConfigMother.pipelineWithElasticJob(elasticProfileId1);
JobPlan jobPlan = new InstanceFactory().createJobPlan(pipelineWithElasticJob.first().getJobs().first(), schedulingContext);
jobPlans.add(jobPlan);
JobInstance jobInstance = mock(JobInstance.class);
doThrow(new RulesViolationException("some rules related violation message"))
.when(elasticAgentPluginService).shouldAssignWork(elasticAgentInstance.elasticAgentMetadata(), null, jobPlan.getElasticProfile(), jobPlan.getClusterProfile(), jobPlan.getIdentifier());
when(jobInstance.getState()).thenReturn(JobState.Scheduled);
when(jobInstanceService.buildById(anyLong())).thenReturn(jobInstance);
buildAssignmentService.onTimer();
assertThatCode(() -> {
JobPlan matchingJob = buildAssignmentService.findMatchingJob(elasticAgentInstance);
assertThat(matchingJob).isNull();
assertThat(buildAssignmentService.jobPlans()).containsExactly(jobPlan);
}).doesNotThrowAnyException();
InOrder inOrder = inOrder(jobInstanceService, scheduleService, consoleService, jobStatusTopic);
inOrder.verify(jobInstanceService).buildById(jobPlan.getJobId());
inOrder.verify(consoleService).appendToConsoleLog(jobPlan.getIdentifier(), "\nThis job was failed by GoCD. This job is configured to run on an elastic agent, there were errors while resolving secrets for the the associated elastic configurations.\nReasons: some rules related violation message");
inOrder.verify(scheduleService).failJob(jobInstance);
inOrder.verify(jobStatusTopic).post(new JobStatusMessage(jobPlan.getIdentifier(), JobState.Scheduled, elasticAgentInstance.getUuid()));
}
@Test
void shouldFailTheJobWhenSecretResolutionErrorOccursForElasticConfiguration() throws IOException, IllegalArtifactLocationException {
PipelineConfig pipelineWithElasticJob = PipelineConfigMother.pipelineWithElasticJob(elasticProfileId1);
JobPlan jobPlan = new InstanceFactory().createJobPlan(pipelineWithElasticJob.first().getJobs().first(), schedulingContext);
jobPlans.add(jobPlan);
JobInstance jobInstance = mock(JobInstance.class);
doThrow(new SecretResolutionFailureException("some secret resolution related failure message"))
.when(elasticAgentPluginService).shouldAssignWork(elasticAgentInstance.elasticAgentMetadata(), null, jobPlan.getElasticProfile(), jobPlan.getClusterProfile(), jobPlan.getIdentifier());
when(jobInstance.getState()).thenReturn(JobState.Scheduled);
when(jobInstanceService.buildById(anyLong())).thenReturn(jobInstance);
buildAssignmentService.onTimer();
assertThatCode(() -> {
JobPlan matchingJob = buildAssignmentService.findMatchingJob(elasticAgentInstance);
assertThat(matchingJob).isNull();
assertThat(buildAssignmentService.jobPlans()).containsExactly(jobPlan);
}).doesNotThrowAnyException();
InOrder inOrder = inOrder(jobInstanceService, scheduleService, consoleService, jobStatusTopic);
inOrder.verify(jobInstanceService).buildById(jobPlan.getJobId());
inOrder.verify(consoleService).appendToConsoleLog(jobPlan.getIdentifier(), "\nThis job was failed by GoCD. This job is configured to run on an elastic agent, there were errors while resolving secrets for the the associated elastic configurations.\nReasons: some secret resolution related failure message");
inOrder.verify(scheduleService).failJob(jobInstance);
inOrder.verify(jobStatusTopic).post(new JobStatusMessage(jobPlan.getIdentifier(), JobState.Scheduled, elasticAgentInstance.getUuid()));
}
private JobPlan getJobPlan(CaseInsensitiveString pipelineName, CaseInsensitiveString stageName, JobConfig job) {
JobPlan jobPlan = new InstanceFactory().createJobPlan(job, schedulingContext);
jobPlan.getIdentifier().setPipelineName(pipelineName.toString());
jobPlan.getIdentifier().setStageName(stageName.toString());
jobPlan.getIdentifier().setBuildName(job.name().toString());
jobPlan.getIdentifier().setPipelineCounter(1);
return jobPlan;
}
private TransactionTemplate dummy() {
PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
return new TransactionTemplate(new org.springframework.transaction.support.TransactionTemplate(transactionManager));
}
}
| apache-2.0 |
marques-work/gocd | server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/validators/authorization/RoleConfigurationValidatorTest.java | 4787 | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.service.plugins.validators.authorization;
import com.thoughtworks.go.config.PluginRoleConfig;
import com.thoughtworks.go.config.exceptions.RecordNotFoundException;
import com.thoughtworks.go.domain.config.ConfigurationKey;
import com.thoughtworks.go.domain.config.ConfigurationProperty;
import com.thoughtworks.go.domain.config.ConfigurationValue;
import com.thoughtworks.go.plugin.access.authorization.AuthorizationExtension;
import com.thoughtworks.go.plugin.api.response.validation.ValidationError;
import com.thoughtworks.go.plugin.api.response.validation.ValidationResult;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.Map;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class RoleConfigurationValidatorTest {
private AuthorizationExtension extension;
private RoleConfigurationValidator validator;
@Before
public void setUp() throws Exception {
extension = mock(AuthorizationExtension.class);
validator = new RoleConfigurationValidator(extension);
when(extension.validateRoleConfiguration(any(String.class), any(Map.class))).thenReturn(new ValidationResult());
}
@Test
public void shouldValidateRoleConfigurationWithPlugin() throws Exception {
ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("view"));
PluginRoleConfig roleConfig = new PluginRoleConfig("admin", "auth_id", property);
validator.validate(roleConfig, "pluginId");
verify(extension).validateRoleConfiguration("pluginId", Collections.singletonMap("username", "view"));
}
@Test
public void shouldMapValidationErrorsToRoleConfiguration() throws Exception {
ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("view"));
PluginRoleConfig roleConfig = new PluginRoleConfig("admin", "auth_id", property);
ValidationResult result = new ValidationResult();
result.addError(new ValidationError("username", "username format is incorrect"));
when(extension.validateRoleConfiguration("pluginId", Collections.singletonMap("username", "view"))).thenReturn(result);
validator.validate(roleConfig, "pluginId");
assertTrue(roleConfig.hasErrors());
assertThat(roleConfig.getProperty("username").errors().get("username").get(0), is("username format is incorrect"));
}
@Test
public void shouldAddConfigurationAndMapErrorsInAbsenceOfConfiguration() throws Exception {
ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("view"));
PluginRoleConfig roleConfig = new PluginRoleConfig("admin", "auth_id", property);
ValidationResult result = new ValidationResult();
result.addError(new ValidationError("password", "password is required"));
when(extension.validateRoleConfiguration("pluginId", Collections.singletonMap("username", "view"))).thenReturn(result);
validator.validate(roleConfig, "pluginId");
assertTrue(roleConfig.hasErrors());
assertThat(roleConfig.getProperty("password").errors().get("password").get(0), is("password is required"));
assertNull(roleConfig.getProperty("password").getValue());
}
@Test
public void shouldAddErrorsInAbsenceOfPlugin() throws Exception {
ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("view"));
PluginRoleConfig roleConfig = new PluginRoleConfig("admin", "auth_id", property);
when(extension.validateRoleConfiguration("pluginId", Collections.singletonMap("username", "view"))).thenThrow(new RecordNotFoundException("not found"));
validator.validate(roleConfig, "pluginId");
assertTrue(roleConfig.hasErrors());
assertThat(roleConfig.errors().get("pluginRole").get(0), is("Unable to validate `pluginRole` configuration, missing plugin: pluginId"));
}
}
| apache-2.0 |
opensingular/singular-core | lib/commons/src/main/java/org/opensingular/internal/lib/commons/util/DebugOutputTable.java | 5997 | package org.opensingular.internal.lib.commons.util;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Helps formats the output in columns with values aligned between lines.
* <p>The resultatnt table ill respect the {@link DebugOutput} current indentation level.</p>
*
* @author Daniel C. Bordin
* @since 2018-10-03
*/
public class DebugOutputTable {
private final DebugOutput out;
private boolean silentMode;
private int currentPos;
private boolean pendingValue;
private final List<InfoColumn> columns = new ArrayList<>();
DebugOutputTable(@Nonnull DebugOutput debugOutput) {
this.out = Objects.requireNonNull(debugOutput);
}
/**
* Creates a table with a line for each element of the collection and the values for each cell of the line provided
* by the informed line mapper.
* <p><The collection will read twice.</p>
*/
public <T> void map(@Nonnull Collection<T> value, @Nonnull BiConsumer<DebugOutputTable, T> lineMapper) {
map(value, lineMapper, null);
}
/**
* Creates a table with a line for each element of the collection and the values for each cell of the line provided
* by the informed line mapper.
* <p><The collection will read twice.</p>
*
* @param preMapper Called before generating the values. It'll probably create the header.
*/
public <T> void map(@Nonnull Collection<T> value, @Nonnull BiConsumer<DebugOutputTable, T> lineMapper,
@Nullable Consumer<DebugOutputTable> preMapper) {
silentMode = true;
mapInternal(value, lineMapper, preMapper);
silentMode = false;
mapInternal(value, lineMapper, preMapper);
}
private <T> void mapInternal(@Nonnull Collection<T> value, @Nonnull BiConsumer<DebugOutputTable, T> lineMapper,
@Nullable Consumer<DebugOutputTable> preMapper) {
if (preMapper != null) {
preMapper.accept(this);
if (pendingValue) {
println();
}
}
value.forEach(v -> {
lineMapper.accept(this, v);
println();
});
}
/**
* Creates a new column with the initial informed width. The width will be automatic adjusted if the column receives
* a larger value.
*/
public void addColumn(int width) {
columns.add(new InfoColumn(width));
}
/**
* Adds a new value for in the current line and column, then changes the current cell to the next column in the
* line.
*/
public void addValue(@Nullable Object value) {
setValue(currentPos, value);
currentPos++;
}
/**
* Add all the values to the current line (multiples call to {@link #addValue(Object)} then close the current line
* (prinln()).
*/
public void addLine(@Nullable Object... values) {
if (values != null) {
for (Object v : values) {
addValue(v);
}
}
println();
}
/**
* Add all the values to the current line (multiples call to {@link #addValue(Object)} then close the current line
* (println()).
*/
public void addLine(@Nullable Collection<?> values) {
addLine(values, null);
}
/**
* Add all the values, after transforming then with the informed mapper, to the current line (multiples call to
* {@link #addValue(Object)} then close the current line (println()).
*/
public <T> void addLine(@Nullable Collection<T> values, @Nullable Function<T, Object> mapper) {
if (values != null) {
Function<T, ?> f = mapper == null ? Function.identity() : mapper;
values.forEach(v -> addValue(v == null ? null : f.apply(v)));
}
println();
}
/** Same as {@link #addLine(Collection)}. */
public void println(@Nullable Object... values) {
addLine(values);
}
/** Set the value of column in the index position in the current line. Null values won't be printed. */
public void setValue(int index, @Nullable Object value) {
if (value != null) {
while (index >= columns.size()) {
addColumn(0);
}
columns.get(index).setValue(value);
pendingValue = true;
}
}
/** Writes all the value (columns) to the {@link DebugOutput} and closes the current line. */
public void println() {
int last = columns.size() - 1;
while (last != -1 && columns.get(last).getValue() == null) {
last--;
}
for (int i = 0; i <= last; i++) {
if (i != 0 && !silentMode) {
out.print(' ');
}
InfoColumn col = columns.get(i);
String v = col.getValue();
col.setValue(null);
if (v == null) {
v = "";
}
if (i != last) {
v = StringUtils.rightPad(v, col.size);
}
if (!silentMode) {
out.print(v);
}
}
currentPos = 0;
pendingValue = false;
if (!silentMode) {
out.println();
}
}
private static class InfoColumn {
public int size;
private String value;
InfoColumn(int size) {
this.size = size;
}
public void setValue(Object v) {
setValue(v == null ? null : v.toString());
}
public void setValue(String v) {
value = v;
if (v != null) {
size = Math.max(size, v.length());
}
}
public String getValue() {
return value;
}
}
}
| apache-2.0 |
ruspl-afed/dbeaver | plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/dialogs/connection/EditShellCommandsDialogPage.java | 13936 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.dialogs.connection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.connection.DBPConnectionEventType;
import org.jkiss.dbeaver.model.runtime.DBRShellCommand;
import org.jkiss.dbeaver.registry.DataSourceDescriptor;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.controls.TextWithOpenFolder;
import org.jkiss.dbeaver.ui.controls.VariablesHintLabel;
import org.jkiss.dbeaver.ui.dialogs.ActiveWizardPage;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Events edit dialog page
*/
public class EditShellCommandsDialogPage extends ActiveWizardPage<ConnectionWizard> {
private Text commandText;
private Button showProcessCheck;
private Button waitFinishCheck;
private Spinner waitFinishTimeoutMs;
private Button terminateCheck;
private Spinner pauseAfterExecute;
private TextWithOpenFolder workingDirectory;
private Table eventTypeTable;
private final Map<DBPConnectionEventType, DBRShellCommand> eventsCache = new HashMap<>();
protected EditShellCommandsDialogPage(DataSourceDescriptor dataSource)
{
super(CoreMessages.dialog_connection_events_title);
setTitle("Shell Commands");
setDescription(CoreMessages.dialog_connection_events_title);
setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.EVENT));
for (DBPConnectionEventType eventType : DBPConnectionEventType.values()) {
DBRShellCommand command = dataSource.getConnectionConfiguration().getEvent(eventType);
eventsCache.put(eventType, command == null ? null : new DBRShellCommand(command));
}
}
@Override
public void createControl(Composite parent)
{
Composite group = UIUtils.createPlaceholder(parent, 2);
group.setLayoutData(new GridData(GridData.FILL_BOTH));
{
Composite eventGroup = new Composite(group, SWT.NONE);
eventGroup.setLayout(new GridLayout(1, false));
eventGroup.setLayoutData(new GridData(GridData.FILL_VERTICAL));
UIUtils.createControlLabel(eventGroup, CoreMessages.dialog_connection_events_label_event);
eventTypeTable = new Table(eventGroup, SWT.BORDER | SWT.CHECK | SWT.SINGLE | SWT.FULL_SELECTION);
eventTypeTable.setLayoutData(new GridData(GridData.FILL_VERTICAL));
eventTypeTable.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
if (event.detail == SWT.CHECK) {
eventTypeTable.select(eventTypeTable.indexOf((TableItem) event.item));
}
}
});
for (DBPConnectionEventType eventType : DBPConnectionEventType.values()) {
DBRShellCommand command = eventsCache.get(eventType);
TableItem item = new TableItem(eventTypeTable, SWT.NONE);
item.setData(eventType);
item.setText(eventType.getTitle());
item.setImage(DBeaverIcons.getImage(UIIcon.EVENT));
item.setChecked(command != null && command.isEnabled());
}
eventTypeTable.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
DBPConnectionEventType eventType = getSelectedEventType();
selectEventType(eventType);
DBRShellCommand command = eventType == null ? null : eventsCache.get(eventType);
boolean enabled = ((TableItem) e.item).getChecked();
if (enabled || (command != null && enabled != command.isEnabled())) {
updateEvent(false);
}
}
});
}
{
Composite detailsGroup = new Composite(group, SWT.NONE);
detailsGroup.setLayout(new GridLayout(1, false));
detailsGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
//UIUtils.createControlGroup(group, "Event", 1, GridData.FILL_BOTH | GridData.HORIZONTAL_ALIGN_BEGINNING, 0);
UIUtils.createControlLabel(detailsGroup, CoreMessages.dialog_connection_events_label_command);
commandText = new Text(detailsGroup, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
commandText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e)
{
updateEvent(true);
}
});
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.heightHint = 60;
gd.widthHint = 300;
commandText.setLayoutData(gd);
SelectionAdapter eventEditAdapter = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
updateEvent(false);
}
};
showProcessCheck = UIUtils.createCheckbox(detailsGroup, CoreMessages.dialog_connection_events_checkbox_show_process, false);
showProcessCheck.addSelectionListener(eventEditAdapter);
waitFinishCheck = UIUtils.createCheckbox(detailsGroup, CoreMessages.dialog_connection_events_checkbox_wait_finish, false);
waitFinishCheck.addSelectionListener(eventEditAdapter);
waitFinishTimeoutMs = createWaitFinishTimeout(detailsGroup);
waitFinishTimeoutMs.addSelectionListener(eventEditAdapter);
terminateCheck = UIUtils.createCheckbox(detailsGroup, CoreMessages.dialog_connection_events_checkbox_terminate_at_disconnect, false);
terminateCheck.addSelectionListener(eventEditAdapter);
{
Composite pauseComposite = UIUtils.createPlaceholder(detailsGroup, 2, 5);
pauseComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
pauseAfterExecute = UIUtils.createLabelSpinner(pauseComposite, "Pause after execute (ms)", "Wait for specified amount of milliseconds after process spawn", 0, 0, Integer.MAX_VALUE);
pauseAfterExecute.addSelectionListener(eventEditAdapter);
UIUtils.createControlLabel(pauseComposite, "Working directory");
workingDirectory = new TextWithOpenFolder(pauseComposite, "Working directory");
workingDirectory.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
workingDirectory.getTextControl().addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e)
{
DBRShellCommand command = getActiveCommand();
if (command != null) {
command.setWorkingDirectory(workingDirectory.getText());
}
}
});
}
new VariablesHintLabel(detailsGroup, DataSourceDescriptor.CONNECT_VARIABLES);
}
selectEventType(null);
setControl(group);
}
private static Spinner createWaitFinishTimeout(Composite detailsGroup) {
Composite waitFinishGroup = new Composite(detailsGroup, SWT.NONE);
GridLayout waitFinishGroupLayout = new GridLayout(2, false);
waitFinishGroupLayout.marginWidth = 0;
waitFinishGroupLayout.marginHeight = 0;
waitFinishGroupLayout.marginLeft = 25;
waitFinishGroup.setLayout(waitFinishGroupLayout);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
waitFinishGroup.setLayoutData(gridData);
int defaultValue = DBRShellCommand.WAIT_PROCESS_TIMEOUT_FOREVER;
int maxSelection = DBRShellCommand.WAIT_PROCESS_TIMEOUT_MAX_SELECTION;
Spinner spinner = UIUtils.createSpinner(waitFinishGroup, "-1 to wait forever", 0, defaultValue, maxSelection);
UIUtils.createLabel(waitFinishGroup, CoreMessages.dialog_connection_events_checkbox_wait_finish_timeout);
return spinner;
}
private DBPConnectionEventType getSelectedEventType()
{
TableItem[] selection = eventTypeTable.getSelection();
return ArrayUtils.isEmpty(selection) ? null : (DBPConnectionEventType) selection[0].getData();
}
private TableItem getEventItem(DBPConnectionEventType eventType)
{
for (TableItem item : eventTypeTable.getItems()) {
if (item.getData() == eventType) {
return item;
}
}
return null;
}
private DBRShellCommand getActiveCommand() {
DBPConnectionEventType eventType = getSelectedEventType();
if (eventType != null) {
DBRShellCommand command = eventsCache.get(eventType);
if (command == null) {
command = new DBRShellCommand(""); //$NON-NLS-1$
eventsCache.put(eventType, command);
}
return command;
}
return null;
}
private void updateEvent(boolean commandChange)
{
DBPConnectionEventType eventType = getSelectedEventType();
DBRShellCommand command = getActiveCommand();
if (command != null) {
boolean prevEnabled = command.isEnabled();
if (commandChange) {
command.setCommand(commandText.getText());
} else {
TableItem item = getEventItem(eventType);
if (item != null) {
command.setEnabled(item.getChecked());
}
command.setShowProcessPanel(showProcessCheck.getSelection());
command.setWaitProcessFinish(waitFinishCheck.getSelection());
waitFinishTimeoutMs.setEnabled(waitFinishCheck.getSelection());
command.setWaitProcessTimeoutMs(waitFinishTimeoutMs.getSelection());
command.setTerminateAtDisconnect(terminateCheck.getSelection());
command.setPauseAfterExecute(pauseAfterExecute.getSelection());
command.setWorkingDirectory(workingDirectory.getText());
if (prevEnabled != command.isEnabled()) {
selectEventType(eventType);
}
}
} else if (!commandChange) {
selectEventType(null);
}
}
private void selectEventType(DBPConnectionEventType eventType)
{
DBRShellCommand command = eventType == null ? null : eventsCache.get(eventType);
commandText.setEnabled(command != null && command.isEnabled());
showProcessCheck.setEnabled(command != null && command.isEnabled());
waitFinishCheck.setEnabled(command != null && command.isEnabled());
waitFinishTimeoutMs.setEnabled(waitFinishCheck.isEnabled());
terminateCheck.setEnabled(command != null && command.isEnabled());
pauseAfterExecute.setEnabled(command != null && command.isEnabled());
workingDirectory.setEnabled(command != null && command.isEnabled());
workingDirectory.getTextControl().setEnabled(command != null && command.isEnabled());
if (command != null) {
commandText.setText(CommonUtils.toString(command.getCommand()));
showProcessCheck.setSelection(command.isShowProcessPanel());
waitFinishCheck.setSelection(command.isWaitProcessFinish());
waitFinishTimeoutMs.setSelection(command.getWaitProcessTimeoutMs());
terminateCheck.setSelection(command.isTerminateAtDisconnect());
pauseAfterExecute.setSelection(command.getPauseAfterExecute());
workingDirectory.setText(CommonUtils.notEmpty(command.getWorkingDirectory()));
} else {
commandText.setText(""); //$NON-NLS-1$
showProcessCheck.setSelection(false);
waitFinishCheck.setSelection(false);
waitFinishTimeoutMs.setSelection(DBRShellCommand.WAIT_PROCESS_TIMEOUT_FOREVER);
terminateCheck.setSelection(false);
pauseAfterExecute.setSelection(0);
workingDirectory.setText("");
}
}
void saveConfigurations(DataSourceDescriptor dataSource)
{
for (Map.Entry<DBPConnectionEventType, DBRShellCommand> entry : eventsCache.entrySet()) {
dataSource.getConnectionConfiguration().setEvent(entry.getKey(), entry.getValue());
}
}
}
| apache-2.0 |
robertvazan/sourceafis-java | src/main/java/com/machinezoo/sourceafis/engine/extractor/RelativeContrastMask.java | 1458 | // Part of SourceAFIS for Java: https://sourceafis.machinezoo.com/java
package com.machinezoo.sourceafis.engine.extractor;
import java.util.*;
import com.machinezoo.sourceafis.engine.configuration.*;
import com.machinezoo.sourceafis.engine.primitives.*;
import com.machinezoo.sourceafis.engine.transparency.*;
public class RelativeContrastMask {
public static BooleanMatrix compute(DoubleMatrix contrast, BlockMap blocks) {
List<Double> sortedContrast = new ArrayList<>();
for (IntPoint block : contrast.size())
sortedContrast.add(contrast.get(block));
sortedContrast.sort(Comparator.<Double>naturalOrder().reversed());
int pixelsPerBlock = blocks.pixels.area() / blocks.primary.blocks.area();
int sampleCount = Math.min(sortedContrast.size(), Parameters.RELATIVE_CONTRAST_SAMPLE / pixelsPerBlock);
int consideredBlocks = Math.max((int)Math.round(sampleCount * Parameters.RELATIVE_CONTRAST_PERCENTILE), 1);
double averageContrast = sortedContrast.stream().mapToDouble(n -> n).limit(consideredBlocks).average().getAsDouble();
double limit = averageContrast * Parameters.MIN_RELATIVE_CONTRAST;
BooleanMatrix result = new BooleanMatrix(blocks.primary.blocks);
for (IntPoint block : blocks.primary.blocks)
if (contrast.get(block) < limit)
result.set(block, true);
// https://sourceafis.machinezoo.com/transparency/relative-contrast-mask
TransparencySink.current().log("relative-contrast-mask", result);
return result;
}
}
| apache-2.0 |
googleapis/java-aiplatform | proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/CompleteTrialRequestOrBuilder.java | 4218 | /*
* Copyright 2020 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/vizier_service.proto
package com.google.cloud.aiplatform.v1;
public interface CompleteTrialRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1.CompleteTrialRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The Trial's name.
* Format:
* `projects/{project}/locations/{location}/studies/{study}/trials/{trial}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
java.lang.String getName();
/**
*
*
* <pre>
* Required. The Trial's name.
* Format:
* `projects/{project}/locations/{location}/studies/{study}/trials/{trial}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
com.google.protobuf.ByteString getNameBytes();
/**
*
*
* <pre>
* Optional. If provided, it will be used as the completed Trial's
* final_measurement; Otherwise, the service will auto-select a
* previously reported measurement as the final-measurement
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.Measurement final_measurement = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the finalMeasurement field is set.
*/
boolean hasFinalMeasurement();
/**
*
*
* <pre>
* Optional. If provided, it will be used as the completed Trial's
* final_measurement; Otherwise, the service will auto-select a
* previously reported measurement as the final-measurement
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.Measurement final_measurement = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The finalMeasurement.
*/
com.google.cloud.aiplatform.v1.Measurement getFinalMeasurement();
/**
*
*
* <pre>
* Optional. If provided, it will be used as the completed Trial's
* final_measurement; Otherwise, the service will auto-select a
* previously reported measurement as the final-measurement
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.Measurement final_measurement = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
com.google.cloud.aiplatform.v1.MeasurementOrBuilder getFinalMeasurementOrBuilder();
/**
*
*
* <pre>
* Optional. True if the Trial cannot be run with the given Parameter, and
* final_measurement will be ignored.
* </pre>
*
* <code>bool trial_infeasible = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The trialInfeasible.
*/
boolean getTrialInfeasible();
/**
*
*
* <pre>
* Optional. A human readable reason why the trial was infeasible. This should
* only be provided if `trial_infeasible` is true.
* </pre>
*
* <code>string infeasible_reason = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The infeasibleReason.
*/
java.lang.String getInfeasibleReason();
/**
*
*
* <pre>
* Optional. A human readable reason why the trial was infeasible. This should
* only be provided if `trial_infeasible` is true.
* </pre>
*
* <code>string infeasible_reason = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for infeasibleReason.
*/
com.google.protobuf.ByteString getInfeasibleReasonBytes();
}
| apache-2.0 |
HaStr/kieker | kieker-tools/src/kieker/tools/traceAnalysis/filter/flow/TraceEventRecords2ExecutionAndMessageTraceFilter.java | 25435 | /***************************************************************************
* Copyright 2015 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.tools.traceAnalysis.filter.flow;
import java.util.Stack;
import kieker.analysis.IProjectContext;
import kieker.analysis.analysisComponent.AbstractAnalysisComponent;
import kieker.analysis.plugin.annotation.InputPort;
import kieker.analysis.plugin.annotation.OutputPort;
import kieker.analysis.plugin.annotation.Plugin;
import kieker.analysis.plugin.annotation.Property;
import kieker.analysis.plugin.annotation.RepositoryPort;
import kieker.analysis.plugin.filter.flow.TraceEventRecords;
import kieker.common.configuration.Configuration;
import kieker.common.logging.Log;
import kieker.common.record.flow.trace.AbstractTraceEvent;
import kieker.common.record.flow.trace.TraceMetadata;
import kieker.common.record.flow.trace.concurrency.SplitEvent;
import kieker.common.record.flow.trace.operation.AbstractOperationEvent;
import kieker.common.record.flow.trace.operation.AfterOperationEvent;
import kieker.common.record.flow.trace.operation.AfterOperationFailedEvent;
import kieker.common.record.flow.trace.operation.BeforeOperationEvent;
import kieker.common.record.flow.trace.operation.CallOperationEvent;
import kieker.common.record.flow.trace.operation.constructor.AfterConstructorEvent;
import kieker.common.record.flow.trace.operation.constructor.AfterConstructorFailedEvent;
import kieker.common.record.flow.trace.operation.constructor.BeforeConstructorEvent;
import kieker.common.record.flow.trace.operation.constructor.CallConstructorEvent;
import kieker.common.util.signature.ClassOperationSignaturePair;
import kieker.common.util.signature.Signature;
import kieker.tools.traceAnalysis.filter.AbstractTraceAnalysisFilter;
import kieker.tools.traceAnalysis.filter.AbstractTraceProcessingFilter;
import kieker.tools.traceAnalysis.filter.traceReconstruction.InvalidTraceException;
import kieker.tools.traceAnalysis.systemModel.Execution;
import kieker.tools.traceAnalysis.systemModel.ExecutionTrace;
import kieker.tools.traceAnalysis.systemModel.InvalidExecutionTrace;
import kieker.tools.traceAnalysis.systemModel.MessageTrace;
import kieker.tools.traceAnalysis.systemModel.repository.SystemModelRepository;
/**
* @author Andre van Hoorn, Holger Knoche, Jan Waller
*
* @since 1.6
*/
@Plugin(description = "Transforms incoming TraceEventRecords into execution and message traces",
outputPorts = {
@OutputPort(name = TraceEventRecords2ExecutionAndMessageTraceFilter.OUTPUT_PORT_NAME_EXECUTION_TRACE,
description = "Outputs transformed execution traces", eventTypes = { ExecutionTrace.class }),
@OutputPort(name = TraceEventRecords2ExecutionAndMessageTraceFilter.OUTPUT_PORT_NAME_MESSAGE_TRACE,
description = "Outputs transformed message traces", eventTypes = { MessageTrace.class }),
@OutputPort(name = TraceEventRecords2ExecutionAndMessageTraceFilter.OUTPUT_PORT_NAME_INVALID_EXECUTION_TRACE,
description = "Invalid Execution Traces", eventTypes = { InvalidExecutionTrace.class }) },
repositoryPorts = {
@RepositoryPort(name = AbstractTraceAnalysisFilter.REPOSITORY_PORT_NAME_SYSTEM_MODEL, repositoryType = SystemModelRepository.class)
},
configuration = {
@Property(name = TraceEventRecords2ExecutionAndMessageTraceFilter.CONFIG_ENHANCE_JAVA_CONSTRUCTORS, defaultValue = "true"),
@Property(name = TraceEventRecords2ExecutionAndMessageTraceFilter.CONFIG_ENHANCE_CALL_DETECTION, defaultValue = "true"),
@Property(name = TraceEventRecords2ExecutionAndMessageTraceFilter.CONFIG_IGNORE_ASSUMED, defaultValue = "false")
})
public class TraceEventRecords2ExecutionAndMessageTraceFilter extends AbstractTraceProcessingFilter {
/** This is the name of the input port receiving new trace events. */
public static final String INPUT_PORT_NAME_EVENT_TRACE = "traceEvents";
/** This is the name of the output port delivering the execution traces. */
public static final String OUTPUT_PORT_NAME_EXECUTION_TRACE = "executionTrace";
/** This is the name of the output port delivering the message traces. */
public static final String OUTPUT_PORT_NAME_MESSAGE_TRACE = "messageTrace";
/** This is the name of the output port delivering invalid traces. */
public static final String OUTPUT_PORT_NAME_INVALID_EXECUTION_TRACE = "invalidTrace";
public static final String CONFIG_IGNORE_ASSUMED = "ignoreAssumed";
public static final String CONFIG_ENHANCE_JAVA_CONSTRUCTORS = "enhanceJavaConstructors";
public static final String CONFIG_ENHANCE_CALL_DETECTION = "enhanceCallDetection";
private final boolean enhanceJavaConstructors;
private final boolean enhanceCallDetection;
private final boolean ignoreAssumedCalls;
/**
* Creates a new instance of this class using the given parameters.
*
* @param configuration
* The configuration for this component.
* @param projectContext
* The project context for this component.
*/
public TraceEventRecords2ExecutionAndMessageTraceFilter(final Configuration configuration, final IProjectContext projectContext) {
super(configuration, projectContext);
this.enhanceJavaConstructors = configuration.getBooleanProperty(CONFIG_ENHANCE_JAVA_CONSTRUCTORS);
this.enhanceCallDetection = configuration.getBooleanProperty(CONFIG_ENHANCE_CALL_DETECTION);
this.ignoreAssumedCalls = configuration.getBooleanProperty(CONFIG_IGNORE_ASSUMED);
}
/**
* {@inheritDoc}
*/
@Override
public Configuration getCurrentConfiguration() {
final Configuration configuration = super.getCurrentConfiguration();
configuration.setProperty(CONFIG_ENHANCE_JAVA_CONSTRUCTORS, String.valueOf(this.enhanceJavaConstructors));
configuration.setProperty(CONFIG_ENHANCE_CALL_DETECTION, String.valueOf(this.enhanceCallDetection));
configuration.setProperty(CONFIG_IGNORE_ASSUMED, String.valueOf(this.ignoreAssumedCalls));
return configuration;
}
/**
* This method represents the input port, processing incoming trace event records.
*
* @param traceEventRecords
* The next trace event record.
*/
@InputPort(name = INPUT_PORT_NAME_EVENT_TRACE, description = "Receives TraceEvents to be transformed", eventTypes = { TraceEventRecords.class })
public void inputTraceEvents(final TraceEventRecords traceEventRecords) {
final TraceMetadata trace = traceEventRecords.getTraceMetadata();
if (trace == null) {
this.log.error("Trace is missing from TraceEvents");
return;
}
final long traceId = trace.getTraceId();
final ExecutionTrace executionTrace = new ExecutionTrace(traceId, trace.getSessionId());
final TraceEventRecordHandler traceEventRecordHandler = new TraceEventRecordHandler(trace, executionTrace, this.getSystemEntityFactory(),
this.enhanceJavaConstructors, this.enhanceCallDetection, this.ignoreAssumedCalls);
int expectedOrderIndex = -1;
for (final AbstractTraceEvent event : traceEventRecords.getTraceEvents()) {
expectedOrderIndex += 1; // increment in each iteration -> 0 is the first real value
if (event.getOrderIndex() != expectedOrderIndex) {
this.log.error("Found event with wrong orderIndex. Found: " + event.getOrderIndex() + " expected: " + (expectedOrderIndex - 1));
continue; // simply ignore wrong event
}
if (event.getTraceId() != traceId) {
this.log.error("Found event with wrong traceId. Found: " + event.getTraceId() + " expected: " + traceId);
continue; // simply ignore wrong event
}
try { // handle all cases (more specific classes should be handled before less specific ones)
// Before Events
if (BeforeConstructorEvent.class.isAssignableFrom(event.getClass())) {
traceEventRecordHandler.handleBeforeConstructorEvent((BeforeConstructorEvent) event);
} else if (BeforeOperationEvent.class.isAssignableFrom(event.getClass())) {
traceEventRecordHandler.handleBeforeOperationEvent((BeforeOperationEvent) event);
// After Events
} else if (AfterConstructorFailedEvent.class.isAssignableFrom(event.getClass())) {
traceEventRecordHandler.handleAfterConstructorFailedEvent((AfterConstructorFailedEvent) event);
} else if (AfterOperationFailedEvent.class.isAssignableFrom(event.getClass())) {
traceEventRecordHandler.handleAfterOperationFailedEvent((AfterOperationFailedEvent) event);
} else if (AfterConstructorEvent.class.isAssignableFrom(event.getClass())) {
traceEventRecordHandler.handleAfterConstructorEvent((AfterConstructorEvent) event);
} else if (AfterOperationEvent.class.isAssignableFrom(event.getClass())) {
traceEventRecordHandler.handleAfterOperationEvent((AfterOperationEvent) event);
// CallOperation Events
} else if (CallConstructorEvent.class.isAssignableFrom(event.getClass())) {
traceEventRecordHandler.handleCallConstructorEvent((CallConstructorEvent) event);
} else if (CallOperationEvent.class.isAssignableFrom(event.getClass())) {
traceEventRecordHandler.handleCallOperationEvent((CallOperationEvent) event);
// SplitEvent
} else if (SplitEvent.class.isAssignableFrom(event.getClass())) {
this.log.warn("Events of type 'SplitEvent' are currently not handled and ignored.");
} else {
this.log.warn("Events of type '" + event.getClass().getName() + "' are currently not handled and ignored.");
}
} catch (final InvalidTraceException ex) {
this.log.error("Failed to reconstruct trace.", ex);
super.deliver(OUTPUT_PORT_NAME_INVALID_EXECUTION_TRACE, new InvalidExecutionTrace(executionTrace));
return;
}
}
try {
traceEventRecordHandler.finish();
final MessageTrace messageTrace = executionTrace.toMessageTrace(SystemModelRepository.ROOT_EXECUTION);
super.deliver(OUTPUT_PORT_NAME_EXECUTION_TRACE, executionTrace);
super.deliver(OUTPUT_PORT_NAME_MESSAGE_TRACE, messageTrace);
super.reportSuccess(executionTrace.getTraceId());
} catch (final InvalidTraceException ex) {
this.log.warn("Failed to convert to message trace: " + ex.getMessage()); // do not pass 'ex' to log.warn because this makes the output verbose (#584)
super.deliver(OUTPUT_PORT_NAME_INVALID_EXECUTION_TRACE, new InvalidExecutionTrace(executionTrace));
}
}
protected static Log getLOG() {
return AbstractAnalysisComponent.LOG;
}
/**
* This class encapsulates the trace's state, that is, the current event and execution stacks.
*
* @author Andre van Hoorn, Holger Knoche, Jan Waller
*/
private static class TraceEventRecordHandler {
private final SystemModelRepository systemModelRepository;
private final TraceMetadata trace;
private final ExecutionTrace executionTrace;
private final Stack<AbstractTraceEvent> eventStack = new Stack<AbstractTraceEvent>();
private final Stack<ExecutionInformation> executionStack = new Stack<ExecutionInformation>();
private final boolean enhanceJavaConstructors;
private final boolean enhanceCallDetection;
private int orderindex;
private final boolean ignoreAssumedCalls;
public TraceEventRecordHandler(final TraceMetadata trace, final ExecutionTrace executionTrace, final SystemModelRepository systemModelRepository,
final boolean enhanceJavaConstructors, final boolean enhanceCallDetection, final boolean ignoreAssumedCalls) {
this.trace = trace;
this.executionTrace = executionTrace;
this.systemModelRepository = systemModelRepository;
this.enhanceJavaConstructors = enhanceJavaConstructors;
this.enhanceCallDetection = enhanceCallDetection;
this.ignoreAssumedCalls = ignoreAssumedCalls;
}
/**
* Finished the current execution. All open executions are finished and correctly added (if possible).
*
* @throws InvalidTraceException
*/
public void finish() throws InvalidTraceException {
final Stack<AbstractTraceEvent> tmpEventStack = new Stack<AbstractTraceEvent>();
final Stack<ExecutionInformation> tmpExecutionStack = new Stack<ExecutionInformation>();
if (!this.eventStack.isEmpty()) {
final long lastTimeStamp = this.eventStack.peek().getTimestamp();
while (!this.eventStack.isEmpty()) { // reverse order
tmpEventStack.push(this.eventStack.pop());
tmpExecutionStack.push(this.executionStack.pop());
}
while (!tmpEventStack.isEmpty()) { // create executions (in reverse order)
final AbstractTraceEvent currentEvent = tmpEventStack.pop();
final ExecutionInformation executionInformation = tmpExecutionStack.pop();
if (currentEvent instanceof CallOperationEvent) {
this.finishExecution(
((CallOperationEvent) currentEvent).getCalleeOperationSignature(),
((CallOperationEvent) currentEvent).getCalleeClassSignature(),
this.trace.getTraceId(),
this.trace.getSessionId(),
this.trace.getHostname(),
executionInformation.getEoi(),
executionInformation.getEss(),
currentEvent.getTimestamp(),
lastTimeStamp,
!this.ignoreAssumedCalls, currentEvent instanceof CallConstructorEvent);
} else {
throw new InvalidTraceException("Only CallOperationEvents are expected to be remaining, but found: "
+ currentEvent.getClass().getSimpleName());
}
}
}
}
/**
* This method delivers the object on top of the stack without removing it, if it exists and null otherwise.
*
* @return The object on top if it exists or null otherwise.
*/
private AbstractTraceEvent peekEvent() {
if (this.eventStack.isEmpty()) {
return null;
}
return this.eventStack.peek();
}
private void registerExecution(final AbstractTraceEvent cause) {
this.eventStack.push(cause);
final ExecutionInformation executionInformation = new ExecutionInformation(this.orderindex++, this.executionStack.size());
this.executionStack.push(executionInformation);
}
private void finishExecution(final String operationSignature, final String classSignature, final long traceId, final String sessionId,
final String hostname, final int eoi, final int ess, final long tin, final long tout, final boolean assumed, final boolean constructor) throws
InvalidTraceException {
final ClassOperationSignaturePair fqComponentNameSignaturePair = ClassOperationSignaturePair.splitOperationSignatureStr(operationSignature,
constructor && this.enhanceJavaConstructors);
final String executionContext;
if (classSignature.length() == 0) {
executionContext = fqComponentNameSignaturePair.getFqClassname();
} else {
executionContext = classSignature;
}
final Execution execution = AbstractTraceAnalysisFilter.createExecutionByEntityNames(this.systemModelRepository,
hostname,
executionContext,
fqComponentNameSignaturePair.getFqClassname(), fqComponentNameSignaturePair.getSignature(),
traceId, sessionId, eoi, ess,
tin, tout, assumed);
try {
this.executionTrace.add(execution);
} catch (final InvalidTraceException ex) {
throw new InvalidTraceException("Failed to add execution " + execution + " to trace " + this.executionTrace + ".", ex);
}
}
/**
* Removes all remaining call events from the top of the event stack. For each removed call statement, an assumed
* execution is generated using the timestamp of the last recursive operation event.
*
* @param lastEvent
* The last processed operation event
* @throws InvalidTraceException
*/
private void closeOpenCalls(final AbstractOperationEvent lastEvent) throws InvalidTraceException {
final Stack<CallOperationEvent> tmpEventStack = new Stack<CallOperationEvent>();
final Stack<ExecutionInformation> tmpExecutionStack = new Stack<ExecutionInformation>();
while (true) {
if (this.eventStack.isEmpty()) {
break; // we are done
}
final AbstractTraceEvent prevEvent = this.eventStack.peek();
if (!(prevEvent instanceof CallOperationEvent)) {
break; // we are done
}
tmpEventStack.push((CallOperationEvent) this.eventStack.pop());
tmpExecutionStack.push(this.executionStack.pop());
if (lastEvent.getOperationSignature().equals(((CallOperationEvent) prevEvent).getOperationSignature())) {
while (!tmpEventStack.isEmpty()) { // create executions (in reverse order)
final CallOperationEvent currentCallEvent = tmpEventStack.pop();
final ExecutionInformation executionInformation = tmpExecutionStack.pop();
this.finishExecution(
currentCallEvent.getCalleeOperationSignature(),
currentCallEvent.getCalleeClassSignature(),
this.trace.getTraceId(),
this.trace.getSessionId(),
this.trace.getHostname(),
executionInformation.getEoi(),
executionInformation.getEss(),
currentCallEvent.getTimestamp(),
lastEvent.getTimestamp(),
!this.ignoreAssumedCalls,
currentCallEvent instanceof CallConstructorEvent);
}
return;
}
}
while (!tmpEventStack.isEmpty()) {
this.eventStack.push(tmpEventStack.pop());
this.executionStack.push(tmpExecutionStack.pop());
}
}
private void handleBeforeEvent(final BeforeOperationEvent beforeOperationEvent,
final Class<? extends CallOperationEvent> callClass) throws InvalidTraceException {
final AbstractTraceEvent prevEvent = this.peekEvent();
if (this.isPrevEventMatchingCall(beforeOperationEvent, prevEvent, callClass)) {
this.eventStack.push(beforeOperationEvent);
} else {
this.closeOpenCalls(beforeOperationEvent);
this.registerExecution(beforeOperationEvent);
}
}
public void handleBeforeOperationEvent(final BeforeOperationEvent beforeOperationEvent) throws InvalidTraceException {
this.handleBeforeEvent(beforeOperationEvent, CallOperationEvent.class);
}
public void handleBeforeConstructorEvent(final BeforeConstructorEvent beforeConstructorEvent) throws InvalidTraceException {
this.handleBeforeEvent(beforeConstructorEvent, CallConstructorEvent.class);
}
private boolean isPrevEventMatchingCall(final BeforeOperationEvent beforeOperationEvent, final AbstractTraceEvent prevEvent,
final Class<? extends CallOperationEvent> callClass) {
if ((prevEvent != null) && callClass.isAssignableFrom(prevEvent.getClass())
&& (prevEvent.getOrderIndex() == (beforeOperationEvent.getOrderIndex() - 1))) {
if (this.callsReferencedOperationOf((CallOperationEvent) prevEvent, beforeOperationEvent)) {
return true;
} else if (this.enhanceCallDetection) { // perhaps we don't find a perfect match, but can guess one!
final boolean isConstructor = beforeOperationEvent instanceof BeforeConstructorEvent;
final CallOperationEvent callEvent = (CallOperationEvent) prevEvent;
final Signature callSignature = ClassOperationSignaturePair.splitOperationSignatureStr(callEvent.getCalleeOperationSignature(),
isConstructor && this.enhanceJavaConstructors).getSignature();
final Signature afterSignature = ClassOperationSignaturePair.splitOperationSignatureStr(beforeOperationEvent.getOperationSignature(),
isConstructor && this.enhanceJavaConstructors).getSignature();
if (callSignature.equals(afterSignature)
&& callEvent.getCalleeClassSignature().equals(beforeOperationEvent.getClassSignature())) {
if (TraceEventRecords2ExecutionAndMessageTraceFilter.getLOG().isDebugEnabled()) {
TraceEventRecords2ExecutionAndMessageTraceFilter.getLOG().debug("Guessed call of \n\t" + callEvent + "\n\t" + beforeOperationEvent);
}
return true;
}
}
}
return false;
}
/**
* Check if a previous event callee is the present operation.
*/
private boolean callsReferencedOperationOf(final CallOperationEvent prevEvent, final BeforeOperationEvent presentEvent) {
return prevEvent.getCalleeOperationSignature().equals(presentEvent.getOperationSignature())
&& prevEvent.getCalleeClassSignature().equals(presentEvent.getClassSignature());
}
private void handleAfterEvent(final AfterOperationEvent afterOperationEvent,
final Class<? extends BeforeOperationEvent> beforeClass,
final Class<? extends CallOperationEvent> callClass) throws InvalidTraceException {
this.closeOpenCalls(afterOperationEvent);
// Obtain the matching before-operation event from the stack
final AbstractTraceEvent potentialBeforeEvent = this.peekEvent();
// The element at the top of the stack needs to be a before-operation event...
if ((potentialBeforeEvent == null) || !beforeClass.isAssignableFrom(potentialBeforeEvent.getClass())) {
throw new InvalidTraceException("Didn't find corresponding "
+ beforeClass.getName() + " for " + afterOperationEvent.getClass().getName() + " "
+ afterOperationEvent.toString() + " (found: " + potentialBeforeEvent + ").");
}
// ... and must reference the same operation as the given after-operation event.
if (!this.refersToSameOperationAs(afterOperationEvent, (BeforeOperationEvent) potentialBeforeEvent)) {
throw new InvalidTraceException("Components of before (" + potentialBeforeEvent + ") " + "and after (" + afterOperationEvent
+ ") events do not match.");
}
final BeforeOperationEvent beforeOperationEvent = (BeforeOperationEvent) this.eventStack.pop();
// Look for a call event at the top of the stack
final AbstractTraceEvent prevEvent = this.peekEvent();
// A definite call occurs if either the stack is empty (entry into the trace) or if a matching call event is found
final boolean definiteCall = (prevEvent == null) || this.isPrevEventMatchingCall(beforeOperationEvent, prevEvent, callClass);
// If a matching call event was found, it must be removed from the stack
if (definiteCall && !this.eventStack.isEmpty()) {
this.eventStack.pop();
}
final ExecutionInformation executionInformation = this.executionStack.pop();
this.finishExecution(
beforeOperationEvent.getOperationSignature(),
beforeOperationEvent.getClassSignature(),
this.trace.getTraceId(),
this.trace.getSessionId(),
this.trace.getHostname(),
executionInformation.getEoi(),
executionInformation.getEss(),
beforeOperationEvent.getTimestamp(),
afterOperationEvent.getTimestamp(),
!(definiteCall || this.ignoreAssumedCalls),
beforeOperationEvent instanceof BeforeConstructorEvent);
}
private boolean refersToSameOperationAs(final AfterOperationEvent afterOperationEvent, final BeforeOperationEvent potentialBeforeEvent) {
return afterOperationEvent.getOperationSignature().equals(potentialBeforeEvent.getOperationSignature())
&& afterOperationEvent.getClassSignature().equals(potentialBeforeEvent.getClassSignature());
}
public void handleAfterOperationEvent(final AfterOperationEvent afterOperationEvent) throws InvalidTraceException {
this.handleAfterEvent(afterOperationEvent, BeforeOperationEvent.class, CallOperationEvent.class);
}
public void handleAfterOperationFailedEvent(final AfterOperationFailedEvent afterOperationEvent) throws InvalidTraceException {
this.handleAfterEvent(afterOperationEvent, BeforeOperationEvent.class, CallOperationEvent.class);
}
public void handleAfterConstructorEvent(final AfterConstructorEvent afterConstructorEvent) throws InvalidTraceException {
this.handleAfterEvent(afterConstructorEvent, BeforeConstructorEvent.class, CallConstructorEvent.class);
}
public void handleAfterConstructorFailedEvent(final AfterConstructorFailedEvent afterConstructorEvent) throws InvalidTraceException {
this.handleAfterEvent(afterConstructorEvent, BeforeConstructorEvent.class, CallConstructorEvent.class);
}
public void handleCallOperationEvent(final CallOperationEvent callOperationEvent) throws InvalidTraceException {
this.closeOpenCalls(callOperationEvent);
this.registerExecution(callOperationEvent);
}
public void handleCallConstructorEvent(final CallConstructorEvent callConstructorEvent) throws InvalidTraceException {
this.handleCallOperationEvent(callConstructorEvent);
}
/**
* This class stores information about a specific execution.
*/
private static class ExecutionInformation {
private final int eoi;
private final int ess;
/**
* Creates a new instance of this class using the given parameters.
*
* @param executionIndex
* The execution order index.
* @param stackDepth
* The execution stack size.
*/
public ExecutionInformation(final int executionIndex, final int stackDepth) {
this.eoi = executionIndex;
this.ess = stackDepth;
}
/**
* Returns the execution's execution order index.
*
* @return See above
*/
public int getEoi() {
return this.eoi;
}
/**
* Returns the stack depth at which the execution occurred.
*
* @return See above
*/
public int getEss() {
return this.ess;
}
}
}
}
| apache-2.0 |
BrianChangchien/FiWoRDC | client/Android/Studio/freeRDPCore/src/main/java/com/freerdp/freerdpcore/presentation/FiwoServerSetting.java | 21294 | package com.freerdp.freerdpcore.presentation;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.freerdp.freerdpcore.R;
import com.freerdp.freerdpcore.utils.GlobelSetting;
import com.freerdp.freerdpcore.utils.appdefine;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.XML;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class FiwoServerSetting extends Dialog implements
android.view.View.OnClickListener {
private Button btnCheckConnect, btnFinish;
private EditText editFiwoServerAddr;
private String sFiwoServerAddr;
private Boolean bConnected;
private ProgressDialog pDialog;
private Boolean bHandshakeResponse=Boolean.FALSE;
private Timer mTimer = null;
private TimerTask mTimerTask = null;
private static int count = 0;
private boolean isPause = false;
private boolean isStop = true;
private static int delay = 15000; //1s
private static int period = 15000; //1s
public Activity context;
private static MyHandler mHandler ;
private OnMyDialogResult mDialogResult; // the callback
private DownloadManager mDownloadManager;
private long enqueueId;
private BroadcastReceiver mBroadcastReceiver;
private String sFiWoUpgradePath, sFiWoUpgradeName="", sFiWoAppVersion="";
public FiwoServerSetting(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.context = a;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fiwo_server_setting);
if(mHandler == null)
mHandler = new MyHandler();
process_ui();
/*
try {
process_app_update();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
*/
}
protected void onResume()
{
if(mHandler == null)
mHandler = new MyHandler();
}
protected void onPause()
{
if(mHandler != null)
{
mHandler.removeCallbacksAndMessages(null);
mHandler = null;
}
System.gc();
}
protected void onDestory(){
if(mHandler != null)
{
mHandler.removeCallbacksAndMessages(null);
mHandler = null;
}
System.gc();
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btnFiwoServerCheckConnect) {
process_press_checkconnect();
}else if (id == R.id.btnFiwoServerFinish) {
process_press_finish();
}
}
public void resetUIStatus(){
ImageView imgStatus = (ImageView) findViewById(R.id.ImgViewFiwoServerConnectStatus);
imgStatus.setVisibility(View.INVISIBLE);
editFiwoServerAddr.setError(null);
btnFinish.setBackgroundResource(R.drawable.btn_bg_grey);
btnFinish.setEnabled(false);
bHandshakeResponse = Boolean.FALSE;
}
public void processEnterKeyEvent(){
if (Boolean.TRUE.equals(bHandshakeResponse))
process_press_finish();
else
process_press_checkconnect();
}
public void setDialogResult(OnMyDialogResult dialogResult){
mDialogResult = dialogResult;
}
private void process_ui() {
SharedPreferences userDetails = context.getSharedPreferences("FiWoServer", Context.MODE_PRIVATE);
String FiwoIP = userDetails.getString("ip", "");
TextView tvTitle = (TextView) findViewById(R.id.textFiWoAddress);
tvTitle.setText(R.string.network_server_address);
TextView tvexample = (TextView) findViewById(R.id.textFiWoAddressExample);
tvexample.setText(R.string.example_network);
btnCheckConnect = (Button) findViewById(R.id.btnFiwoServerCheckConnect);
btnCheckConnect.setText(R.string.network_check_connection);
btnFinish = (Button) findViewById(R.id.btnFiwoServerFinish);
btnFinish.setText(R.string.network_Finish);
btnCheckConnect.setOnClickListener(this);
btnFinish.setOnClickListener(this);
btnFinish.setEnabled(false);
editFiwoServerAddr = (EditText) findViewById(R.id.editFIWOaddress);
editFiwoServerAddr.setText(FiwoIP);
//editFiwoServerAddr.setText("10.67.54.15");
/*
editFiwoServerAddr.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
if (Boolean.TRUE.equals(bHandshakeResponse)) {
process_press_finish();
return true;
}else {
process_press_checkconnect();
return true;
}
}
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) {
// Perform action on key press
if (Boolean.TRUE.equals(bHandshakeResponse)) {
process_press_finish();
return true;
}else {
process_press_checkconnect();
return true;
}
}
return false;
}
});
*/
bConnected=false;
// sFiwoServerAddr = editFiwoServerAddr.getText().toString();
}
private void process_press_checkconnect() {
sFiwoServerAddr = editFiwoServerAddr.getText().toString();
if (sFiwoServerAddr.equals("")) {
editFiwoServerAddr.setError(getContext().getString(R.string.network_server_address_message));
return;
}
bHandshakeResponse = Boolean.FALSE;
startTimer();
show_process_dialog(getContext().getString(R.string.loading), false);
Thread thread = new Thread(ThreadHandshake);
thread.start();
}
private void process_press_finish() {
show_process_dialog(getContext().getString(R.string.loading), false);
stopTimer();
Thread thread = new Thread(ThreadDomain);
thread.start();
}
public void downloadNewVersion() {
mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
String sAPKDownloadPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS) + "/" + sFiWoUpgradeName;
File f = new File(sAPKDownloadPath);
Boolean deleted = f.delete();
// apkDownloadUrl 是 apk 的下载地址
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(sFiWoUpgradePath+sFiWoUpgradeName));
request.setDestinationInExternalPublicDir(android.os.Environment.DIRECTORY_DOWNLOADS, sFiWoUpgradeName);
// 获取下载队列 id
enqueueId = mDownloadManager.enqueue(request);
}
private void promptInstall(Uri data) {
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(data, "application/vnd.android.package-archive");
// FLAG_ACTIVITY_NEW_TASK 可以保证安装成功时可以正常打开 app
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(promptInstall);
}
private Runnable ThreadHandshake = new Runnable() {
public void run() {
// 運行網路連線的程式
sendHttpGetHandShake();
}
};
private Runnable ThreadDomain = new Runnable() {
public void run() {
// 運行網路連線的程式
String r = sendHttpGetDomain();
if(mHandler != null)
{
Message msg1 = new Message();
msg1.what = appdefine.MSG_GET_DOMAIN;
mHandler.sendMessage(msg1);
}
mDialogResult.finish(sFiwoServerAddr,r);
}
};
private String sendHttpGetHandShake() {
String strUrl = "http://";
strUrl += sFiwoServerAddr;
strUrl += ":";
strUrl += GlobelSetting.sServicePort;
strUrl += "/FiWo/Interface/rest/deskpool/app";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(strUrl);
HttpResponse response ;
String result = "";
JSONObject soapDatainJsonObject = null;
String sCurrentVersionName = null;
try {
PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
sCurrentVersionName = pinfo.versionName;
}
catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
int status_code = 0;
try {
response = client.execute(request);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
status_code = response.getStatusLine().getStatusCode();
}
if (status_code == 200) {
bHandshakeResponse = Boolean.TRUE;
soapDatainJsonObject = XML.toJSONObject(result);
JSONObject jsonAPPInfo = soapDatainJsonObject.getJSONObject("deskpoolApp");
sFiWoUpgradePath = jsonAPPInfo.getString("baseUrl");
if (jsonAPPInfo.has("androidName"))
sFiWoUpgradeName = jsonAPPInfo.getString("androidName");
if (jsonAPPInfo.has("androidVersion"))
sFiWoAppVersion = jsonAPPInfo.getString("androidVersion");
if(mHandler != null)
{
Message msg1 = new Message();
boolean bUpdrade = false;
/*
if (sFiWoAppVersion.equals("") || sFiWoUpgradeName.equals(""))
bUpdrade = false;
else
bUpdrade = GlobelSetting.compareVersionNames(sCurrentVersionName, sFiWoAppVersion);
*/
if (bUpdrade)
msg1.what = appdefine.MSG_NEED_UPGRADE;
else
msg1.what = appdefine.MSG_SHOW_CONNECTING;
mHandler.sendMessage(msg1);
}
}
else
{
if(mHandler != null) {
Message msg1 = new Message();
msg1.what = appdefine.MSG_CONNECTION_FAIL;
mHandler.sendMessage(msg1);
}
}
Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
result = Integer.toString(status_code);
return result;
}
private String sendHttpGetDomain() {
String strUrl = "http://";
strUrl += sFiwoServerAddr;
strUrl += ":";
strUrl += GlobelSetting.sServicePort;
strUrl += "/FiWo/Interface/rest/deskpool/domain";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(strUrl);
HttpResponse response ;
JSONObject soapDatainJsonObject = null;
String result = "";
try {
response = client.execute(request);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
soapDatainJsonObject = XML.toJSONObject(result);
}
Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return soapDatainJsonObject.toString();
}
public void show_process_dialog(String sMessage, boolean b_can_cancel)
{
if(pDialog != null && pDialog.isShowing())
return;
if(pDialog == null)
{
pDialog = new ProgressDialog(this.getContext());
pDialog.setTitle("");
pDialog.setMessage(sMessage);
}
pDialog.setCancelable(b_can_cancel);
pDialog.show();
}
private void cancel_progressdialog()
{
if(pDialog != null)
{
pDialog.dismiss();
pDialog = null;
}
}
private void startTimer(){
if (mTimer == null) {
mTimer = new Timer();
}
if (mTimerTask == null) {
mTimerTask = new TimerTask() {
@Override
public void run() {
if (bHandshakeResponse) {
if(mHandler != null)
{
Message msg1 = new Message();
msg1.what = appdefine.MSG_CONNECT_RESPONSE;
mHandler.sendMessage(msg1);
}
}
else{
if(mHandler != null)
{
Message msg1 = new Message();
msg1.what = appdefine.MSG_CONNECT_NON_RESPONSE;
mHandler.sendMessage(msg1);
}
}
count++;
}
};
}
if(mTimer != null && mTimerTask != null )
mTimer.schedule(mTimerTask, delay, period);
}
private void stopTimer() {
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
if (mTimerTask != null) {
mTimerTask.cancel();
mTimerTask = null;
}
count = 0;
}
// -----------------------------------------------------------
private class MyHandler extends Handler
{
public void handleMessage( Message msg)
{
switch( msg.what)
{
case appdefine.MSG_SHOW_CONNECTING: {
SharedPreferences keyValues = context.getSharedPreferences(("FiWoServer"), Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();
keyValuesEditor.clear();
keyValuesEditor.putString("ip", sFiwoServerAddr);
keyValuesEditor.commit();
ImageView imgStatus = (ImageView) findViewById(R.id.ImgViewFiwoServerConnectStatus);
imgStatus.setImageResource(R.drawable.icon_connect);
imgStatus.setVisibility(View.VISIBLE);
btnFinish.setBackgroundResource(R.drawable.btn_bg_green);
btnFinish.setEnabled(true);
stopTimer();
cancel_progressdialog();
}
break;
case appdefine.MSG_NEED_UPGRADE:{
stopTimer();
cancel_progressdialog();
AlertDialog.Builder b = new AlertDialog.Builder(context);
b.setIcon(R.drawable.ic_dialog_alert_holo_light);
b.setTitle(getContext().getString(R.string.network_update));
b.setMessage(getContext().getString(R.string.network_version_update));
b.setNegativeButton(getContext().getString(R.string.ok) , new DialogInterface.OnClickListener()
{
@Override
public void onClick( DialogInterface arg0, int arg1)
{
downloadNewVersion();
show_process_dialog(getContext().getString(R.string.network_downloading), false);
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
cancel_progressdialog();
long downloadCompletedId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
// 检查是否是自己的下载队列 id, 有可能是其他应用的
if (enqueueId != downloadCompletedId) {
return;
}
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueueId);
Cursor c = mDownloadManager.query(query);
if (c.moveToFirst()) {
context.unregisterReceiver(mBroadcastReceiver);
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
// 下载失败也会返回这个广播,所以要判断下是否真的下载成功
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
// 获取下载好的 apk 路径
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
// 提示用户安装
promptInstall(Uri.parse("file://" + uriString));
}
}
}
};
context.registerReceiver(mBroadcastReceiver, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
});
b.show();
}
break;
case appdefine.MSG_CONNECTION_FAIL: {
stopTimer();
ImageView imgStatus = (ImageView) findViewById(R.id.ImgViewFiwoServerConnectStatus);
imgStatus.setImageResource(R.drawable.icon_disconnect);
imgStatus.setVisibility(View.VISIBLE);
cancel_progressdialog();
}
break;
case appdefine.MSG_GET_DOMAIN: {
cancel_progressdialog();
cancel();
}
break;
case appdefine.MSG_CONNECT_RESPONSE: {
stopTimer();
}
break;
case appdefine.MSG_CONNECT_NON_RESPONSE: {
stopTimer();
ImageView imgStatus = (ImageView) findViewById(R.id.ImgViewFiwoServerConnectStatus);
imgStatus.setImageResource(R.drawable.icon_disconnect);
imgStatus.setVisibility(View.VISIBLE);
cancel_progressdialog();
}
break;
default:
break;
}
}
}
public interface OnMyDialogResult{
void finish(String sFiWoAddress, String result);
}
}
| apache-2.0 |
sajavadi/pinot | pinot-server/src/main/java/com/linkedin/pinot/server/starter/helix/AdminApiApplication.java | 4459 | /**
* Copyright (C) 2014-2016 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.server.starter.helix;
import com.linkedin.pinot.server.starter.ServerInstance;
import io.swagger.jaxrs.config.BeanConfig;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import org.glassfish.grizzly.http.server.CLStaticHttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AdminApiApplication extends ResourceConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AdminApiApplication.class);
private final ServerInstance serverInstance;
private URI baseUri;
private boolean started = false;
private HttpServer httpServer;
public static final String RESOURCE_PACKAGE = "com.linkedin.pinot.server.api.resources";
public AdminApiApplication(ServerInstance instance) {
this.serverInstance = instance;
packages(RESOURCE_PACKAGE);
register(new AbstractBinder() {
@Override
protected void configure() {
bind(serverInstance).to(ServerInstance.class);
}
});
register(JacksonFeature.class);
registerClasses(io.swagger.jaxrs.listing.ApiListingResource.class);
registerClasses(io.swagger.jaxrs.listing.SwaggerSerializers.class);
register(new ContainerResponseFilter() {
@Override
public void filter(ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext)
throws IOException {
containerResponseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
}
});
}
public boolean start(int httpPort) {
if (httpPort <= 0 ) {
LOGGER.warn("Invalid admin API port: {}. Not starting admin service", httpPort);
return false;
}
baseUri = URI.create("http://0.0.0.0:" + Integer.toString(httpPort) + "/");
httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, this);
setupSwagger(httpServer);
started = true;
return true;
}
public URI getBaseUri() {
return baseUri;
}
private void setupSwagger(HttpServer httpServer) {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("Pinot Server API");
beanConfig.setDescription("APIs for accessing Pinot server information");
beanConfig.setContact("https://github.com/linkedin/pinot");
beanConfig.setVersion("1.0");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setBasePath(baseUri.getPath());
beanConfig.setResourcePackage(RESOURCE_PACKAGE);
beanConfig.setScan(true);
CLStaticHttpHandler staticHttpHandler = new CLStaticHttpHandler(AdminApiApplication.class.getClassLoader(), "/api/");
// map both /api and /help to swagger docs. /api because it looks nice. /help for backward compatibility
httpServer.getServerConfiguration().addHttpHandler(staticHttpHandler, "/api");
httpServer.getServerConfiguration().addHttpHandler(staticHttpHandler, "/help");
URL swaggerDistLocation = AdminApiApplication.class.getClassLoader()
.getResource("META-INF/resources/webjars/swagger-ui/2.2.2/");
CLStaticHttpHandler swaggerDist = new CLStaticHttpHandler(
new URLClassLoader(new URL[] {swaggerDistLocation}));
httpServer.getServerConfiguration().addHttpHandler(swaggerDist, "/swaggerui-dist/");
}
public void stop(){
if (!started) {
return;
}
httpServer.shutdownNow();
}
}
| apache-2.0 |
uchicom/dirpop3 | src/main/java/com/uchicom/pop3/Pop3Process.java | 17747 | /**
* (c) 2014 uchicom
*/
package com.uchicom.pop3;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import com.uchicom.server.ServerProcess;
import com.uchicom.util.Parameter;
public class Pop3Process implements ServerProcess {
/** ファイルとUIDLで使用する日時フォーマット */
private final SimpleDateFormat format = new SimpleDateFormat(
Constants.DATE_TIME_MILI_FORMAT);
private Parameter parameter;
private Socket socket;
protected FileComparator comparator = new FileComparator();
/** 最終処理時刻 */
private long lastTime = System.currentTimeMillis();
/**
* コンストラクタ.
*
* @param parameter
* @param socket
* @throws IOException
*/
public Pop3Process(Parameter parameter, Socket socket) {
this.parameter = parameter;
this.socket = socket;
}
/**
* pop3処理.
*/
public void execute() {
Pop3Util.log(format.format(new Date()) + ":"
+ String.valueOf(socket.getRemoteSocketAddress()));
// 0.はプロセスごとに変える番号だけど、とくに複数プロセスを持っていないので。
String timestamp = "<" + Thread.currentThread().getId() + "."
+ System.currentTimeMillis() + "@" + parameter.get("hostName")
+ ">";
BufferedReader br = null;
PrintStream ps = null;
try {
br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
// 1接続に対する受付開始
Pop3Util.recieveLine(ps, Constants.RECV_OK, " ", timestamp);
// 以下はログイン中のみ有効な変数
String line = br.readLine();
// ユーザーコマンドでユーザーが設定されたかどうかのフラグ
boolean bUser = false;
// 認証が許可されたかどうかのフラグ
boolean bPass = false;
String user = null;
String pass = null;
File userBox = null;
// メールbox内にあるメールリスト(PASSコマンド時に認証が許可されると設定される)
List<File> mailList = null;
// DELEコマンド時に指定したメールが格納される(PASSコマンド時に認証が許可されると設定される)
List<File> delList = null;
while (line != null) {
if (Pop3Util.isUser(line)) {
bUser = true;
user = line.split(" ")[1];
Pop3Util.recieveLine(ps, Constants.RECV_OK);
} else if (Pop3Util.isPass(line)) {
if (bUser && !bPass) {
pass = line.split(" ")[1];
// ユーザーチェック
boolean existUser = false;
for (File box : parameter.getFile("dir").listFiles()) {
if (box.isDirectory()) {
if (user.equals(box.getName())) {
userBox = box;
File[] mails = userBox
.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir,
String name) {
File file = new File(dir,
name);
if (file.isFile()
&& !file.isHidden()
&& file.canRead()
&& !Constants.PASSWORD_FILE_NAME
.equals(name)) {
return true;
}
return false;
}
});
mailList = Arrays.asList(mails);
Collections.sort(mailList, comparator);
delList = new ArrayList<File>();
existUser = true;
}
}
}
if (existUser) {
// パスワードチェック
if (!"".equals(pass)) {
File passwordFile = new File(userBox,
Constants.PASSWORD_FILE_NAME);
if (passwordFile.exists()
&& passwordFile.isFile()) {
BufferedReader passReader = new BufferedReader(
new InputStreamReader(
new FileInputStream(
passwordFile)));
String password = passReader.readLine();
while ("".equals(password)) {
password = passReader.readLine();
}
passReader.close();
if (pass.equals(password)) {
Pop3Util.recieveLine(ps,
Constants.RECV_OK);
bPass = true;
} else {
// パスワード不一致エラー
Pop3Util.recieveLine(ps,
Constants.RECV_NG);
}
} else {
// パスワードファイルなしエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// パスワード入力なしエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// ユーザー存在しないエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// ユーザー名未入力エラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else if (Pop3Util.isStat(line)) {
if (bPass) {
// 簡易一覧表示
long fileLength = 0;
int fileCnt = 0;
for (File child : mailList) {
if (!delList.contains(child)) {
fileLength += child.length();
fileCnt++;
}
}
Pop3Util.recieveLine(ps, Constants.RECV_OK, " ",
String.valueOf(fileCnt), " ",
String.valueOf(fileLength));
} else {
// 認証なしエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else if (Pop3Util.isList(line)) {
if (bPass) {
// リスト表示
Pop3Util.recieveLine(ps, Constants.RECV_OK);
for (int i = 0; i < mailList.size(); i++) {
File child = mailList.get(i);
if (!delList.contains(child)) {
Pop3Util.recieveLine(ps, String.valueOf(i + 1),
" ", String.valueOf(child.length()));
}
}
Pop3Util.recieveLine(ps, Constants.RECV_DATA);
} else {
// 認証なしエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
ps.flush();
} else if (Pop3Util.isListNum(line)) {
if (bPass) {
// 指定番号のリスト表示
String[] heads = line.split(" ");
int index = Integer.parseInt(heads[1]) - 1;
if (0 <= index && index < mailList.size()) {
File child = mailList.get(index);
if (!delList.contains(child)) {
Pop3Util.recieveLine(ps, Constants.RECV_OK,
" ", line.substring(5), " ",
String.valueOf(child.length()));
} else {
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// index範囲外
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// 認証なしエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else if (Pop3Util.isRetr(line)) {
if (bPass) {
Pop3Util.recieveLine(ps, Constants.RECV_OK);
for (File child : mailList) {
if (!delList.contains(child)) {
BufferedReader fileReader = new BufferedReader(
new InputStreamReader(
new FileInputStream(child)));
String readLine = fileReader.readLine();
while (readLine != null) {
if (readLine.length() > 0 && readLine.charAt(0) == '.') {
ps.write((byte)'.');
}
Pop3Util.recieveLine(ps, readLine);
readLine = fileReader.readLine();
lastTime = System.currentTimeMillis();
}
fileReader.close();
}
}
Pop3Util.recieveLine(ps, Constants.RECV_DATA);
} else {
// エラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else if (Pop3Util.isRetrNum(line)) {
if (bPass) {
String[] heads = line.split(" ");
int index = Integer.parseInt(heads[1]) - 1;
if (0 <= index && index < mailList.size()) {
File child = mailList.get(index);
if (!delList.contains(child)) {
Pop3Util.recieveLine(ps, Constants.RECV_OK, " ", String.valueOf(child.length()));
BufferedReader fileReader = new BufferedReader(
new InputStreamReader(
new FileInputStream(child)));
String readLine = fileReader.readLine();
while (readLine != null) {
if (readLine.length() > 0 && readLine.charAt(0) == '.') {
ps.write((byte)'.');
}
Pop3Util.recieveLine(ps, readLine);
readLine = fileReader.readLine();
lastTime = System.currentTimeMillis();
}
Pop3Util.recieveLine(ps, Constants.RECV_DATA);
fileReader.close();
} else {
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// index範囲外
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// エラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
ps.flush();
} else if (Pop3Util.isDeleNum(line)) {
if (bPass) {
// 削除処理
String[] heads = line.split(" ");
int index = Integer.parseInt(heads[1]) - 1;
if (0 <= index && index < mailList.size()) {
File child = mailList.get(index);
delList.add(child);
Pop3Util.recieveLine(ps, Constants.RECV_OK);
} else {
// index範囲外
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// エラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else if (Pop3Util.isRset(line)) {
// リセット
if (bPass) {
// 消去マークを無くす
delList.clear();
Pop3Util.recieveLine(ps, Constants.RECV_OK);
} else {
// エラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else if (Pop3Util.isQuit(line)) {
if (delList != null) {
// 消去マークの入ったファイルを削除する
for (File delFile : delList) {
delFile.delete();
}
}
Pop3Util.recieveLine(ps, Constants.RECV_OK);
// 削除失敗時は-ERRを返すべきだけどまだやってない。
break;
} else if (Pop3Util.isTopNumNum(line)) {
if (bPass) {
// TRANSACTION 状態でのみ許可される
String[] heads = line.split(" ");
int index = Integer.parseInt(heads[1]) - 1;
if (0 <= index && index < mailList.size()) {
File child = mailList.get(index);
if (!delList.contains(child)) {
Pop3Util.recieveLine(ps, Constants.RECV_OK);
BufferedReader fileReader = new BufferedReader(
new InputStreamReader(
new FileInputStream(child)));
String readLine = fileReader.readLine();
int maxRow = Integer.parseInt(heads[2]);
int row = 0;
boolean messageHead = true;
while (readLine != null
&& (messageHead || row <= maxRow)) {
Pop3Util.recieveLine(ps, readLine);
readLine = fileReader.readLine();
if (!messageHead) {
row++;
}
if ("".equals(readLine)) {
messageHead = false;
}
}
Pop3Util.recieveLine(ps, Constants.RECV_DATA);
fileReader.close();
} else {
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// 認証なしエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else if (Pop3Util.isUidl(line)) {
if (bPass) {
// TRANSACTION 状態でのみ許可される
Pop3Util.recieveLine(ps, Constants.RECV_OK);
for (int i = 0; i < mailList.size(); i++) {
File child = mailList.get(i);
if (!delList.contains(child)) {
ps.print(i + 1);
ps.print(' ');
String name = child.getName();
int lastIndex = name.lastIndexOf('~');
if (lastIndex < 0) {
if (name.length() > 70) {
lastIndex = name.length() - 70;
} else {
ps.print(name);
}
} else {
ps.print(name.substring(lastIndex));
}
ps.print(Constants.RECV_LINE_END);
}
}
Pop3Util.recieveLine(ps, Constants.RECV_DATA);
} else {
// 認証なしエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
ps.flush();
} else if (Pop3Util.isUidlNum(line)) {
if (bPass) {
// TRANSACTION 状態でのみ許可される
String[] heads = line.split(" ");
int index = Integer.parseInt(heads[1]) - 1;
if (0 <= index && index < mailList.size()) {
File child = mailList.get(index);
if (!delList.contains(child)) {
ps.print(Constants.RECV_OK);
ps.print(' ');
ps.print(heads[1]);
ps.print(' ');
String name = child.getName();
int lastIndex = name.lastIndexOf('~');
if (lastIndex < 0) {
if (name.length() > 70) {
lastIndex = name.length() - 70;
} else {
ps.print(name);
}
} else {
ps.print(name.substring(lastIndex));
}
ps.print(Constants.RECV_LINE_END);
} else {
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// index範囲外
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// 認証なしエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
ps.flush();
} else if (Pop3Util.isApopNameDigest(line)) {
if (!bPass) {
// 未実装のためエラーとする
String[] heads = line.split(" ");
user = heads[1];
String digest = heads[2];
// ユーザーチェック
boolean existUser = false;
for (File box : parameter.getFile("dir").listFiles()) {
if (box.isDirectory()) {
if (user.equals(box.getName())) {
userBox = box;
File[] mails = userBox
.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir,
String name) {
File file = new File(dir,
name);
if (file.isFile()
&& !file.isHidden()
&& !Constants.PASSWORD_FILE_NAME
.equals(name)) {
return true;
}
return false;
}
});
mailList = Arrays.asList(mails);
Collections.sort(mailList, comparator);
delList = new ArrayList<File>();
existUser = true;
}
}
}
if (existUser) {
// パスワードチェック
File passwordFile = new File(userBox,
Constants.PASSWORD_FILE_NAME);
if (passwordFile.exists() && passwordFile.isFile()) {
BufferedReader passReader = new BufferedReader(
new InputStreamReader(
new FileInputStream(
passwordFile)));
String password = passReader.readLine();
while ("".equals(password)) {
password = passReader.readLine();
}
passReader.close();
// ダイジェストとタイムスタンプを元にダイジェストを作成
MessageDigest md = MessageDigest
.getInstance("MD5");
md.update((timestamp + password).getBytes());
byte[] passBytes = md.digest();
StringBuffer strBuff = new StringBuffer(32);
for (int i = 0; i < passBytes.length; i++) {
int d = passBytes[i] & 0xFF;
if (d < 0x10) {
strBuff.append("0");
}
strBuff.append(Integer.toHexString(d));
}
if (digest.equals(strBuff.toString())) {
Pop3Util.recieveLine(ps, Constants.RECV_OK);
bPass = true;
} else {
// パスワード不一致エラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// パスワードファイルなしエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// ユーザー存在しないエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else {
// パスワード認証後に再度パスワード認証はエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG);
}
} else if (line.length() == 0 || Pop3Util.isNoop(line)) {
// 何もしない
} else {
//コマンドエラー
Pop3Util.recieveLine(ps, Constants.RECV_NG_CMD_NOT_FOUND);
}
lastTime = System.currentTimeMillis();
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
synchronized (socket) {
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
socket = null;
}
}
}
}
/**
* 最終処理時刻を取得します.
*
* @return
*/
public long getLastTime() {
return lastTime;
}
/**
* 強制終了.
*/
public void forceClose() {
// if (rejectMap.containsKey(senderAddress)) {
// rejectMap.put(senderAddress, rejectMap.get(senderAddress) + 1);
// } else {
// rejectMap.put(senderAddress, 1);
// }
System.out.println("forceClose!");
if (socket != null && socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
socket = null;
}
}
}
| apache-2.0 |
dickschoeller/gedbrowser | gedbrowserng/src/main/java/org/schoellerfamily/gedbrowser/api/crud/NewId.java | 830 | package org.schoellerfamily.gedbrowser.api.crud;
import org.schoellerfamily.gedbrowser.datamodel.GedObject;
import org.schoellerfamily.gedbrowser.persistence.domain.GedDocument;
import org.schoellerfamily.gedbrowser.persistence.domain.RootDocument;
import org.schoellerfamily.gedbrowser.persistence.repository.FindableDocument;
/**
* @param <X> the data model type we are creating
* @param <Y> the DB type associated with the type X
* @author Dick Schoeller
*/
public interface NewId <X extends GedObject, Y extends GedDocument<X>> {
/**
* @return the DB repository for this type
*/
FindableDocument<X, Y> getRepository();
/**
* @param root the root
* @return the next ID string
*/
default String newId(final RootDocument root) {
return getRepository().newId(root);
}
}
| apache-2.0 |
egustafson/sandbox | Java/mvn/spring-spel/src/test/java/org/elfwerks/sandbox/spel/DemoSpringBeanTest.java | 1016 | package org.elfwerks.sandbox.spel;
import static org.junit.Assert.*;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // default context: DemoSpringBeanTest-context.xml
public class DemoSpringBeanTest {
@Resource
protected DemoSpringBean testBean;
@Test
public void testGetName() {
assertEquals("Configuration Name", testBean.getName());
}
@Test
public void testGetVersion() {
assertEquals("1.2.0", testBean.getVersion());
}
@Test
public void testGetPort() {
assertEquals(2120, testBean.getPort());
}
@Test
public void testToString() {
String str = testBean.toString();
System.out.println(str);
assertNotNull(str);
}
}
| apache-2.0 |
marcinkwiatkowski/buck | src/com/facebook/buck/artifact_cache/MultiArtifactCache.java | 4883 | /*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.artifact_cache;
import com.facebook.buck.io.BorrowablePath;
import com.facebook.buck.io.LazyPath;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.util.MoreCollectors;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.List;
import java.util.Optional;
/**
* MultiArtifactCache encapsulates a set of ArtifactCache instances such that fetch() succeeds if
* any of the ArtifactCaches contain the desired artifact, and store() applies to all
* ArtifactCaches.
*/
public class MultiArtifactCache implements ArtifactCache {
private final ImmutableList<ArtifactCache> artifactCaches;
private final ImmutableList<ArtifactCache> writableArtifactCaches;
private final boolean isStoreSupported;
public MultiArtifactCache(ImmutableList<ArtifactCache> artifactCaches) {
this.artifactCaches = artifactCaches;
this.writableArtifactCaches =
artifactCaches
.stream()
.filter(c -> c.getCacheReadMode().equals(CacheReadMode.READWRITE))
.collect(MoreCollectors.toImmutableList());
this.isStoreSupported = this.writableArtifactCaches.size() > 0;
}
/**
* Fetch the artifact matching ruleKey and store it to output. If any of the encapsulated
* ArtifactCaches contains the desired artifact, this method succeeds, and it may store the
* artifact to one or more of the other encapsulated ArtifactCaches as a side effect.
*/
@Override
public CacheResult fetch(RuleKey ruleKey, LazyPath output) {
CacheResult cacheResult = CacheResult.miss();
ImmutableList.Builder<ArtifactCache> priorCaches = ImmutableList.builder();
for (ArtifactCache artifactCache : artifactCaches) {
cacheResult = artifactCache.fetch(ruleKey, output);
if (cacheResult.getType().isSuccess()) {
break;
}
if (artifactCache.getCacheReadMode().isWritable()) {
priorCaches.add(artifactCache);
}
}
if (cacheResult.getType().isSuccess()) {
// Success; terminate search for a cached artifact, and propagate artifact to caches
// earlier in the search order so that subsequent searches terminate earlier.
storeToCaches(
priorCaches.build(),
ArtifactInfo.builder()
.addRuleKeys(ruleKey)
.setMetadata(cacheResult.getMetadata())
.build(),
BorrowablePath.notBorrowablePath(output.getUnchecked()));
}
return cacheResult;
}
private static ListenableFuture<Void> storeToCaches(
ImmutableList<ArtifactCache> caches, ArtifactInfo info, BorrowablePath output) {
// TODO(cjhopman): support BorrowablePath with multiple writable caches.
if (caches.size() != 1) {
output = BorrowablePath.notBorrowablePath(output.getPath());
}
List<ListenableFuture<Void>> storeFutures = Lists.newArrayListWithExpectedSize(caches.size());
for (ArtifactCache artifactCache : caches) {
storeFutures.add(artifactCache.store(info, output));
}
// Aggregate future to ensure all store operations have completed.
return Futures.transform(Futures.allAsList(storeFutures), Functions.<Void>constant(null));
}
/** Store the artifact to all encapsulated ArtifactCaches. */
@Override
public ListenableFuture<Void> store(ArtifactInfo info, BorrowablePath output) {
return storeToCaches(writableArtifactCaches, info, output);
}
@Override
public CacheReadMode getCacheReadMode() {
return isStoreSupported ? CacheReadMode.READWRITE : CacheReadMode.READONLY;
}
@Override
public void close() {
Optional<RuntimeException> throwable = Optional.empty();
for (ArtifactCache artifactCache : artifactCaches) {
try {
artifactCache.close();
} catch (RuntimeException e) {
throwable = Optional.of(e);
}
}
if (throwable.isPresent()) {
throw throwable.get();
}
}
@VisibleForTesting
ImmutableList<ArtifactCache> getArtifactCaches() {
return ImmutableList.copyOf(artifactCaches);
}
}
| apache-2.0 |
mr3chitk/KLTN | app/src/androidTest/java/com/uit_252254/mr3chi/kltn/Utils/UtilsTest.java | 484 | package com.uit_252254.mr3chi.kltn.Utils;
import junit.framework.TestCase;
/**
* Created by Jie on 6/2/2015.
*/
public class UtilsTest extends TestCase {
public void testCalculateBirthdayToWeeks() throws Exception {
int expected = 1;
int reality = 1;
assertEquals(expected, reality);
}
public void testGetGuessingBirthDay() throws Exception {
int expected = 1;
int reality = 2;
assertEquals(expected, reality);
}
} | apache-2.0 |
naveenbhaskar/gocd | server/src/test-fast/java/com/thoughtworks/go/server/service/AdminsConfigServiceTest.java | 8812 | /*
* 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.server.service;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.exceptions.GoConfigInvalidException;
import com.thoughtworks.go.config.update.AdminsConfigUpdateCommand;
import com.thoughtworks.go.helper.GoConfigMother;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.service.result.BulkUpdateAdminsResult;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
public class AdminsConfigServiceTest {
@Mock
private GoConfigService goConfigService;
private BasicCruiseConfig cruiseConfig;
private AdminsConfigService adminsConfigService;
@Mock
private EntityHashingService entityHashingService;
@Before
public void setUp() throws Exception {
initMocks(this);
cruiseConfig = GoConfigMother.defaultCruiseConfig();
when(goConfigService.cruiseConfig()).thenReturn(cruiseConfig);
adminsConfigService = new AdminsConfigService(goConfigService, entityHashingService);
}
@Test
public void update_shouldAddAdminsToConfig() {
AdminsConfig config = new AdminsConfig();
Username admin = new Username("admin");
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
adminsConfigService.update(admin, config, "md5", result);
verify(goConfigService).updateConfig(any(AdminsConfigUpdateCommand.class), eq(admin));
}
@Test
public void shouldBulkUpdateToAddAdminsToConfig() {
AdminsConfig config = new AdminsConfig(new AdminUser("existingAdminUser"), new AdminRole("existingAdminRole"));
cruiseConfig = GoConfigMother.defaultCruiseConfig();
cruiseConfig.server().security().setAdminsConfig(config);
when(goConfigService.serverConfig()).thenReturn(cruiseConfig.server());
Username user = new Username("user");
adminsConfigService.bulkUpdate(user, singletonList("newUser1"), emptyList(), singletonList("newRole1"), emptyList(), "md5");
ArgumentCaptor<AdminsConfigUpdateCommand> captor = ArgumentCaptor.forClass(AdminsConfigUpdateCommand.class);
verify(goConfigService).updateConfig(captor.capture(), eq(user));
AdminsConfigUpdateCommand updateCommand = captor.getValue();
AdminsConfig adminsConfig = updateCommand.getPreprocessedEntityConfig();
assertThat(adminsConfig.getUsers(), hasSize(2));
assertThat(adminsConfig.getUsers(), hasItems(new AdminUser("existingAdminUser"), new AdminUser("newUser1")));
assertThat(adminsConfig.getRoles(), hasSize(2));
assertThat(adminsConfig.getRoles(), hasItems(new AdminRole("existingAdminRole"), new AdminRole("newRole1")));
}
@Test
public void shouldBulkUpdateToRemoveAdminsFromConfig() {
AdminsConfig config = new AdminsConfig(new AdminUser("adminUser1"), new AdminUser("adminUser2"),
new AdminRole("adminRole1"), new AdminRole("adminRole2"));
cruiseConfig = GoConfigMother.defaultCruiseConfig();
cruiseConfig.server().security().setAdminsConfig(config);
when(goConfigService.serverConfig()).thenReturn(cruiseConfig.server());
Username user = new Username("user");
adminsConfigService.bulkUpdate(user, emptyList(), singletonList("adminUser1"), emptyList(), singletonList("adminRole1"), "md5");
ArgumentCaptor<AdminsConfigUpdateCommand> captor = ArgumentCaptor.forClass(AdminsConfigUpdateCommand.class);
verify(goConfigService).updateConfig(captor.capture(), eq(user));
AdminsConfigUpdateCommand updateCommand = captor.getValue();
AdminsConfig adminsConfig = updateCommand.getPreprocessedEntityConfig();
assertThat(adminsConfig.getUsers(), hasSize(1));
assertThat(adminsConfig.getUsers(), hasItems(new AdminUser("adminUser2")));
assertThat(adminsConfig.getRoles(), hasSize(1));
assertThat(adminsConfig.getRoles(), hasItems(new AdminRole("adminRole2")));
}
@Test
public void bulkUpdate_shouldValidateThatRoleIsAnAdminWhenTryingToRemove() {
AdminsConfig config = new AdminsConfig(new AdminUser("adminUser1"), new AdminUser("adminUser2"),
new AdminRole("adminRole1"), new AdminRole("adminRole2"));
cruiseConfig = GoConfigMother.defaultCruiseConfig();
cruiseConfig.server().security().setAdminsConfig(config);
when(goConfigService.serverConfig()).thenReturn(cruiseConfig.server());
Username user = new Username("user");
BulkUpdateAdminsResult result = adminsConfigService.bulkUpdate(user, emptyList(), emptyList(), emptyList(),
singletonList("someOtherRole"), "md5");
assertThat(result.isSuccessful(), is(false));
assertThat(result.httpCode(), is(422));
assertThat(result.message(), is("Update failed because some users or roles do not exist under super admins."));
assertThat(result.getNonExistentRoles(), hasSize(1));
assertThat(result.getNonExistentRoles(), hasItem(new CaseInsensitiveString("someOtherRole")));
assertThat(result.getNonExistentUsers(), hasSize(0));
verify(goConfigService, times(0)).updateConfig(any(), any());
}
@Test
public void bulkUpdate_shouldValidateThatUserIsAnAdminWhenTryingToRemove() {
AdminsConfig config = new AdminsConfig(new AdminUser("adminUser1"), new AdminUser("adminUser2"),
new AdminRole("adminRole1"), new AdminRole("adminRole2"));
cruiseConfig = GoConfigMother.defaultCruiseConfig();
cruiseConfig.server().security().setAdminsConfig(config);
when(goConfigService.serverConfig()).thenReturn(cruiseConfig.server());
Username user = new Username("user");
BulkUpdateAdminsResult result = adminsConfigService.bulkUpdate(user, emptyList(), singletonList("someOtherUser"),
emptyList(), emptyList(), "md5");
assertThat(result.isSuccessful(), is(false));
assertThat(result.httpCode(), is(422));
assertThat(result.getNonExistentUsers(), hasSize(1));
assertThat(result.getNonExistentUsers(), hasItem(new CaseInsensitiveString("someOtherUser")));
assertThat(result.getNonExistentRoles(), hasSize(0));
verify(goConfigService, times(0)).updateConfig(any(), any());
}
@Test
public void bulkUpdate_shouldAddErrorsWhenValidationFails() {
Username user = new Username("user");
AdminsConfig config = new AdminsConfig(new AdminUser("adminUser1"), new AdminUser("adminUser2"),
new AdminRole("adminRole1"), new AdminRole("adminRole2"));
config.errors().add("foo", "bar");
config.errors().add("baz", "bar");
cruiseConfig = GoConfigMother.defaultCruiseConfig();
cruiseConfig.server().security().setAdminsConfig(config);
when(goConfigService.serverConfig()).thenReturn(cruiseConfig.server());
cruiseConfig = GoConfigMother.defaultCruiseConfig();
cruiseConfig.server().security().setAdminsConfig(config);
when(goConfigService.serverConfig()).thenReturn(cruiseConfig.server());
doThrow(new GoConfigInvalidException(cruiseConfig, "Validation Failed."))
.when(goConfigService).updateConfig(any(AdminsConfigUpdateCommand.class), eq(user));
BulkUpdateAdminsResult result = adminsConfigService.bulkUpdate(user, emptyList(), emptyList(), singletonList("roleToRemove"),
emptyList(), "md5");
assertThat(result.isSuccessful(), is(false));
assertThat(result.httpCode(), is(422));
assertThat(result.message(), is("Validations failed for admins. Error(s): [bar]. Please correct and resubmit."));
}
}
| apache-2.0 |
BonDyka/abondarev | intern/chapter_001/src/main/java/ru/job4j/loop/package-info.java | 158 | /**
* Package for loop task.
*
* @author Alexander Bondarev (mailto:bondarew2507@gmail.com)
* @version 2.0
* @since 13.07.2017
*/
package ru.job4j.loop; | apache-2.0 |
gdefias/JavaDemo | InitJava/base/src/main/java/Init/JavaThis.java | 1015 | /**
* Created by Defias on 2016/2/27.
*
* this
*
* 关于构造方法:
* 1、构造方法的名称必须与类的名称相同,并且没有返回值
* 2、每个类都有构造方法。如果没有显式地为类定义构造方法,Java编译器将会为该类提供一个默认的构造方法
* 3、构造方法不能被显示调用
* 4、可以通过重载构造方法来表达对象的多种初始化行为
*/
package Init;
public class JavaThis {
public String name;
public int age;
public JavaThis(){
this("微学苑", 3); //调用本类的其它构造方法(下面带参的Demo方法),它必须作为构造方法的第一句
}
public JavaThis(String name, int age){
this.name = name;
this.age = age;
}
public void say(){
System.out.println("网站的名字是" + name + ",已经成立了" + age + "年");
}
public static void main(String[] args) {
JavaThis obj = new JavaThis();
obj.say();
}
}
| apache-2.0 |
SanteriHetekivi/Rasian | app/src/main/java/com/hetekivi/rasian/Tasks/RemoveTask.java | 1842 | package com.hetekivi.rasian.Tasks;
/**
* Created by Santeri Hetekivi on 2.4.2016.
*/
import android.os.AsyncTask;
import com.hetekivi.rasian.Interfaces.Addable;
import com.hetekivi.rasian.Interfaces.Listener;
import com.hetekivi.rasian.Interfaces.Removable;
/**
* AsyncTask
* for loading data from preferences.
*/
public class RemoveTask extends RootTask<Object, Void, Boolean>
{
private Removable delegate = null;
public RemoveTask(Removable obj)
{
this.delegate = obj;
}
public RemoveTask(Removable obj, Listener _listener)
{
this.delegate = obj;
this.listener = _listener;
}
public RemoveTask(Removable obj, Listener _listener, Object _object)
{
this.delegate = obj;
this.listener = _listener;
this.object = _object;
}
/**
* Background runner.
* for saving data to preferences.
* @param objectsToRemove Objects that will be removed.
* @return Data has been loaded.
*/
@Override
protected Boolean doInBackground(Object... objectsToRemove)
{
boolean success = false;
if(this.delegate != null && objectsToRemove != null)
{
success = true;
for (Object objectToRemove: objectsToRemove)
{
success = delegate.Remove(objectToRemove) && success;
}
}
return success;
}
/**
* Post Executor
* for telling caller what happened.
* @param success All given classes has been loaded.
*/
@Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
if(delegate != null)
{
if(success) delegate.onRemoveSuccess();
else delegate.onRemoveFailure();
}
this.callListener(success);
}
}
| apache-2.0 |
charliem/OCM | OCM Compiler/src/com/kissintellignetsystems/ocm/compiler/parser/SimpleCharStream.java | 12619 | /* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 4.1 */
/* JavaCCOptions:STATIC=true */
package com.kissintellignetsystems.ocm.compiler.parser;
/**
* An implementation of interface CharStream, where the stream is assumed to
* contain only ASCII characters (without unicode processing).
*/
public class SimpleCharStream
{
/** Whether parser is static. */
public static final boolean staticFlag = true;
static int bufsize;
static int available;
static int tokenBegin;
/** Position in buffer. */
static public int bufpos = -1;
static protected int bufline[];
static protected int bufcolumn[];
static protected int column = 0;
static protected int line = 1;
static protected boolean prevCharIsCR = false;
static protected boolean prevCharIsLF = false;
static protected java.io.Reader inputStream;
static protected char[] buffer;
static protected int maxNextCharInd = 0;
static protected int inBuf = 0;
static protected int tabSize = 8;
static protected void setTabSize(int i) { tabSize = i; }
static protected int getTabSize(int i) { return tabSize; }
static protected void ExpandBuff(boolean wrapAround)
{
char[] newbuffer = new char[bufsize + 2048];
int newbufline[] = new int[bufsize + 2048];
int newbufcolumn[] = new int[bufsize + 2048];
try
{
if (wrapAround)
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
System.arraycopy(buffer, 0, newbuffer,
bufsize - tokenBegin, bufpos);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos += (bufsize - tokenBegin));
}
else
{
System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
buffer = newbuffer;
System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
bufline = newbufline;
System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
bufcolumn = newbufcolumn;
maxNextCharInd = (bufpos -= tokenBegin);
}
}
catch (Throwable t)
{
throw new Error(t.getMessage());
}
bufsize += 2048;
available = bufsize;
tokenBegin = 0;
}
static protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd,
available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
}
/** Start. */
static public char BeginToken() throws java.io.IOException
{
tokenBegin = -1;
char c = readChar();
tokenBegin = bufpos;
return c;
}
static protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (tabSize - (column % tabSize));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
/** Read a character. */
static public char readChar() throws java.io.IOException
{
if (inBuf > 0)
{
--inBuf;
if (++bufpos == bufsize)
bufpos = 0;
return buffer[bufpos];
}
if (++bufpos >= maxNextCharInd)
FillBuff();
char c = buffer[bufpos];
UpdateLineColumn(c);
return c;
}
/**
* @deprecated
* @see #getEndColumn
*/
static public int getColumn() {
return bufcolumn[bufpos];
}
/**
* @deprecated
* @see #getEndLine
*/
static public int getLine() {
return bufline[bufpos];
}
/** Get token end column number. */
static public int getEndColumn() {
return bufcolumn[bufpos];
}
/** Get token end line number. */
static public int getEndLine() {
return bufline[bufpos];
}
/** Get token beginning column number. */
static public int getBeginColumn() {
return bufcolumn[tokenBegin];
}
/** Get token beginning line number. */
static public int getBeginLine() {
return bufline[tokenBegin];
}
/** Backup a number of characters. */
static public void backup(int amount) {
inBuf += amount;
if ((bufpos -= amount) < 0)
bufpos += bufsize;
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
if (inputStream != null)
throw new Error("\n ERROR: Second call to the constructor of a static SimpleCharStream.\n" +
" You must either use ReInit() or set the JavaCC option STATIC to false\n" +
" during the generation of this class.");
inputStream = dstream;
line = startline;
column = startcolumn - 1;
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.Reader dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn, int buffersize)
{
inputStream = dstream;
line = startline;
column = startcolumn - 1;
if (buffer == null || buffersize != buffer.length)
{
available = bufsize = buffersize;
buffer = new char[buffersize];
bufline = new int[buffersize];
bufcolumn = new int[buffersize];
}
prevCharIsLF = prevCharIsCR = false;
tokenBegin = inBuf = maxNextCharInd = 0;
bufpos = -1;
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.Reader dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, int startline,
int startcolumn)
{
this(dstream, startline, startcolumn, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
this(dstream, encoding, 1, 1, 4096);
}
/** Constructor. */
public SimpleCharStream(java.io.InputStream dstream)
{
this(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
{
ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn, int buffersize)
{
ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream)
{
ReInit(dstream, 1, 1, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, String encoding, int startline,
int startcolumn) throws java.io.UnsupportedEncodingException
{
ReInit(dstream, encoding, startline, startcolumn, 4096);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream dstream, int startline,
int startcolumn)
{
ReInit(dstream, startline, startcolumn, 4096);
}
/** Get token literal value. */
static public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
}
/** Get the suffix. */
static public char[] GetSuffix(int len)
{
char[] ret = new char[len];
if ((bufpos + 1) >= len)
System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
else
{
System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
len - bufpos - 1);
System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
}
return ret;
}
/** Reset buffer when finished. */
static public void Done()
{
buffer = null;
bufline = null;
bufcolumn = null;
}
/**
* Method to adjust line and column numbers for the start of a token.
*/
static public void adjustBeginLineColumn(int newLine, int newCol)
{
int start = tokenBegin;
int len;
if (bufpos >= tokenBegin)
{
len = bufpos - tokenBegin + inBuf + 1;
}
else
{
len = bufsize - tokenBegin + bufpos + 1 + inBuf;
}
int i = 0, j = 0, k = 0;
int nextColDiff = 0, columnDiff = 0;
while (i < len &&
bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
{
bufline[j] = newLine;
nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
bufcolumn[j] = newCol + columnDiff;
columnDiff = nextColDiff;
i++;
}
if (i < len)
{
bufline[j] = newLine++;
bufcolumn[j] = newCol + columnDiff;
while (i++ < len)
{
if (bufline[j = start % bufsize] != bufline[++start % bufsize])
bufline[j] = newLine++;
else
bufline[j] = newLine;
}
}
line = bufline[j];
column = bufcolumn[j];
}
}
/* JavaCC - OriginalChecksum=4bcc43aa1969efcd072c2b53b1565cc6 (do not edit this line) */
| apache-2.0 |
ksoichiro/spring-boot-practice | contents/20161016-logging/src/main/java/com/example/spring/service/ProjectService.java | 287 | package com.example.spring.service;
import org.springframework.stereotype.Service;
@Service
public class ProjectService {
public void create(String name) {
if ("bar".equals(name)) {
throw new IllegalStateException("Service throws exception");
}
}
}
| apache-2.0 |
duck1123/java-xmltooling | src/main/java/org/opensaml/xml/encryption/InlineEncryptedKeyResolver.java | 1603 | /*
* Copyright [2007] [University Corporation for Advanced Internet Development, Inc.]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensaml.xml.encryption;
import java.util.ArrayList;
import java.util.List;
/**
* Implementation of {@link EncryptedKeyResolver} which finds {@link EncryptedKey} elements
* within the {@link org.opensaml.xml.signature.KeyInfo} of the {@link EncryptedData} context.
*/
public class InlineEncryptedKeyResolver extends AbstractEncryptedKeyResolver {
/** {@inheritDoc} */
public Iterable<EncryptedKey> resolve(EncryptedData encryptedData) {
List<EncryptedKey> resolvedEncKeys = new ArrayList<EncryptedKey>();
if (encryptedData.getKeyInfo() == null) {
return resolvedEncKeys;
}
for (EncryptedKey encKey : encryptedData.getKeyInfo().getEncryptedKeys()) {
if (matchRecipient(encKey.getRecipient())) {
resolvedEncKeys.add(encKey);
}
}
return resolvedEncKeys;
}
} | apache-2.0 |
JervyShi/elasticsearch | modules/transport-netty3/src/test/java/org/elasticsearch/http/netty3/Netty3HttpServerPipeliningTests.java | 11086 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.http.netty3;
import org.elasticsearch.common.network.NetworkService;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.util.MockBigArrays;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.http.netty3.Netty3HttpServerTransport.HttpChannelPipelineFactory;
import org.elasticsearch.http.netty3.pipelining.OrderedDownstreamChannelEvent;
import org.elasticsearch.http.netty3.pipelining.OrderedUpstreamMessageEvent;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.junit.After;
import org.junit.Before;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.elasticsearch.http.netty3.Netty3HttpClient.returnHttpResponseBodies;
import static org.elasticsearch.test.hamcrest.RegexMatcher.matches;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;
/**
* This test just tests, if he pipelining works in general with out any connection the elasticsearch handler
*/
public class Netty3HttpServerPipeliningTests extends ESTestCase {
private NetworkService networkService;
private ThreadPool threadPool;
private MockBigArrays bigArrays;
private CustomNetty3HttpServerTransport httpServerTransport;
@Before
public void setup() throws Exception {
networkService = new NetworkService(Settings.EMPTY, Collections.emptyList());
threadPool = new TestThreadPool("test");
bigArrays = new MockBigArrays(Settings.EMPTY, new NoneCircuitBreakerService());
}
@After
public void shutdown() throws Exception {
if (threadPool != null) {
threadPool.shutdownNow();
}
if (httpServerTransport != null) {
httpServerTransport.close();
}
}
public void testThatHttpPipeliningWorksWhenEnabled() throws Exception {
Settings settings = Settings.builder()
.put("http.pipelining", true)
.put("http.port", "0")
.build();
httpServerTransport = new CustomNetty3HttpServerTransport(settings);
httpServerTransport.start();
TransportAddress transportAddress = randomFrom(httpServerTransport.boundAddress().boundAddresses());
final int numberOfRequests = randomIntBetween(4, 16);
final List<String> requests = new ArrayList<>(numberOfRequests);
for (int i = 0; i < numberOfRequests; i++) {
if (rarely()) {
requests.add("/slow/" + i);
} else {
requests.add("/" + i);
}
}
try (Netty3HttpClient nettyHttpClient = new Netty3HttpClient()) {
Collection<HttpResponse> responses = nettyHttpClient.get(transportAddress.address(), requests.toArray(new String[]{}));
Collection<String> responseBodies = returnHttpResponseBodies(responses);
assertThat(responseBodies, contains(requests.toArray()));
}
}
public void testThatHttpPipeliningCanBeDisabled() throws Exception {
Settings settings = Settings.builder()
.put("http.pipelining", false)
.put("http.port", "0")
.build();
httpServerTransport = new CustomNetty3HttpServerTransport(settings);
httpServerTransport.start();
TransportAddress transportAddress = randomFrom(httpServerTransport.boundAddress().boundAddresses());
final int numberOfRequests = randomIntBetween(4, 16);
final Set<Integer> slowIds = new HashSet<>();
final List<String> requests = new ArrayList<>(numberOfRequests);
for (int i = 0; i < numberOfRequests; i++) {
if (rarely()) {
requests.add("/slow/" + i);
slowIds.add(i);
} else {
requests.add("/" + i);
}
}
try (Netty3HttpClient nettyHttpClient = new Netty3HttpClient()) {
Collection<HttpResponse> responses = nettyHttpClient.get(transportAddress.address(), requests.toArray(new String[]{}));
List<String> responseBodies = new ArrayList<>(returnHttpResponseBodies(responses));
// we cannot be sure about the order of the responses, but the slow ones should come last
assertThat(responseBodies, hasSize(numberOfRequests));
for (int i = 0; i < numberOfRequests - slowIds.size(); i++) {
assertThat(responseBodies.get(i), matches("/\\d+"));
}
final Set<Integer> ids = new HashSet<>();
for (int i = 0; i < slowIds.size(); i++) {
final String response = responseBodies.get(numberOfRequests - slowIds.size() + i);
assertThat(response, matches("/slow/\\d+"));
assertTrue(ids.add(Integer.parseInt(response.split("/")[2])));
}
assertThat(ids, equalTo(slowIds));
}
}
class CustomNetty3HttpServerTransport extends Netty3HttpServerTransport {
private final ExecutorService executorService;
public CustomNetty3HttpServerTransport(Settings settings) {
super(settings, Netty3HttpServerPipeliningTests.this.networkService,
Netty3HttpServerPipeliningTests.this.bigArrays, Netty3HttpServerPipeliningTests.this.threadPool
);
this.executorService = Executors.newFixedThreadPool(5);
}
@Override
public ChannelPipelineFactory configureServerChannelPipelineFactory() {
return new CustomHttpChannelPipelineFactory(this, executorService, Netty3HttpServerPipeliningTests.this.threadPool
.getThreadContext());
}
@Override
public void stop() {
executorService.shutdownNow();
super.stop();
}
}
private class CustomHttpChannelPipelineFactory extends HttpChannelPipelineFactory {
private final ExecutorService executorService;
public CustomHttpChannelPipelineFactory(Netty3HttpServerTransport transport, ExecutorService executorService,
ThreadContext threadContext) {
super(transport, randomBoolean(), threadContext);
this.executorService = executorService;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = super.getPipeline();
pipeline.replace("handler", "handler", new PossiblySlowUpstreamHandler(executorService));
return pipeline;
}
}
class PossiblySlowUpstreamHandler extends SimpleChannelUpstreamHandler {
private final ExecutorService executorService;
public PossiblySlowUpstreamHandler(ExecutorService executorService) {
this.executorService = executorService;
}
@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
executorService.submit(new PossiblySlowRunnable(ctx, e));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
logger.info("Caught exception", e.getCause());
e.getChannel().close();
}
}
class PossiblySlowRunnable implements Runnable {
private ChannelHandlerContext ctx;
private MessageEvent e;
public PossiblySlowRunnable(ChannelHandlerContext ctx, MessageEvent e) {
this.ctx = ctx;
this.e = e;
}
@Override
public void run() {
HttpRequest request;
OrderedUpstreamMessageEvent oue = null;
if (e instanceof OrderedUpstreamMessageEvent) {
oue = (OrderedUpstreamMessageEvent) e;
request = (HttpRequest) oue.getMessage();
} else {
request = (HttpRequest) e.getMessage();
}
ChannelBuffer buffer = ChannelBuffers.copiedBuffer(request.getUri(), StandardCharsets.UTF_8);
DefaultHttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);
httpResponse.headers().add(CONTENT_LENGTH, buffer.readableBytes());
httpResponse.setContent(buffer);
final boolean slow = request.getUri().matches("/slow/\\d+");
if (slow) {
try {
Thread.sleep(scaledRandomIntBetween(500, 1000));
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
} else {
assert request.getUri().matches("/\\d+");
}
if (oue != null) {
ctx.sendDownstream(new OrderedDownstreamChannelEvent(oue, 0, true, httpResponse));
} else {
ctx.getChannel().write(httpResponse);
}
}
}
}
| apache-2.0 |
jiangyuanlin/hello | src/main/java/com/idp/web/generator/controller/CgDataSourceController.java | 2407 | package com.idp.web.generator.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.idp.common.base.BaseController;
import com.idp.common.persistence.Page;
import com.idp.common.util.ValidateUtils;
import com.idp.web.generator.entity.CgDataSource;
import com.idp.web.generator.service.CgDataSourceService;
import net.sf.json.JSONObject;
@Controller
@RequestMapping("/dataSource")
public class CgDataSourceController extends BaseController {
private static Logger logger = Logger.getLogger(CgDataSourceController.class);
@Resource
private CgDataSourceService cgDataSourceService;
@RequestMapping("/init")
public String init(HttpServletRequest request){
return "generator/datasource/dataSourceSearch";
}
@RequestMapping("/list")
public String list(CgDataSource dataSource,Page<CgDataSource> page,HttpServletRequest request){
request.setAttribute("page", cgDataSourceService.findByPage(dataSource, page));
return "generator/datasource/dataSourceList";
}
@RequestMapping("/dataSource")
public String database(Long id,HttpServletRequest request){
if(ValidateUtils.isNotEmpty(id)){
CgDataSource dataSource = cgDataSourceService.getById(id);
request.setAttribute("dataSource", dataSource);
}
return "generator/datasource/dataSource";
}
@RequestMapping("/save")
@ResponseBody
public String save(CgDataSource dataSource){
JSONObject json = new JSONObject();
try {
if(ValidateUtils.isNotEmpty(dataSource.getId())){
cgDataSourceService.update(dataSource);
}
else{
cgDataSourceService.add(dataSource);
}
json.put("result", "save_success");
} catch (Exception e) {
json.put("result", "save_fail");
logger.error(e.getMessage(), e);
}
return json.toString();
}
@RequestMapping("/delete")
@ResponseBody
public String delete(Long id){
JSONObject json = new JSONObject();
try {
if(ValidateUtils.isNotEmpty(id)){
cgDataSourceService.delete(id);
json.put("result", "delete_success");
}
} catch (Exception e) {
json.put("result", "delete_fail");
logger.error(e.getMessage(), e);
}
return json.toString();
}
}
| apache-2.0 |
nickman/heliosutils | src/main/java/com/heliosapm/utils/io/package-info.java | 1077 | /**
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.
*/
/**
* <p>Title: package-info</p>
* <p>Description: Package of generic IO utilities</p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.utils.io.package-info</code></p>
*/
package com.heliosapm.utils.io; | apache-2.0 |
googleads/googleads-java-lib | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201809/cm/AdGroupExtensionSetting.java | 9964 | // Copyright 2018 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.
/**
* AdGroupExtensionSetting.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.adwords.axis.v201809.cm;
/**
* An AdGroupExtensionSetting is used to add or modify extensions
* being served for the specified
* ad group.
*/
public class AdGroupExtensionSetting implements java.io.Serializable {
/* The id of the ad group for the feed items being added or modified.
* <span class="constraint Required">This field is required and should
* not be {@code null}.</span> */
private java.lang.Long adGroupId;
/* The extension type the extension setting applies to.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span> */
private com.google.api.ads.adwords.axis.v201809.cm.FeedType extensionType;
/* The extension setting specifying which extensions to serve
* for the specified ad group. If
* extensionSetting is empty (i.e. has an empty list
* of feed items and null platformRestrictions),
* extensions are disabled for the specified extensionType. */
private com.google.api.ads.adwords.axis.v201809.cm.ExtensionSetting extensionSetting;
public AdGroupExtensionSetting() {
}
public AdGroupExtensionSetting(
java.lang.Long adGroupId,
com.google.api.ads.adwords.axis.v201809.cm.FeedType extensionType,
com.google.api.ads.adwords.axis.v201809.cm.ExtensionSetting extensionSetting) {
this.adGroupId = adGroupId;
this.extensionType = extensionType;
this.extensionSetting = extensionSetting;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("adGroupId", getAdGroupId())
.add("extensionSetting", getExtensionSetting())
.add("extensionType", getExtensionType())
.toString();
}
/**
* Gets the adGroupId value for this AdGroupExtensionSetting.
*
* @return adGroupId * The id of the ad group for the feed items being added or modified.
* <span class="constraint Required">This field is required and should
* not be {@code null}.</span>
*/
public java.lang.Long getAdGroupId() {
return adGroupId;
}
/**
* Sets the adGroupId value for this AdGroupExtensionSetting.
*
* @param adGroupId * The id of the ad group for the feed items being added or modified.
* <span class="constraint Required">This field is required and should
* not be {@code null}.</span>
*/
public void setAdGroupId(java.lang.Long adGroupId) {
this.adGroupId = adGroupId;
}
/**
* Gets the extensionType value for this AdGroupExtensionSetting.
*
* @return extensionType * The extension type the extension setting applies to.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public com.google.api.ads.adwords.axis.v201809.cm.FeedType getExtensionType() {
return extensionType;
}
/**
* Sets the extensionType value for this AdGroupExtensionSetting.
*
* @param extensionType * The extension type the extension setting applies to.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public void setExtensionType(com.google.api.ads.adwords.axis.v201809.cm.FeedType extensionType) {
this.extensionType = extensionType;
}
/**
* Gets the extensionSetting value for this AdGroupExtensionSetting.
*
* @return extensionSetting * The extension setting specifying which extensions to serve
* for the specified ad group. If
* extensionSetting is empty (i.e. has an empty list
* of feed items and null platformRestrictions),
* extensions are disabled for the specified extensionType.
*/
public com.google.api.ads.adwords.axis.v201809.cm.ExtensionSetting getExtensionSetting() {
return extensionSetting;
}
/**
* Sets the extensionSetting value for this AdGroupExtensionSetting.
*
* @param extensionSetting * The extension setting specifying which extensions to serve
* for the specified ad group. If
* extensionSetting is empty (i.e. has an empty list
* of feed items and null platformRestrictions),
* extensions are disabled for the specified extensionType.
*/
public void setExtensionSetting(com.google.api.ads.adwords.axis.v201809.cm.ExtensionSetting extensionSetting) {
this.extensionSetting = extensionSetting;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof AdGroupExtensionSetting)) return false;
AdGroupExtensionSetting other = (AdGroupExtensionSetting) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.adGroupId==null && other.getAdGroupId()==null) ||
(this.adGroupId!=null &&
this.adGroupId.equals(other.getAdGroupId()))) &&
((this.extensionType==null && other.getExtensionType()==null) ||
(this.extensionType!=null &&
this.extensionType.equals(other.getExtensionType()))) &&
((this.extensionSetting==null && other.getExtensionSetting()==null) ||
(this.extensionSetting!=null &&
this.extensionSetting.equals(other.getExtensionSetting())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getAdGroupId() != null) {
_hashCode += getAdGroupId().hashCode();
}
if (getExtensionType() != null) {
_hashCode += getExtensionType().hashCode();
}
if (getExtensionSetting() != null) {
_hashCode += getExtensionSetting().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AdGroupExtensionSetting.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "AdGroupExtensionSetting"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("adGroupId");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "adGroupId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("extensionType");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "extensionType"));
elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "Feed.Type"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("extensionSetting");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "extensionSetting"));
elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "ExtensionSetting"));
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 |
uds-lsv/platon | src/main/groovy/de/uds/lsv/platon/script/ExceptionMapper.java | 8419 | /*
* Copyright 2015, Spoken Language Systems Group, Saarland University.
*
* 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.uds.lsv.platon.script;
import java.util.ArrayList;
import java.util.List;
import javax.script.ScriptException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.control.MultipleCompilationErrorsException;
import org.codehaus.groovy.control.messages.ExceptionMessage;
import org.codehaus.groovy.control.messages.Message;
import org.codehaus.groovy.control.messages.SimpleMessage;
import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
import org.codehaus.groovy.syntax.SyntaxException;
import de.uds.lsv.platon.script.IncludeReader.CodeLocation;
public class ExceptionMapper {
private static final Log logger = LogFactory.getLog(ExceptionMapper.class.getName());
private IncludeReader includeReader;
private ClassLoader scriptClassLoader;
public ExceptionMapper(IncludeReader reader, ClassLoader scriptClassLoader) {
this.includeReader = reader;
this.scriptClassLoader = scriptClassLoader;
}
/**
* Try to find the source code location for e and
* wrap it in a DialogScriptException.
* If that's not possible, return e.
*
* @param e
* @return
*/
public Throwable translateException(Throwable e) {
Throwable t = tryTranslateException(e);
if (t == null) {
// We don't know the exception type, but maybe there's
// something useful in the stack trace?
CodeLocation location = getLocationFromTrace(e);
if (location != null) {
return wrapException(e, location);
}
logger.debug("Unknown throwable, no script location found in trace: " + e);
return e;
} else {
return t;
}
}
/**
* @param line
* line number (0-based!)
* @return
*/
private CodeLocation translateLocation(int line) {
if (includeReader != null) {
return includeReader.translateLocation(line);
} else {
return new CodeLocation(null, line);
}
}
/**
* Translate exception if type is supported.
*
* @param e
* @return
*/
private DialogScriptException tryTranslateException(Throwable e) {
if (e instanceof DialogScriptException) {
return (DialogScriptException)e;
} else if (e instanceof ScriptException) {
return translateScriptException((ScriptException)e);
} else if (e instanceof MultipleCompilationErrorsException) {
return translateMultipleCompilationErrorsException((MultipleCompilationErrorsException)e);
} else if (e instanceof SyntaxException) {
return translateSyntaxException((SyntaxException)e);
}
return null;
}
public DialogScriptException translateScriptException(ScriptException e) {
Throwable unpacked = unpackScriptException(e);
if (unpacked != null) {
if (unpacked instanceof ScriptException) {
if (((ScriptException)unpacked).getLineNumber() > 0) {
CodeLocation location = translateLocation(e.getLineNumber() - 1);
return wrapException(e, location);
}
}
// let's see if we have unpacked something useful...
DialogScriptException t = tryTranslateException(unpacked);
if (t != null) {
return t;
}
}
// try to guess a line number from the stack trace
CodeLocation location = getLocationFromTrace(e);
if (location != null) {
return wrapException(e, location);
}
// give up
return null;
}
/**
* Unpack a ScriptException, until we find
* either a ScriptException with a line number
* or a different exception type.
*
* @param e
* @return
*/
private Throwable unpackScriptException(Throwable t) {
for (Throwable e = t; e != null; e = e.getCause()) {
if (e instanceof ScriptException) {
if (((ScriptException)e).getLineNumber() > 0) {
return e;
}
} else {
return e;
}
}
// this would mean we have a ScriptException with
// only ScriptExceptions
return null;
}
@SuppressWarnings("unchecked")
public DialogScriptException translateMultipleCompilationErrorsException(MultipleCompilationErrorsException e) {
List<DialogScriptException> exceptions = new ArrayList<>();
for (Message m : (List<Message>)e.getErrorCollector().getErrors()) {
if (m instanceof SyntaxErrorMessage) {
exceptions.add(translateSyntaxErrorMessage((SyntaxErrorMessage)m));
} else if (m instanceof ExceptionMessage) {
exceptions.add(translateExceptionMessage((ExceptionMessage)m));
} else if (m instanceof SimpleMessage) {
exceptions.add(translateSimpleMessage((SimpleMessage)m));
} else {
throw new AssertionError("Unknown message type: " + m.getClass() + ": " + m);
}
}
if (exceptions.size() == 1) {
return exceptions.get(0);
} else {
return new MultiException(e, exceptions);
}
}
public DialogScriptException translateSimpleMessage(SimpleMessage m) {
// No idea what I'm supposed to make of this one...
return new DialogScriptException(new RuntimeException("SimpleMessage: " + m.getMessage()));
}
public DialogScriptException translateExceptionMessage(ExceptionMessage m) {
Throwable e = m.getCause();
DialogScriptException dse = tryTranslateException(e);
if (dse != null) {
return dse;
}
// no information found -- still wrap exception in a DSE
return new DialogScriptException(e);
}
public DialogScriptException translateSyntaxErrorMessage(SyntaxErrorMessage m) {
return translateSyntaxException(m.getCause());
}
public DialogScriptException translateSyntaxException(SyntaxException e) {
CodeLocation startLocation = translateLocation(e.getStartLine() - 1);
CodeLocation endLocation = translateLocation(e.getEndLine() - 1);
assert (startLocation.url == endLocation.url || startLocation.url.equals(endLocation.url));
DialogScriptException dse = new DialogScriptException(e);
dse.sourceUrl = startLocation.url;
dse.startLine = startLocation.startLine + 1;
dse.endLine = endLocation.startLine + 1;
dse.startColumn = e.getStartColumn();
dse.endColumn = e.getEndColumn();
return dse;
}
/**
* True, if we think the class might be our groovy
* script from the groovy script engine.
*
* @param className
* @return
*/
private boolean couldBeScriptClass(String className) {
// The script class loader has to know the class
Class<?> cls;
try {
cls = scriptClassLoader.loadClass(className);
}
catch (ClassNotFoundException e) {
return false;
}
// The script class is loaded by the script class loader,
// so our class loader should not know it.
try {
this.getClass().getClassLoader().loadClass(className);
return false;
}
catch (ClassNotFoundException e) {
}
return couldBeScriptClassHelper(cls);
}
/**
* @param cls
* A class from the script class loader.
* @return
*/
private boolean couldBeScriptClassHelper(Class<?> cls) {
// If we have a contained class, check the
// parent class
Class<?> encl = cls.getEnclosingClass();
if (encl != null) {
if (couldBeScriptClassHelper(encl)) {
return true;
}
}
// The class has to be a groovy.lang.Script
if (!groovy.lang.Script.class.isAssignableFrom(cls)) {
return false;
}
return true;
}
/**
* The Groovy Script Engine does not (seem to?) expose the
* class a script is compiled to.
* So all we can do is GUESS!
*
* @param e
* @return
*/
public CodeLocation getLocationFromTrace(Throwable e) {
for (Throwable x = e; x != null; x = x.getCause()) {
for (StackTraceElement ste : x.getStackTrace()) {
if (couldBeScriptClass(ste.getClassName())) {
return translateLocation(ste.getLineNumber() - 1);
}
}
}
return null;
}
private static DialogScriptException wrapException(Throwable t, CodeLocation location) {
DialogScriptException dse = new DialogScriptException(t);
dse.sourceUrl = location.url;
dse.startLine = location.startLine + 1;
return dse;
}
}
| apache-2.0 |
Kevin-Lee/kommonlee-asm | src/main/java/org/elixirian/kommonlee/asm/util/AsmClasses.java | 11233 | /**
* This project is licensed under the Apache License, Version 2.0
* if the following condition is met:
* (otherwise it cannot be used by anyone but the author, Kevin, only)
*
* The original KommonLee project is owned by Lee, Seong Hyun (Kevin).
*
* -What does it mean to you?
* Nothing, unless you want to take the ownership of
* "the original project" (not yours or forked & modified one).
* You are free to use it for both non-commercial and commercial projects
* and free to modify it as the Apache License allows.
*
* -So why is this condition necessary?
* It is only to protect the original project (See the case of Java).
*
*
* Copyright 2009 Lee, Seong Hyun (Kevin)
*
* 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.elixirian.kommonlee.asm.util;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import org.elixirian.kommonlee.asm.exception.RuntimeClassNotFoundException;
import org.elixirian.kommonlee.exception.ExtraExceptionInformation;
import org.elixirian.kommonlee.lib3rd.asm5.Type;
import org.elixirian.kommonlee.util.CommonConstants;
/**
* <pre>
* ___ _____ _____
* / \/ / ______ __________________ ______ __ ______ / / ______ ______
* / / _/ __ // / / / / / /_/ __ // // // / / ___ \/ ___ \
* / \ / /_/ _/ _ _ / _ _ // /_/ _/ __ // /___/ _____/ _____/
* /____/\____\/_____//__//_//_/__//_//_/ /_____//___/ /__//________/\_____/ \_____/
* </pre>
*
* <pre>
* ___ _____ _____
* / \/ /_________ ___ ____ __ ______ / / ______ ______
* / / / ___ \ \/ //___// // / / / / ___ \/ ___ \
* / \ / _____/\ // // __ / / /___/ _____/ _____/
* /____/\____\\_____/ \__//___//___/ /__/ /________/\_____/ \_____/
* </pre>
*
* @author Lee, SeongHyun (Kevin)
* @version 0.0.1 (2010-06-22)
*/
public final class AsmClasses
{
public static final String CONSTRUCTOR_NAME = "<init>";
public static final String ASM_TYPE_ARRAY_AFFIX = "[]";
private final static Map<String, Class<?>> PRIMITIVE_TYPES;
private final static Map<String, Class<?>> KNOWN_ARRAY_TYPES;
private final static Map<String, Class<?>> COMMON_REFERENCE_TYPES;
static
{
Map<String, Class<?>> tempMap = new HashMap<String, Class<?>>(8);
tempMap.put(int.class.getName(), int.class);
tempMap.put(byte.class.getName(), byte.class);
tempMap.put(short.class.getName(), short.class);
tempMap.put(char.class.getName(), char.class);
tempMap.put(long.class.getName(), long.class);
tempMap.put(float.class.getName(), float.class);
tempMap.put(double.class.getName(), double.class);
tempMap.put(boolean.class.getName(), boolean.class);
PRIMITIVE_TYPES = Collections.unmodifiableMap(tempMap);
tempMap = new HashMap<String, Class<?>>();
tempMap.put(int.class.getName() + ASM_TYPE_ARRAY_AFFIX, int[].class);
tempMap.put(byte.class.getName() + ASM_TYPE_ARRAY_AFFIX, byte[].class);
tempMap.put(short.class.getName() + ASM_TYPE_ARRAY_AFFIX, short[].class);
tempMap.put(char.class.getName() + ASM_TYPE_ARRAY_AFFIX, char[].class);
tempMap.put(long.class.getName() + ASM_TYPE_ARRAY_AFFIX, long[].class);
tempMap.put(float.class.getName() + ASM_TYPE_ARRAY_AFFIX, float[].class);
tempMap.put(double.class.getName() + ASM_TYPE_ARRAY_AFFIX, double[].class);
tempMap.put(boolean.class.getName() + ASM_TYPE_ARRAY_AFFIX, boolean[].class);
tempMap.put(Integer.class.getName() + ASM_TYPE_ARRAY_AFFIX, Integer[].class);
tempMap.put(Byte.class.getName() + ASM_TYPE_ARRAY_AFFIX, Byte[].class);
tempMap.put(Short.class.getName() + ASM_TYPE_ARRAY_AFFIX, Short[].class);
tempMap.put(Character.class.getName() + ASM_TYPE_ARRAY_AFFIX, Character[].class);
tempMap.put(Long.class.getName() + ASM_TYPE_ARRAY_AFFIX, Long[].class);
tempMap.put(Float.class.getName() + ASM_TYPE_ARRAY_AFFIX, Float[].class);
tempMap.put(Double.class.getName() + ASM_TYPE_ARRAY_AFFIX, Double[].class);
tempMap.put(Boolean.class.getName() + ASM_TYPE_ARRAY_AFFIX, Boolean[].class);
tempMap.put(Number.class.getName() + ASM_TYPE_ARRAY_AFFIX, Number[].class);
tempMap.put(Object.class.getName() + ASM_TYPE_ARRAY_AFFIX, Object[].class);
tempMap.put(Class.class.getName() + ASM_TYPE_ARRAY_AFFIX, Class[].class);
tempMap.put(String[].class.getName(), String[].class);
KNOWN_ARRAY_TYPES = Collections.unmodifiableMap(tempMap);
tempMap = new HashMap<String, Class<?>>();
tempMap.put(Integer.class.getName(), Integer.class);
tempMap.put(Byte.class.getName(), Byte.class);
tempMap.put(Short.class.getName(), Short.class);
tempMap.put(Character.class.getName(), Character.class);
tempMap.put(Long.class.getName(), Long.class);
tempMap.put(Float.class.getName(), Float.class);
tempMap.put(Double.class.getName(), Double.class);
tempMap.put(Boolean.class.getName(), Boolean.class);
tempMap.put(String.class.getName(), String.class);
tempMap.put(BigInteger.class.getName(), BigInteger.class);
tempMap.put(BigDecimal.class.getName(), BigDecimal.class);
tempMap.put(Date.class.getName(), Date.class);
tempMap.put(Calendar.class.getName(), Calendar.class);
tempMap.put(Object.class.getName(), Object.class);
tempMap.put(Class.class.getName(), Class.class);
COMMON_REFERENCE_TYPES = Collections.unmodifiableMap(tempMap);
}
private AsmClasses() throws IllegalAccessException
{
throw new IllegalAccessException(getClass().getName() + CommonConstants.CANNOT_BE_INSTANTIATED);
}
public static Class<?> getClassByType(final Type memberType, final Class<?> theClass)
{
return getClassByName(memberType.getClassName(), theClass.getClassLoader());
}
public static Class<?> getClassByType(final Type memberType, final Class<?> theClass,
final ConcurrentMap<String, Class<?>> otherKnownTypesMap)
{
return getClassByName(memberType.getClassName(), theClass.getClassLoader(), otherKnownTypesMap);
}
private static Class<?> findKnownType(final String className)
{
Class<?> memberClass = PRIMITIVE_TYPES.get(className);
if (null != memberClass)
return memberClass;
memberClass = COMMON_REFERENCE_TYPES.get(className);
if (null != memberClass)
return memberClass;
return KNOWN_ARRAY_TYPES.get(className);
}
private static Class<?> findKnownType(final String className, final Map<String, Class<?>> externalTypeCacheMap)
{
final Class<?> memberClass = findKnownType(className);
if (null == memberClass)
{
return externalTypeCacheMap.get(className);
}
return memberClass;
}
public static Class<?> getClassByName(final String className, final ClassLoader classLoader)
{
Class<?> memberClass = findKnownType(className);
if (null != memberClass)
{
return memberClass;
}
if (className.endsWith(ASM_TYPE_ARRAY_AFFIX))
{
memberClass =
getClassByName(className.substring(0, className.length() - ASM_TYPE_ARRAY_AFFIX.length()), classLoader);
return Array.newInstance(memberClass, 0)
.getClass();
}
try
{
ClassLoader classLoaderToUse = (null == classLoader ? getCurrentThreadContextClassLoader() : classLoader);
if (null == classLoaderToUse)
{
classLoaderToUse = AsmClasses.class.getClassLoader();
}
return classLoaderToUse.loadClass(className);
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
throw new UnsupportedOperationException(e);
}
}
public static Class<?> getClassByName(final String className, final ClassLoader classLoader,
final ConcurrentMap<String, Class<?>> externalTypeCacheMap)
{
Class<?> memberClass = findKnownType(className, externalTypeCacheMap);
if (null != memberClass)
{
return memberClass;
}
if (className.endsWith(ASM_TYPE_ARRAY_AFFIX))
{
memberClass =
getClassByName(className.substring(0, className.length() - ASM_TYPE_ARRAY_AFFIX.length()), classLoader,
externalTypeCacheMap);
return Array.newInstance(memberClass, 0)
.getClass();
}
try
{
ClassLoader classLoaderToUse = (null == classLoader ? getCurrentThreadContextClassLoader() : classLoader);
if (null == classLoader)
{
classLoaderToUse = AsmClasses.class.getClassLoader();
}
final Class<?> theType = classLoaderToUse.loadClass(className);
final Class<?> theTypeFromCache = externalTypeCacheMap.putIfAbsent(className, theType);
return (null == theTypeFromCache ? theType : theTypeFromCache);
}
catch (final ClassNotFoundException e)
{
e.printStackTrace();
throw new RuntimeClassNotFoundException(e.getMessage(), e, ExtraExceptionInformation.builder()
.addParamInfo(String.class, "className", className)
.addParamInfo(ClassLoader.class, "classLoader", classLoader)
.addParamInfo(ConcurrentMap.class, "externalTypeCacheMap", externalTypeCacheMap)
.possibleReason(
"failed when doing final Class<?> theType = classLoaderToUse.loadClass(className);\n"
+ "The class with the className is not found.")
.build());
}
}
public static ClassLoader getCurrentThreadContextClassLoader()
{
return Thread.currentThread()
.getContextClassLoader();
}
public static InputStream getResourceAsStream(final Class<?> theClass)
{
return theClass.getResourceAsStream("/" + theClass.getName()
.replace('.', '/') + ".class");
}
/**
* Each slot in the local variables and operand stack parts can hold any Java value, except long and double values.
* These values require two slots.
*
* @param type
* @return
*/
public static int calculateLocalVariableSlotSize(final Type type)
{
return (Type.LONG_TYPE == type || Type.DOUBLE_TYPE == type ? 2 : 1);
}
public static int[] calculateLocalVariableSlotIndices(final boolean isStaticMethod, final Type[] params)
{
final int[] localVariableSlotIndices = new int[params.length];
int next = isStaticMethod ? 0 : 1;
for (int i = 0, size = params.length; i < size; i++)
{
localVariableSlotIndices[i] = next;
next += calculateLocalVariableSlotSize(params[i]);
}
return localVariableSlotIndices;
}
}
| apache-2.0 |
dbeat/Optics | src/main/java/com/dbeat/rayCurvature/Ray.java | 2191 | package com.dbeat.rayCurvature;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.ode.FirstOrderDifferentialEquations;
import org.apache.commons.math3.ode.FirstOrderIntegrator;
import org.apache.commons.math3.ode.nonstiff.ClassicalRungeKuttaIntegrator;
// see Landau & Lifschitz Vol-2 The Classical Theory of Fields
class Ray implements FirstOrderDifferentialEquations {
private double c;
private double n;
public Ray(double n) {
this.c = 3e8;
this.n = n;
}
public void computeDerivatives(double t, double[] y, double[] yDot)
throws MaxCountExceededException, DimensionMismatchException {
// y[0], y[1], and y[2] = kx, ky, kz and y[3], y[4], and y[5] = qx, qy, qz
double normk = Math.sqrt(Math.pow(y[0],2)+Math.pow(y[1],2)+Math.pow(y[2],2));
yDot[0] = 0.0;
yDot[1] = 0.0;
yDot[2] = 0.0;
yDot[3] = c /(n * normk) * y[0];
yDot[4] = c /(n * normk) * y[1];
yDot[5] = c /(n * normk) * y[2];
}
public int getDimension() {
// TODO Auto-generated method stub
return 6;
}
public static void main(String[] args) {
FirstOrderIntegrator dp853 = new ClassicalRungeKuttaIntegrator(1.0e-13);
FirstOrderDifferentialEquations ode = new Ray( 1.0 );
double c = 3.0e8;
double n = 1.0;
double lambda0 = 660.0e-9;
double omega = 2*Math.PI*c/(n*lambda0);
double[] L0 = new double[] {1.0, 0.0, 0.0};
double normL0 = Math.sqrt(Math.pow(L0[0],2)+Math.pow(L0[1],2)+Math.pow(L0[2],2));
double[] k0 = new double[] {omega*n*L0[0]/(c*normL0),omega*n*L0[1]/(c*normL0),omega*n*L0[2]/(c*normL0)};
double[] q0 = new double[] {0.0, 0.0, 0.0};
double[] y = new double[] { k0[0], k0[1], k0[2], q0[0], q0[1], q0[2] }; // initial state
double t = 1.0e-9;
dp853.integrate(ode, 0.0, y, t, y); // now y contains final state at time t=1.0e-9
System.out.println("kx: "+y[0]+" ky: "+y[1]+" kz: "+y[2]); // should give 9.5200e6 rad/m, 0.0 rad/m, 0.0 rad/m
System.out.println("qx: "+y[3]+" qy: "+y[4]+" qz: "+y[5]); // should give 0.29979 m, 0.0 m, 0.0 m
}
}
| apache-2.0 |
srirampatil/CombiningTree | src/SharedCountingFrame.java | 6872 | import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SharedCountingFrame extends JFrame implements IAtomicCounter,
ActionListener {
private final int WIDTH = 800;
private final int HEIGHT = 600;
private NodePanel[] nodePanels;
private NodePanel[] leaf = null;
private int panelCount;
public SharedCountingFrame(int width) {
this.setLayout(null);
setSize(WIDTH, HEIGHT);
int midX = WIDTH / 2;
int midY = HEIGHT / 2;
nodePanels = new NodePanel[width];
panelCount = 0;
NodePanel root = new NodePanel(20, 10);
int nodeWidthMid = root.getWidth() / 2;
root.setBounds(midX - nodeWidthMid, 10, root.getWidth(),
root.getHeight());
this.add(root);
nodePanels[panelCount++] = root;
NodePanel leftChild = new NodePanel(20, 10, root);
leftChild.setBounds(midX / 2 - nodeWidthMid, 200, leftChild.getWidth(),
leftChild.getHeight());
this.add(leftChild);
nodePanels[panelCount++] = leftChild;
NodePanel rightChild = new NodePanel(20, 10, root);
rightChild.setBounds(midX + midX / 2 - nodeWidthMid, 200,
rightChild.getWidth(), rightChild.getHeight());
this.add(rightChild);
nodePanels[panelCount++] = rightChild;
NodePanel llChild = new NodePanel(20, 10, leftChild);
llChild.setBounds(midX / 4 - nodeWidthMid, 400, llChild.getWidth(),
llChild.getHeight());
this.add(llChild);
nodePanels[panelCount++] = llChild;
NodePanel lrChild = new NodePanel(20, 10, leftChild);
lrChild.setBounds(midX / 2 + midX / 4 - nodeWidthMid, 400,
lrChild.getWidth(), lrChild.getHeight());
this.add(lrChild);
nodePanels[panelCount++] = lrChild;
NodePanel rlChild = new NodePanel(20, 10, rightChild);
rlChild.setBounds(midX + midX / 4 - nodeWidthMid, 400,
rlChild.getWidth(), rlChild.getHeight());
this.add(rlChild);
nodePanels[panelCount++] = rlChild;
NodePanel rrChild = new NodePanel(20, 10, rightChild);
rrChild.setBounds(midX + midX / 2 + midX / 4 - nodeWidthMid, 400,
rrChild.getWidth(), rrChild.getHeight());
this.add(rrChild);
nodePanels[panelCount++] = rrChild;
leaf = new NodePanel[(width + 1) / 2];
for (int i = 0; i < leaf.length; i++)
leaf[i] = nodePanels[panelCount - i - 1];
JButton btn = new JButton();
btn.setBounds(midX - 40, HEIGHT - 50 - OFFSET, 80, 30);
btn.setText("Next");
btn.addActionListener(this);
this.add(btn);
repaint();
}
private final int OFFSET = 28;
private Stroke dashedStroke = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL, 0, new float[] { 9 }, 0);
private Stroke defaultStroke = new BasicStroke();
@Override
public void paint(Graphics g) {
super.paint(g);
for (int i = 1; i < panelCount; i++) {
NodePanel current = nodePanels[i];
NodePanel parent = nodePanels[(i - 1) / 2];
g.drawLine(parent.getX() + parent.getWidth() / 2, parent.getY()
+ parent.getHeight() + OFFSET,
current.getX() + current.getWidth() / 2, current.getY()
+ 10 + OFFSET);
}
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.setStroke(dashedStroke);
for (String key : paths.keySet()) {
PrecombinePath path = paths.get(key);
if(path.startNode == path.endNode)
g2d.drawLine(path.endNode.getX() + path.endNode.getWidth() / 2,
path.endNode.getY() + path.endNode.getHeight() + OFFSET + 30,
path.endNode.getX() + path.endNode.getWidth() / 2,
path.endNode.getY() + path.endNode.getHeight() + OFFSET);
else
g2d.drawLine(path.endNode.getX() + path.endNode.getWidth() / 2,
path.endNode.getY() + path.endNode.getHeight() + OFFSET,
path.startNode.getX() + path.startNode.getWidth() / 2,
path.startNode.getY() + 10 + OFFSET);
}
g2d.setColor(Color.BLACK);
g2d.setStroke(defaultStroke);
}
boolean performNext = false;
private synchronized void waitForEvent() {
while (!performNext) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
performNext = false;
}
Map<String, PrecombinePath> paths = new HashMap<String, SharedCountingFrame.PrecombinePath>();
private class PrecombinePath {
NodePanel startNode;
NodePanel endNode;
}
public int getAndIncrement() throws PanicException {
waitForEvent();
Stack<NodePanel> nodeStack = new Stack<NodePanel>();
NodePanel myLeaf = leaf[((CountingThread) Thread.currentThread())
.getThreadId() / 2];
NodePanel node = myLeaf;
PrecombinePath path = new PrecombinePath();
path.startNode = node;
/* pre-combining phase */
while (node.precombine()) {
node.setThreadName(Thread.currentThread().getName());
node = node.graphicalParent;
}
path.endNode = node;
paths.put(Thread.currentThread().getName(), path);
repaint();
NodePanel stopNode = node;
node.setThreadName(Thread.currentThread().getName());
waitForEvent();
/* combining phase */
node = myLeaf;
int combined = 1;
while (node != stopNode) {
combined = node.combine(combined);
nodeStack.push(node);
node = node.graphicalParent;
}
waitForEvent();
/* operation phase */
int prior = stopNode.op(combined);
/* distribution phase */
while (!nodeStack.isEmpty()) {
node = nodeStack.pop();
if (node.threadName.equals(Thread.currentThread().getName()))
node.setThreadName("");
node.distribute(prior);
}
if (stopNode.threadName.equals(Thread.currentThread().getName()))
stopNode.setThreadName("");
return prior;
}
public static void main(String[] args) {
SharedCountingFrame frame = new SharedCountingFrame(8);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
List<CountingThread> threadList = new ArrayList<CountingThread>();
char tName = 'A';
Set<Integer> threadIdSet = new HashSet<Integer>();
Random num = new Random();
while (true) {
int threadId = num.nextInt(5) + 1;
if (threadIdSet.add(threadId)) {
CountingThread thread = new CountingThread(frame, threadId);
char threadName = (char) (tName + (threadId - 1));
thread.setName(threadName + "");
threadList.add(thread);
thread.start();
}
if (threadIdSet.size() == 5)
break;
}
for (CountingThread t : threadList) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void setPerformNext(boolean value) {
performNext = value;
if (performNext)
notifyAll();
}
@Override
public void actionPerformed(ActionEvent e) {
setPerformNext(true);
}
}
| apache-2.0 |
lukecampbell/webtest | src/test/java/com/canoo/webtest/extension/SelectLinesFilterTest.java | 2972 | // Copyright © 2006-2007 ASERT. Released under the Canoo Webtest license.
package com.canoo.webtest.extension;
import com.canoo.webtest.engine.StepExecutionException;
import com.canoo.webtest.self.TestBlock;
import com.canoo.webtest.self.ThrowAssert;
import com.canoo.webtest.steps.AbstractFilter;
import com.canoo.webtest.steps.Step;
/**
* Test for {@link MatchLinesFilter}.
*
* @author Paul King
*/
public class SelectLinesFilterTest extends BaseFilterTestCase
{
private static final String LS = System.getProperty("line.separator");
private static final String SOURCE = "The quick" + LS + "brown fox" + LS + "jumped over the" + LS + "lazy dog" + LS;
private static final String START_REGEX_1 = ".*quick.*";
private static final String STOP_REGEX_1 = ".*over.*";
private static final String START_REGEX_2 = "[^e]*e.*";
private static final String STOP_REGEX_2 = "[^ ]* .*";
private static final String EXPECTED_1A = "The quick" + LS + "brown fox" + LS;
private static final String EXPECTED_1B = "brown fox" + LS + "jumped over the" + LS;
private static final String EXPECTED_1C = "The quick" + LS + "lazy dog" + LS;
private static final String EXPECTED_1D = "The quick" + LS;
private static final String EXPECTED_1E = "The quick" + LS + "jumped over the" + LS;
private SelectLinesFilter fFilter;
protected void setUp() throws Exception
{
super.setUp();
fFilter = (SelectLinesFilter) getStep();
fFilter.setStartRegex(START_REGEX_1);
fFilter.setStopRegex(STOP_REGEX_1);
fFilter.setIncludeStart("true");
fFilter.setIncludeStop("false");
checkFilter(EXPECTED_1A, SOURCE);
fFilter.setIncludeStart("false");
fFilter.setIncludeStop("true");
checkFilter(EXPECTED_1B, SOURCE);
fFilter.setRemove("true");
checkFilter(EXPECTED_1C, SOURCE);
fFilter.setStartRegex(null);
fFilter.setIncludeStart(null);
fFilter.setRemove(null);
fFilter.setIncludeStop("false");
checkFilter(EXPECTED_1A, SOURCE);
fFilter.setStartRegex(START_REGEX_2);
fFilter.setStopRegex(STOP_REGEX_2);
checkFilter(EXPECTED_1D, SOURCE);
fFilter.setRepeat("true");
checkFilter(EXPECTED_1E, SOURCE);
}
public void testFailsIfInsufficientParams() {
final Step step = createAndConfigureStep();
final String msg = ThrowAssert.assertThrows(StepExecutionException.class, new TestBlock() {
public void call() throws Throwable {
step.execute();
}
});
assertEquals("One of 'startRegex' or 'stopRegex' must be set!", msg);
}
public void testFailsIfNoResponse() {
fFilter.setStartRegex("dummy");
checkFailsIfNoResponse();
}
protected AbstractFilter getFilter() {
return fFilter;
}
protected Step createStep() {
return new SelectLinesFilter();
}
}
| apache-2.0 |
paulrzcz/montecarlo | src/main/java/cz/paulrz/montecarlo/estimator/FokkerOperator.java | 2645 | package cz.paulrz.montecarlo.estimator;
import cz.paulrz.montecarlo.single.StochasticProcess1D;
public class FokkerOperator implements ImplicitStencil {
private final int _size;
private final double _dt;
private final double _dx;
private final double _alpha;
private final double _beta;
private final StochasticProcess1D _process;
private final Mesh _mesh;
public FokkerOperator(StochasticProcess1D process1D, Mesh mesh) {
_size = mesh.sizeX;
_process = process1D;
_dt = mesh.dt;
_dx = mesh.dx;
_alpha = _dt/_dx/4;
_beta = _dt/_dx/_dx/2;
_mesh = mesh;
}
public TridiagonalOperator createOperator(double t) {
final TridiagonalOperator result = new TridiagonalOperator(_size);
double t1 = t + _dt;
result.setFirstRow(
-(2*ksi(t1, _mesh.xStart) + 1),
_beta * ksi(t1, _mesh.getX(1)) - _alpha*_process.drift(t1, _mesh.getX(1))
);
result.setLastRow(
_alpha*_process.drift(t1, _mesh.xEnd - _dx) + _beta*ksi(t1, _mesh.xEnd - _dx),
-(2*ksi(t1, _mesh.xEnd) + 1)
);
for(int i=1; i < _size -1 ; ++i) {
final double xn = _mesh.getX(i - 1);
final double x0 = _mesh.getX(i);
final double xp = _mesh.getX(i+1);
result.setMidRow(
i,
_alpha*_process.drift(t1, xn) + _beta*ksi(t1, xn),
-(2*ksi(t1, x0) + 1),
_beta * ksi(t1, xp) - _alpha*_process.drift(t1, xp)
);
}
return result;
}
public double[] createRhs(double[] f, double t) {
final double[] result = new double[_size];
result[0] = rightHandFunction(t, _mesh.xStart, 0.0, f[0], f[1]);
result[_size - 1] = rightHandFunction(t, _mesh.xEnd, f[_size-2], f[_size-1], 0.0);
for(int i=1; i<_size-1; ++i) {
result[i] = rightHandFunction(t, _mesh.getX(i), f[i-1], f[i], f[i+1]);
}
return result;
}
private double rightHandFunction(double t, double x, double fn, double f0, double fp) {
final double xp = x + _dx;
final double xn = x - _dx;
final double dmf = mu(t, xp)*fp - mu(t, xn) * fn;
final double dxf = ksi(t, xp)*fp - 2*ksi(t, x)*f0 + ksi(t, xn)*fn;
return _alpha*dmf - _beta*dxf - f0;
}
private double mu(double t, double x) {
return _process.drift(t, x);
}
private double ksi(double t, double x) {
final double v = _process.diffusion(t, x);
return v*v/2;
}
}
| apache-2.0 |
dump247/aws-sdk-java | aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/transform/ListTaskDefinitionsResultJsonUnmarshaller.java | 3326 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ecs.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.ecs.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ListTaskDefinitionsResult JSON Unmarshaller
*/
public class ListTaskDefinitionsResultJsonUnmarshaller implements
Unmarshaller<ListTaskDefinitionsResult, JsonUnmarshallerContext> {
public ListTaskDefinitionsResult unmarshall(JsonUnmarshallerContext context)
throws Exception {
ListTaskDefinitionsResult listTaskDefinitionsResult = new ListTaskDefinitionsResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("taskDefinitionArns", targetDepth)) {
context.nextToken();
listTaskDefinitionsResult
.setTaskDefinitionArns(new ListUnmarshaller<String>(
StringJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("nextToken", targetDepth)) {
context.nextToken();
listTaskDefinitionsResult
.setNextToken(StringJsonUnmarshaller.getInstance()
.unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return listTaskDefinitionsResult;
}
private static ListTaskDefinitionsResultJsonUnmarshaller instance;
public static ListTaskDefinitionsResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ListTaskDefinitionsResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
sudosurootdev/SeriesGuide | SeriesGuide/src/main/java/com/battlelancer/seriesguide/ui/BaseTopShowsActivity.java | 2041 |
/*
* Copyright 2014 Uwe Trottmann
*
* 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.battlelancer.seriesguide.ui;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.battlelancer.seriesguide.R;
import android.content.Intent;
/**
* Adds action items specific to top show activities.
*/
public abstract class BaseTopShowsActivity extends BaseTopActivity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean isLightTheme = SeriesGuidePreferences.THEME == R.style.SeriesGuideThemeLight;
getSupportMenuInflater()
.inflate(isLightTheme ? R.menu.base_show_menu_light : R.menu.base_show_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menu_checkin) {
startActivity(new Intent(this, CheckinActivity.class));
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
fireTrackerEvent("Check-In");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean isDrawerOpen = isDrawerOpen();
menu.findItem(R.id.menu_checkin).setVisible(!isDrawerOpen);
return super.onPrepareOptionsMenu(menu);
}
}
| apache-2.0 |
dremio/dremio-oss | services/datastore/src/main/java/com/dremio/datastore/api/options/VersionOption.java | 3823 | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.datastore.api.options;
import org.immutables.value.Value;
import com.dremio.datastore.RemoteDataStoreProtobuf.PutOptionInfo;
import com.dremio.datastore.RemoteDataStoreProtobuf.PutOptionType;
import com.dremio.datastore.api.Document;
import com.dremio.datastore.api.KVStore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* VersionOption for specifying version tag for optimistic concurrency control. It is used as an
* option in PUT and DELETE KVStore operations. PUT and DELETE operations would fail if the version
* of the target document has been updated since the tag provided by this VersionOption.
*/
@JsonDeserialize(builder = ImmutableVersionOption.Builder.class)
@Value.Immutable
public interface VersionOption extends KVStore.PutOption, KVStore.DeleteOption {
/**
* Gets the version tag.
* @return the version tag associated with this option object.
*/
String getTag();
@Override
default PutOptionInfo getPutOptionInfo() {
return PutOptionInfo.newBuilder()
.setType(PutOptionType.VERSION)
.setParameter(getTag())
.build();
}
static VersionOption from(Document<?, ?> doc) {
Preconditions.checkArgument(doc.getTag() != null);
return new ImmutableVersionOption.Builder().setTag(doc.getTag()).build();
}
static KVStore.PutOption getTTLOption(final int timeout_sec) {
return new KVStore.PutOption() {
@Override
public PutOptionInfo getPutOptionInfo() {
return PutOptionInfo.newBuilder().setType(PutOptionType.TTL).setTimeoutSec(timeout_sec).build();
}
};
}
/**
* Stores information about the VersionOption parsed from an array of KVStoreOptions.
*/
class TagInfo {
private final boolean hasVersionOption;
private final boolean hasCreateOption;
private final String tag;
@VisibleForTesting
public TagInfo(boolean hasVersionOption, boolean hasCreateOption, String tag) {
this.hasVersionOption = hasVersionOption;
this.hasCreateOption = hasCreateOption;
this.tag = tag;
}
public boolean hasVersionOption() {
return hasVersionOption;
}
public boolean hasCreateOption() {
return hasCreateOption;
}
public String getTag() {
return tag;
}
}
/**
* Retrieve the version option.
*/
static TagInfo getTagInfo(KVStore.KVStoreOption... options) {
KVStoreOptionUtility.validateOptions(options);
if (null == options || options.length == 0) {
return new TagInfo(false, false, null);
}
for (KVStore.KVStoreOption option: options) {
if (option instanceof VersionOption) {
return new TagInfo(true, false, ((VersionOption) option).getTag());
} else if (option == CREATE) {
// XXX: This is kinda gross. Create is not a version option, yet we collapse it down to this piece of information.
// We should work to deprecate/eliminate this class, or at the very least stop making it represent a Create.
return new TagInfo(true, true, null);
}
}
return new TagInfo(false, false, null);
}
}
| apache-2.0 |
consulo/consulo-csharp | csharp-impl/src/main/java/consulo/csharp/ide/actions/generate/GeneratePropertyAction.java | 2357 | /*
* Copyright 2013-2017 consulo.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.csharp.ide.actions.generate;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import consulo.annotation.access.RequiredReadAction;
import consulo.csharp.lang.psi.CSharpTypeDeclaration;
import consulo.csharp.lang.psi.impl.source.CSharpPsiUtilImpl;
import consulo.dotnet.psi.DotNetFieldDeclaration;
import consulo.dotnet.psi.DotNetNamedElement;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
/**
* @author VISTALL
* @since 24.07.2015
*/
public class GeneratePropertyAction extends CSharpGenerateAction
{
public GeneratePropertyAction()
{
this(new GeneratePropertyHandler(false));
}
public GeneratePropertyAction(CodeInsightActionHandler handler)
{
super(handler);
}
@Override
@RequiredReadAction
protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file)
{
CSharpTypeDeclaration typeDeclaration = findTypeDeclaration(editor, file);
return typeDeclaration != null && !getFields(typeDeclaration).isEmpty();
}
@RequiredReadAction
public static List<DotNetFieldDeclaration> getFields(CSharpTypeDeclaration typeDeclaration)
{
List<DotNetFieldDeclaration> fieldDeclarations = new ArrayList<>(5);
for(DotNetNamedElement dotNetNamedElement : typeDeclaration.getMembers())
{
if(dotNetNamedElement instanceof DotNetFieldDeclaration)
{
DotNetFieldDeclaration fieldDeclaration = (DotNetFieldDeclaration) dotNetNamedElement;
if(CSharpPsiUtilImpl.isNullOrEmpty(fieldDeclaration))
{
continue;
}
fieldDeclarations.add(fieldDeclaration);
}
}
return fieldDeclarations;
}
}
| apache-2.0 |
ServerStarted/cat | cat-home/src/main/java/com/dianping/cat/report/page/cdn/graph/CdnReportConvertor.java | 2707 | package com.dianping.cat.report.page.cdn.graph;
import com.dianping.cat.consumer.metric.model.entity.MetricItem;
import com.dianping.cat.consumer.metric.model.entity.MetricReport;
import com.dianping.cat.consumer.metric.model.entity.Segment;
import com.dianping.cat.consumer.metric.model.transform.BaseVisitor;
import com.dianping.cat.service.IpService;
import com.dianping.cat.service.IpService.IpInfo;
public class CdnReportConvertor extends BaseVisitor {
private IpService m_ipService;
private MetricReport m_report;
private String m_cdn;
private String m_province;
private String m_city;
private static final String ALL = "ALL";
public CdnReportConvertor(IpService ipService) {
m_ipService = ipService;
}
private String filterAndConvert(String cdn, String sip) {
if (m_cdn.equals(ALL)) {
return cdn;
} else if (!m_cdn.equals(cdn)) {
return null;
}
IpInfo ipInfo = m_ipService.findIpInfoByString(sip);
String province = ipInfo.getProvince();
String city = ipInfo.getCity();
if (m_province.equals(ALL)) {
return province;
} else if (!m_province.equals(province)) {
return null;
}
if (m_city.equals(ALL)) {
return city;
} else if (!m_city.equals(city)) {
return null;
}
return sip;
}
public MetricReport getReport() {
return m_report;
}
public void mergeMetricItem(MetricItem from, MetricItem to) {
for (Segment temp : to.getSegments().values()) {
Segment target = from.findOrCreateSegment(temp.getId());
mergeSegment(target, temp);
}
}
protected void mergeSegment(Segment old, Segment point) {
old.setCount(old.getCount() + point.getCount());
old.setSum(old.getSum() + point.getSum());
if (old.getCount() > 0) {
old.setAvg(old.getSum() / old.getCount());
}
}
public CdnReportConvertor setCdn(String cdn) {
m_cdn = cdn;
return this;
}
public CdnReportConvertor setCity(String city) {
m_city = city;
return this;
}
public CdnReportConvertor setProvince(String province) {
m_province = province;
return this;
}
@Override
public void visitMetricItem(MetricItem metricItem) {
try {
String id = metricItem.getId();
String[] temp = id.split(":");
String cdn = temp[2];
String sip = temp[3];
String key = filterAndConvert(cdn, sip);
if (key != null) {
MetricItem item = m_report.findOrCreateMetricItem(key);
mergeMetricItem(item, metricItem);
}
} catch (Exception e) {
}
}
@Override
public void visitMetricReport(MetricReport metricReport) {
m_report = new MetricReport(metricReport.getProduct());
super.visitMetricReport(metricReport);
}
@Override
public void visitSegment(Segment segment) {
super.visitSegment(segment);
}
}
| apache-2.0 |
airbnb/lottie-android | lottie/src/main/java/com/airbnb/lottie/network/DefaultLottieFetchResult.java | 1866 | package com.airbnb.lottie.network;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.airbnb.lottie.utils.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
public class DefaultLottieFetchResult implements LottieFetchResult {
@NonNull
private final HttpURLConnection connection;
public DefaultLottieFetchResult(@NonNull HttpURLConnection connection) {
this.connection = connection;
}
@Override public boolean isSuccessful() {
try {
return connection.getResponseCode() / 100 == 2;
} catch (IOException e) {
return false;
}
}
@NonNull @Override public InputStream bodyByteStream() throws IOException {
return connection.getInputStream();
}
@Nullable @Override public String contentType() {
return connection.getContentType();
}
@Nullable @Override public String error() {
try {
return isSuccessful() ? null :
"Unable to fetch " + connection.getURL() + ". Failed with " + connection.getResponseCode() + "\n" + getErrorFromConnection(connection);
} catch (IOException e) {
Logger.warning("get error failed ", e);
return e.getMessage();
}
}
@Override public void close() {
connection.disconnect();
}
private String getErrorFromConnection(HttpURLConnection connection) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
StringBuilder error = new StringBuilder();
String line;
try {
while ((line = r.readLine()) != null) {
error.append(line).append('\n');
}
} finally {
try {
r.close();
} catch (Exception e) {
// Do nothing.
}
}
return error.toString();
}
}
| apache-2.0 |
equella/Equella | Source/Plugins/Core/com.equella.core/src/com/tle/web/workflow/tasks/WorkflowSelection.java | 1175 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.web.workflow.tasks;
import com.tle.common.workflow.Workflow;
import com.tle.web.sections.SectionId;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.TreeIndexed;
@TreeIndexed
public interface WorkflowSelection extends SectionId {
Workflow getWorkflow(SectionInfo info);
void setWorkflow(SectionInfo info, Workflow workflow);
}
| apache-2.0 |
MichaelChansn/SSM | ssm/src/main/java/com/ks/ssm/controller/ForgetPasswordController.java | 4264 | package com.ks.ssm.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.code.kaptcha.Constants;
import com.ks.ssm.constant.RetInfos;
import com.ks.ssm.domain.User;
import com.ks.ssm.form.domain.ForgetPassword;
import com.ks.ssm.form.domain.SetNewPassword;
import com.ks.ssm.interceptors.LoginCheck;
import com.ks.ssm.interceptors.TokenCheck;
import com.ks.ssm.service.IUserService;
import com.ks.ssm.service.ISendEmailService;
import com.ks.ssm.utils.CommonUtils;
import com.ks.ssm.utils.SSMUtils;
@Controller
@RequestMapping("/user")
public class ForgetPasswordController {
@Resource
private IUserService userService;
@Resource
private ISendEmailService sendEmailService;
@RequestMapping(value = "/forgetPassword", method = RequestMethod.GET)
@LoginCheck(saveInfo=true,autoLogin = true)
@TokenCheck(generateToken=true)
public String forgetPasswordGet(HttpServletRequest request, HttpSession session, Model model) {
String token=request.getParameter("token");
if(!CommonUtils.isBlank(token))
{
if(SSMUtils.verifyToken(token, userService,null)){
//把token带下去,用于提交验证
model.addAttribute(RetInfos.FORGET_PASSWORD_TOKEN,token);
}
}
return "forgetPassword";
}
@RequestMapping(value = "/forgetPassword", method = RequestMethod.POST)
@LoginCheck(saveInfo=true,autoLogin = true)
@TokenCheck(check=true)
public String forgetPasswordPost(HttpServletRequest request, HttpSession session, Model model,
@ModelAttribute("forgetPassword") @Valid ForgetPassword forgetPassword, BindingResult result) {
String retWeb = "forgetPassword";
do {
String email=forgetPassword.getEmail();
model.addAttribute("email", email);
if (!result.hasErrors()) {
String captchaInSession = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
if(forgetPassword.getCaptcha()==null || !forgetPassword.getCaptcha().equals(captchaInSession))
{
model.addAttribute(RetInfos.ERROR, RetInfos.FORGET_PASSWORD_ERROR_MSG2);
break;
}
User user=userService.selectByEmail(email);
if(user==null){
model.addAttribute(RetInfos.ERROR, RetInfos.FORGET_PASSWORD_ERROR_MSG);
}
else
{
SSMUtils.generateForgetPasswordToken(request,session, userService, sendEmailService, user);
model.addAttribute(RetInfos.SUCCESS, RetInfos.FORGET_PASSWORD_SUCCESS_MSG);
}
break;
} else {
//model.addAttribute(RetInfos.ERROR, result.getAllErrors());
break;
}
} while (false);
return retWeb;
}
@RequestMapping(value = "/setNewPassword", method = RequestMethod.POST)
@LoginCheck(autoLogin = true)
@TokenCheck(check=true)
public String setNewPasswordPost(HttpServletRequest request, HttpSession session, Model model,
@ModelAttribute("setNewPassword") @Valid SetNewPassword setNewPassword, BindingResult result) {
String retWeb = "forgetPassword";
model.addAttribute(RetInfos.FORGET_PASSWORD_TOKEN,setNewPassword.getToken());
do {
if (!result.hasErrors())
{
String captchaInSession = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
if(setNewPassword.getCaptcha()==null || !setNewPassword.getCaptcha().equals(captchaInSession))
{
model.addAttribute(RetInfos.ERROR, RetInfos.FORGET_PASSWORD_ERROR_MSG2);
break;
}
if(!setNewPassword.isSamePassword())
{
model.addAttribute(RetInfos.ERROR,RetInfos.PASSWORD_NOT_SAME);
break;
}
if(SSMUtils.verifyTokenAndSaveNewPassword(setNewPassword.getToken(), userService,setNewPassword.getNewPassword()))
{
model.addAttribute(RetInfos.SUCCESS,RetInfos.SET_NEW_PASSWORD_SUCCESS_MSG);
break;
}
}
else
{
//model.addAttribute(RetInfos.ERROR, result.getAllErrors());
break;
}
} while (false);
return retWeb;
}
}
| apache-2.0 |
SES-fortiss/SmartGridCoSimulation | projects/previousProjects/strategyNoHierarchy-V0.1/src/test/java/tests/testRandom.java | 1177 | /*
* Copyright (c) 2011-2015, fortiss GmbH.
* Licensed under the Apache License, Version 2.0.
*
* Use, modification and distribution are subject to the terms specified
* in the accompanying license file LICENSE.txt located at the root directory
* of this software distribution.
*/
package tests;
import java.util.Random;
import org.junit.Test;
public class testRandom {
@Test
public void testRandomGaussian(){
Random r = new Random();
double x = 0;
for (int i = 0; i<10000000; i++) {
double y = r.nextGaussian();
x = (y<x) ? y : x;
}
System.out.println(x);
}
@Test
public void testRandomInt(){
Random r = new Random();
int x = 0;
for (int i = 0; i<10000000; i++) {
int y = r.nextInt();
x = (y<x) ? y : x;
}
System.out.println(x);
}
@Test
public void testRandomDouble(){
Random r = new Random();
double x = 0;
for (int i = 0; i<10000000; i++) {
double y = r.nextDouble();
x = (y<x) ? y : x;
}
System.out.println(x);
}
@Test
public void testMathRandom(){
double x = 0;
for (int i = 0; i<10000000; i++) {
double y = Math.random();
x = (y<x) ? y : x;
}
System.out.println(x);
}
}
| apache-2.0 |
iyzico/google-cloud-java | google-cloud-vision/src/main/java/com/iyzipay/google/cloud/vision/model/Image.java | 432 | package com.iyzipay.google.cloud.vision.model;
public class Image {
private String content;
private ImageSource source;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public ImageSource getSource() {
return source;
}
public void setSource(ImageSource source) {
this.source = source;
}
}
| apache-2.0 |
chirankavinda123/identity-inbound-auth-oauth | components/org.wso2.carbon.identity.oauth.dcr/src/main/java/org/wso2/carbon/identity/oauth/dcr/DCRClientException.java | 1313 | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.oauth.dcr;
import org.wso2.carbon.identity.application.authentication.framework.inbound.FrameworkClientException;
public class DCRClientException extends FrameworkClientException {
public DCRClientException(String message) {
super(message);
}
public DCRClientException(String errorCode, String message) {
super(errorCode, message);
}
public DCRClientException(String message, Throwable cause) {
super(message, cause);
}
public DCRClientException(String errorCode, String message, Throwable cause) {
super(errorCode, message, cause);
}
}
| apache-2.0 |
PJayGroup/restful-webservices-examples | restfulapp1/src/main/java/org/pjaygroup/restfulapp1/model/User.java | 1690 | package org.pjaygroup.restfulapp1.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author Vijay Konduru
*
*/
@Entity
@Table(name = "user")
@XmlRootElement(name = "user")
//@XmlAccessorType(XmlAccessType.FIELD)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(unique = true)
private String user_id;
// @JsonIgnore // Xml part will not work well, json part works fine
// @XmlTransient // Not working as expected
// private String password;
private String first_name;
private String last_name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
@Override
public String toString() {
return "User [id=" + id + ", user_id=" + user_id + ", first_name=" + first_name + ", last_name=" + last_name
+ "]";
}
/* @JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty
public void setPassword(String password) {
this.password = password;
}*/
}
| apache-2.0 |
manoharprabhu/Topcoder | misc/mergesort/src/test/java/mergesort/Tests.java | 1284 | package mergesort;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by manoharprabhu on 14/7/16.
*/
public class Tests {
@Test
public void test1() {
int[] numbers = new int[]{3,2,1,5,2,7,8};
Assert.assertArrayEquals(new int[]{1,2,2,3,5,7,8}, MergeSort.sort(numbers));
}
@Test
public void test2() {
int[] numbers = new int[]{3};
Assert.assertArrayEquals(new int[]{3}, MergeSort.sort(numbers));
}
@Test
public void test3() {
int[] numbers = new int[]{};
Assert.assertArrayEquals(new int[]{}, MergeSort.sort(numbers));
}
@Test
public void test4() {
int[] numbers = new int[]{1,2,3,4,5};
Assert.assertArrayEquals(new int[]{1,2,3,4,5}, MergeSort.sort(numbers));
}
@Test
public void test5() {
int[] numbers = new int[]{5,4,3,2,1};
Assert.assertArrayEquals(new int[]{1,2,3,4,5}, MergeSort.sort(numbers));
}
@Test
public void test6() {
int[] numbers = new int[]{3, 2};
Assert.assertArrayEquals(new int[]{2, 3}, MergeSort.sort(numbers));
}
@Test
public void test7() {
int[] numbers = new int[]{2, 3};
Assert.assertArrayEquals(new int[]{2, 3}, MergeSort.sort(numbers));
}
}
| apache-2.0 |
draken1/torrent-world | torrent/src/main/java/com/draken/torrent/bootstrap/DaumVarietyProgramSearchBootstrap.java | 1771 | package com.draken.torrent.bootstrap;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import com.draken.torrent.TvProgramEntity;
import com.draken.torrent.TvProgramInfo;
import com.draken.torrent.bootstrap.codec.DaumTvProgramInfoDecoder;
import com.draken.torrent.bootstrap.codec.TvProgramInfoDecoder;
/**
* @author jsh
* @since 1.0
*/
public class DaumVarietyProgramSearchBootstrap extends AbstractHttpSearchBootstrap {
private TvProgramInfoDecoder<Element> decoder;
private String varietyName;
private Response res;
private Document document;
public DaumVarietyProgramSearchBootstrap(String varietyName) {
this(new DaumTvProgramInfoDecoder(),varietyName);
}
public DaumVarietyProgramSearchBootstrap(TvProgramInfoDecoder<Element> decoder,String varietyName) {
this.decoder = decoder;
this.varietyName = varietyName;
}
@SuppressWarnings("unchecked")
@Override
public TvProgramInfo search() {
StringBuilder urlBuilder =
new StringBuilder("http://search.daum.net/search?w=tot&nil_profile=rtupkwd_33&rtupcate=33&rtmaxcoll=TVP&DA=RNTO&q=")
.append(varietyName);
TvProgramInfo variety = new TvProgramEntity();
try {
res = response(urlBuilder.toString());
document = res.parse();
variety
.broadCastDays(decoder.broadCastDays(document))
.broadCastType(decoder.broadCastType(document))
.broadCastTime(decoder.broadCastTime(document))
.broadCastDateRange(decoder.broadCastDateRange(document))
.cornerPrograms(decoder.cornerPrograms(document))
.seasons(decoder.seasons(document))
.casts(decoder.casts(document))
.guest(decoder.guests(document));
} catch(Exception e) {
e.printStackTrace();
}
return variety;
}
}
| apache-2.0 |
hetianpeng/shareApk | shareapk/src/main/java/com/codehe/shareapk/util/KeyBoardUtils.java | 1255 | package com.codehe.shareapk.util;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
* 打开或关闭软键盘
*
*/
public class KeyBoardUtils
{
/**
* 打开软键盘
*
* @param mEditText
* 输入框
* @param mContext
* 上下文
*/
public static void openKeyboard(EditText mEditText, Context mContext)
{
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}
/**
* 关闭软键盘
*
* 输入框
* @param mContext
* 上下文
*/
public static void closeKeyboard(View view, Context mContext)
{
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
| apache-2.0 |
peridotperiod/isis | core/viewer-wicket/ui/src/main/java/org/apache/isis/viewer/wicket/ui/components/scalars/reference/ReferencePanel.java | 21903 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.viewer.wicket.ui.components.scalars.reference;
import java.util.List;
import javax.inject.Inject;
import com.google.common.collect.Lists;
import com.vaynberg.wicket.select2.ChoiceProvider;
import com.vaynberg.wicket.select2.Select2Choice;
import com.vaynberg.wicket.select2.Settings;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;
import org.apache.isis.core.commons.config.IsisConfiguration;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.adapter.mgr.AdapterManager.ConcurrencyChecking;
import org.apache.isis.core.metamodel.facets.all.named.NamedFacet;
import org.apache.isis.core.metamodel.facets.object.autocomplete.AutoCompleteFacet;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.runtime.system.context.IsisContext;
import org.apache.isis.viewer.wicket.model.isis.WicketViewerSettings;
import org.apache.isis.viewer.wicket.model.links.LinkAndLabel;
import org.apache.isis.viewer.wicket.model.mementos.ObjectAdapterMemento;
import org.apache.isis.viewer.wicket.model.models.EntityModel;
import org.apache.isis.viewer.wicket.model.models.ScalarModel;
import org.apache.isis.viewer.wicket.model.models.ScalarModelWithPending.Util;
import org.apache.isis.viewer.wicket.ui.ComponentFactory;
import org.apache.isis.viewer.wicket.ui.ComponentType;
import org.apache.isis.viewer.wicket.ui.components.actionmenu.entityactions.EntityActionUtil;
import org.apache.isis.viewer.wicket.ui.components.scalars.ScalarPanelAbstract;
import org.apache.isis.viewer.wicket.ui.components.widgets.ObjectAdapterMementoProviderAbstract;
import org.apache.isis.viewer.wicket.ui.components.widgets.bootstrap.FormGroup;
import org.apache.isis.viewer.wicket.ui.components.widgets.entitysimplelink.EntityLinkSimplePanel;
import org.apache.isis.viewer.wicket.ui.components.widgets.select2.Select2ChoiceUtil;
import org.apache.isis.viewer.wicket.ui.util.Components;
import org.apache.isis.viewer.wicket.ui.util.CssClassAppender;
/**
* Panel for rendering scalars which of are of reference type (as opposed to
* value types).
*/
public class ReferencePanel extends ScalarPanelAbstract {
private static final long serialVersionUID = 1L;
private static final String ID_AUTO_COMPLETE = "autoComplete";
private static final String ID_ENTITY_ICON_TITLE = "entityIconAndTitle";
/**
* Determines the behaviour of dependent choices for the dependent; either to autoselect the first available choice, or to select none.
*/
private static final String KEY_DISABLE_DEPENDENT_CHOICE_AUTO_SELECTION = "isis.viewer.wicket.disableDependentChoiceAutoSelection";
private EntityLinkSelect2Panel entityLink;
Select2Choice<ObjectAdapterMemento> select2Field;
private EntityLinkSimplePanel entitySimpleLink;
public ReferencePanel(final String id, final ScalarModel scalarModel) {
super(id, scalarModel);
}
// //////////////////////////////////////
// addComponentFor{Compact/Regular}
// //////////////////////////////////////
// First called as a side-effect of {@link #beforeRender()}
@Override
protected Component addComponentForCompact() {
final ScalarModel scalarModel = getModel();
final String name = scalarModel.getName();
entitySimpleLink = (EntityLinkSimplePanel) getComponentFactoryRegistry().createComponent(ComponentType.ENTITY_LINK, getModel());
entitySimpleLink.setOutputMarkupId(true);
entitySimpleLink.setLabel(Model.of(name));
final WebMarkupContainer labelIfCompact = new WebMarkupContainer(ID_SCALAR_IF_COMPACT);
labelIfCompact.add(entitySimpleLink);
addOrReplace(labelIfCompact);
return labelIfCompact;
}
// First called as a side-effect of {@link #beforeRender()}
@Override
protected FormGroup addComponentForRegular() {
final ScalarModel scalarModel = getModel();
final String name = scalarModel.getName();
entityLink = new EntityLinkSelect2Panel(ComponentType.ENTITY_LINK.getWicketId(), this);
syncWithInput();
setOutputMarkupId(true);
entityLink.setOutputMarkupId(true);
entityLink.setLabel(Model.of(name));
final FormGroup labelIfRegular = new FormGroup(ID_SCALAR_IF_REGULAR, entityLink);
labelIfRegular.add(entityLink);
final String describedAs = getModel().getDescribedAs();
if(describedAs != null) {
labelIfRegular.add(new AttributeModifier("title", Model.of(describedAs)));
}
final Label scalarName = new Label(ID_SCALAR_NAME, getRendering().getLabelCaption(entityLink));
labelIfRegular.add(scalarName);
NamedFacet namedFacet = getModel().getFacet(NamedFacet.class);
if (namedFacet != null) {
scalarName.setEscapeModelStrings(namedFacet.escaped());
}
// find the links...
final List<LinkAndLabel> entityActions = EntityActionUtil.getEntityActionLinksForAssociation(this.scalarModel, getDeploymentType());
addPositioningCssTo(labelIfRegular, entityActions);
addOrReplace(labelIfRegular);
addFeedbackTo(labelIfRegular, entityLink);
// ... add entity links to panel (below and to right)
addEntityActionLinksBelowAndRight(labelIfRegular, entityActions);
// add semantics
entityLink.setRequired(getModel().isRequired());
entityLink.add(new IValidator<ObjectAdapter>() {
private static final long serialVersionUID = 1L;
@Override
public void validate(final IValidatable<ObjectAdapter> validatable) {
final ObjectAdapter proposedAdapter = validatable.getValue();
final String reasonIfAny = getModel().validate(proposedAdapter);
if (reasonIfAny != null) {
final ValidationError error = new ValidationError();
error.setMessage(reasonIfAny);
validatable.error(error);
}
}
});
if(getModel().isRequired()) {
labelIfRegular.add(new CssClassAppender("mandatory"));
}
return labelIfRegular;
}
// //////////////////////////////////////
// called from buildGui
@Override
protected void addFormComponentBehavior(Behavior behavior) {
if(select2Field != null) {
select2Field.add(behavior);
}
}
// //////////////////////////////////////
// onBeforeRender*
// //////////////////////////////////////
@Override
protected void onBeforeRenderWhenEnabled() {
super.onBeforeRenderWhenEnabled();
entityLink.setEnabled(true);
syncWithInput();
}
@Override
protected void onBeforeRenderWhenViewMode() {
super.onBeforeRenderWhenViewMode();
entityLink.setEnabled(false);
syncWithInput();
}
@Override
protected void onBeforeRenderWhenDisabled(final String disableReason) {
super.onBeforeRenderWhenDisabled(disableReason);
syncWithInput();
final EntityModel entityLinkModel = (EntityModel) entityLink.getModel();
entityLinkModel.toViewMode();
entityLink.setEnabled(false);
entityLink.add(new AttributeModifier("title", Model.of(disableReason)));
}
// //////////////////////////////////////
// syncWithInput
// //////////////////////////////////////
// called from onBeforeRender*
// (was previous called by EntityLinkSelect2Panel in onBeforeRender, this responsibility now moved)
private void syncWithInput() {
final ObjectAdapter adapter = getModel().getPendingElseCurrentAdapter();
// syncLinkWithInput
final MarkupContainer componentForRegular = (MarkupContainer) getComponentForRegular();
if (adapter != null) {
if(componentForRegular != null) {
final EntityModel entityModelForLink = new EntityModel(adapter);
entityModelForLink.setContextAdapterIfAny(getModel().getContextAdapterIfAny());
entityModelForLink.setRenderingHint(getModel().getRenderingHint());
final ComponentFactory componentFactory =
getComponentFactoryRegistry().findComponentFactory(ComponentType.ENTITY_ICON_AND_TITLE, entityModelForLink);
final Component component = componentFactory.createComponent(entityModelForLink);
componentForRegular.addOrReplace(component);
Components.permanentlyHide(componentForRegular, "entityTitleIfNull");
}
} else {
if(componentForRegular != null) {
componentForRegular.addOrReplace(new Label("entityTitleIfNull", "(none)"));
//Components.permanentlyHide(componentForRegular, "entityTitleIfNull");
Components.permanentlyHide(componentForRegular, ID_ENTITY_ICON_TITLE);
}
}
// syncLinkWithInputIfAutoCompleteOrChoices
if(isEditableWithEitherAutoCompleteOrChoices()) {
final IModel<ObjectAdapterMemento> model = Util.createModel(getModel().asScalarModelWithPending());
if(select2Field == null) {
entityLink.setRequired(getModel().isRequired());
select2Field = Select2ChoiceUtil.newSelect2Choice(ID_AUTO_COMPLETE, model, getModel());
setProviderAndCurrAndPending(select2Field, getModel().getActionArgsHint());
if(!getModel().hasChoices()) {
final Settings settings = select2Field.getSettings();
final int minLength = getModel().getAutoCompleteMinLength();
settings.setMinimumInputLength(minLength);
settings.setPlaceholder(getModel().getName());
}
entityLink.addOrReplace(select2Field);
} else {
//
// the select2Field already exists, so the widget has been rendered before. If it is
// being re-rendered now, it may be because some other property/parameter was invalid.
// when the form was submitted, the selected object (its oid as a string) would have
// been saved as rawInput. If the property/parameter had been valid, then this rawInput
// would be correctly converted and processed by the select2Field's choiceProvider. However,
// an invalid property/parameter means that the webpage is re-rendered in another request,
// and the rawInput can no longer be interpreted. The net result is that the field appears
// with no input.
//
// The fix is therefore (I think) simply to clear any rawInput, so that the select2Field
// renders its state from its model.
//
// see: FormComponent#getInputAsArray()
// see: Select2Choice#renderInitializationScript()
//
select2Field.clearInput();
}
if(getComponentForRegular() != null) {
Components.permanentlyHide((MarkupContainer)getComponentForRegular(), ID_ENTITY_ICON_TITLE);
Components.permanentlyHide(componentForRegular, "entityTitleIfNull");
}
// syncUsability
if(select2Field != null) {
final boolean mutability = entityLink.isEnableAllowed() && !getModel().isViewMode();
select2Field.setEnabled(mutability);
}
Components.permanentlyHide(entityLink, "entityLinkIfNull");
} else {
// this is horrid; adds a label to the id
// should instead be a 'temporary hide'
Components.permanentlyHide(entityLink, ID_AUTO_COMPLETE);
select2Field = null; // this forces recreation next time around
}
}
// called by syncWithInput
private void permanentlyHideEntityIconAndTitleIfInRegularMode() {
if(getComponentForRegular() != null) {
Components.permanentlyHide((MarkupContainer)getComponentForRegular(), ID_ENTITY_ICON_TITLE);
}
}
// //////////////////////////////////////
// setProviderAndCurrAndPending
// //////////////////////////////////////
// called by syncWithInput, updateChoices
private void setProviderAndCurrAndPending(
final Select2Choice<ObjectAdapterMemento> select2Field,
final ObjectAdapter[] argsIfAvailable) {
if (getModel().hasChoices()) {
final List<ObjectAdapterMemento> choiceMementos = obtainChoiceMementos(argsIfAvailable);
ObjectAdapterMementoProviderAbstract providerForChoices = providerForChoices(choiceMementos);
select2Field.setProvider(providerForChoices);
getModel().clearPending();
resetIfCurrentNotInChoices(select2Field, choiceMementos);
} else if(hasParamOrPropertyAutoComplete()) {
select2Field.setProvider(providerForParamOrPropertyAutoComplete());
getModel().clearPending();
} else {
select2Field.setProvider(providerForObjectAutoComplete());
getModel().clearPending();
}
}
// called by setProviderAndCurrAndPending
private List<ObjectAdapterMemento> obtainChoiceMementos(final ObjectAdapter[] argsIfAvailable) {
final List<ObjectAdapter> choices = Lists.newArrayList();
if(getModel().hasChoices()) {
choices.addAll(getModel().getChoices(argsIfAvailable));
}
// take a copy otherwise is only lazily evaluated
return Lists.newArrayList(Lists.transform(choices, ObjectAdapterMemento.Functions.fromAdapter()));
}
// called by setProviderAndCurrAndPending
private void resetIfCurrentNotInChoices(final Select2Choice<ObjectAdapterMemento> select2Field, final List<ObjectAdapterMemento> choiceMementos) {
final ObjectAdapterMemento curr = select2Field.getModelObject();
if(curr == null) {
select2Field.getModel().setObject(null);
getModel().setObject(null);
return;
}
if(!curr.containedIn(choiceMementos)) {
if(!choiceMementos.isEmpty() && autoSelect()) {
final ObjectAdapterMemento newAdapterMemento = choiceMementos.get(0);
select2Field.getModel().setObject(newAdapterMemento);
getModel().setObject(newAdapterMemento.getObjectAdapter(ConcurrencyChecking.NO_CHECK));
} else {
select2Field.getModel().setObject(null);
getModel().setObject(null);
}
}
}
private boolean autoSelect() {
final boolean disableAutoSelect = getConfiguration().getBoolean(KEY_DISABLE_DEPENDENT_CHOICE_AUTO_SELECTION, false);
final boolean autoSelect = !disableAutoSelect;
return autoSelect;
}
// called by setProviderAndCurrAndPending
private ChoiceProvider<ObjectAdapterMemento> providerForObjectAutoComplete() {
return new ObjectAdapterMementoProviderAbstract(getModel(), wicketViewerSettings) {
private static final long serialVersionUID = 1L;
@Override
protected List<ObjectAdapterMemento> obtainMementos(String term) {
final ObjectSpecification typeOfSpecification = getScalarModel().getTypeOfSpecification();
final AutoCompleteFacet autoCompleteFacet = typeOfSpecification.getFacet(AutoCompleteFacet.class);
final List<ObjectAdapter> results = autoCompleteFacet.execute(term);
return Lists.transform(results, ObjectAdapterMemento.Functions.fromAdapter());
}
};
}
// called by setProviderAndCurrAndPending
private ChoiceProvider<ObjectAdapterMemento> providerForParamOrPropertyAutoComplete() {
return new ObjectAdapterMementoProviderAbstract(getModel(), wicketViewerSettings) {
private static final long serialVersionUID = 1L;
@Override
protected List<ObjectAdapterMemento> obtainMementos(String term) {
final List<ObjectAdapter> autoCompleteChoices = Lists.newArrayList();
if(getScalarModel().hasAutoComplete()) {
autoCompleteChoices.addAll(getScalarModel().getAutoComplete(term));
}
// take a copy otherwise is only lazily evaluated
return Lists.newArrayList(Lists.transform(autoCompleteChoices, ObjectAdapterMemento.Functions.fromAdapter()));
}
};
}
// called by setProviderAndCurrAndPending
private ObjectAdapterMementoProviderAbstract providerForChoices(final List<ObjectAdapterMemento> choiceMementos) {
return new ObjectAdapterMementoProviderAbstract(getModel(), wicketViewerSettings) {
private static final long serialVersionUID = 1L;
@Override
protected List<ObjectAdapterMemento> obtainMementos(String term) {
return obtainMementos(term, choiceMementos);
}
};
}
// //////////////////////////////////////
// getInput, convertInput
// //////////////////////////////////////
// called by EntityLinkSelect2Panel
String getInput() {
final ObjectAdapter pendingElseCurrentAdapter = getModel().getPendingElseCurrentAdapter();
return pendingElseCurrentAdapter != null? pendingElseCurrentAdapter.titleString(null): "(no object)";
}
// //////////////////////////////////////
// called by EntityLinkSelect2Panel
void convertInput() {
if(isEditableWithEitherAutoCompleteOrChoices()) {
// flush changes to pending
ObjectAdapterMemento convertedInput = select2Field.getConvertedInput();
getModel().setPending(convertedInput);
if(select2Field != null) {
select2Field.getModel().setObject(convertedInput);
}
final ObjectAdapter adapter = convertedInput!=null?convertedInput.getObjectAdapter(ConcurrencyChecking.NO_CHECK):null;
getModel().setObject(adapter);
}
final ObjectAdapter pendingAdapter = getModel().getPendingAdapter();
entityLink.setConvertedInput(pendingAdapter);
}
// //////////////////////////////////////
// updateChoices
// //////////////////////////////////////
/**
* Hook method to refresh choices when changing.
*
* <p>
* called from onUpdate callback
*/
@Override
public boolean updateChoices(ObjectAdapter[] argsIfAvailable) {
if(select2Field != null) {
setProviderAndCurrAndPending(select2Field, argsIfAvailable);
return true;
} else {
return false;
}
}
// //////////////////////////////////////
// helpers querying model state
// //////////////////////////////////////
// called from convertInput, syncWithInput
private boolean isEditableWithEitherAutoCompleteOrChoices() {
if(getModel().getRenderingHint().isInTable()) {
return false;
}
// doesn't apply if not editable, either
if(getModel().isViewMode()) {
return false;
}
return getModel().hasChoices() || hasParamOrPropertyAutoComplete() || hasObjectAutoComplete();
}
// called by isEditableWithEitherAutoCompleteOrChoices, also syncProviderAndCurrAndPending
private boolean hasParamOrPropertyAutoComplete() {
return getModel().hasAutoComplete();
}
// called by isEditableWithEitherAutoCompleteOrChoices
private boolean hasObjectAutoComplete() {
final ObjectSpecification typeOfSpecification = getModel().getTypeOfSpecification();
final AutoCompleteFacet autoCompleteFacet =
(typeOfSpecification != null)? typeOfSpecification.getFacet(AutoCompleteFacet.class):null;
return autoCompleteFacet != null;
}
@Inject
private WicketViewerSettings wicketViewerSettings;
IsisConfiguration getConfiguration() {
return IsisContext.getConfiguration();
}
}
| apache-2.0 |
claremontqualitymanagement/TestAutomationFramework | TestingCapabilityJavaGui/src/main/java/se/claremont/taf/javasupport/applicationundertest/ApplicationUnderTest.java | 10281 | package se.claremont.taf.javasupport.applicationundertest;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import se.claremont.taf.core.logging.LogLevel;
import se.claremont.taf.core.testcase.TestCase;
import se.claremont.taf.javasupport.applicationundertest.applicationcontext.ApplicationContextManager;
import se.claremont.taf.javasupport.applicationundertest.applicationstarters.ApplicationStartMechanism;
import se.claremont.taf.javasupport.applicationundertest.applicationstarters.ApplicationThreadRunner;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class ApplicationUnderTest implements Serializable{
@JsonProperty public String friendlyName;
@JsonProperty public ApplicationContextManager context;
@JsonProperty public ApplicationStartMechanism startMechanism;
@JsonIgnore transient TestCase testCase;
@JsonIgnore static transient ArrayList<Window> windowsStartedBeforeStartingSut = new ArrayList<>();
private ApplicationUnderTest(){ //For JSON parsing to work
TestCase testCase = new TestCase();
context = new ApplicationContextManager(testCase);
this.startMechanism = new ApplicationStartMechanism(testCase);
this.testCase = testCase;
}
public ApplicationUnderTest(TestCase testCase, ApplicationStartMechanism startMechanism){
context = new ApplicationContextManager(testCase);
this.startMechanism = startMechanism;
this.testCase = testCase;
}
public ApplicationUnderTest(ApplicationUnderTest aut){
this.testCase = aut.testCase;
context = new ApplicationContextManager(testCase);
startMechanism = new ApplicationStartMechanism(testCase);
this.context.jvmSettings.appliedSetting = new ArrayList<>(aut.context.jvmSettings.appliedSetting);
this.context.loadedLibraries.appliedFiles = new ArrayList<>(aut.context.loadedLibraries.appliedFiles);
this.context.properties.appliedProperties = new ArrayList<>(aut.context.properties.appliedProperties);
this.context.environmentVariables.appliedVariableChanges = new ArrayList<>(aut.context.environmentVariables.appliedVariableChanges);
this.startMechanism.mainClass = aut.startMechanism.mainClass;
this.startMechanism.startUrlOrPathToJarFile = aut.startMechanism.startUrlOrPathToJarFile;
this.startMechanism.arguments = aut.startMechanism.arguments;
}
public ApplicationUnderTest(ApplicationStartMechanism startMechanism, ApplicationContextManager context){
this.context = context;
this.startMechanism = startMechanism;
}
public void reAssignTestCase(TestCase testCase){
this.testCase = testCase;
}
public void setName(String name){
this.friendlyName = name;
}
@JsonIgnore
public void setProgramArguments(String[] args){
for(String arg : args){
startMechanism.arguments.add(arg);
}
}
@JsonIgnore
public void addProgramArgument(String arg){
startMechanism.arguments.add(arg);
}
@JsonIgnore
public void setMainClass(String mainClassName){
startMechanism.mainClass = mainClassName;
}
@JsonIgnore
public void loadLibrary(String path){
context.loadedLibraries.loadLibrary(path);
}
@JsonIgnore
public void loadAllLibrariesInFolder(String path){
context.loadedLibraries.loadAllDllsInFolder(path);
}
@JsonIgnore
public void setEnvironmentVariableValue(String variableName, String variableValue){
context.environmentVariables.setEnvironmentVariable(variableName, variableValue);
}
@JsonIgnore
public void setSystemPropertyValue(String name, String value){
context.properties.setProperty(name, value);
}
@JsonIgnore
public void attemptToAddJVMSetting(String name, String value){
context.jvmSettings.setVMOption(name, value);
}
@JsonIgnore
public void setMainJarOrUrl(String jarFilePathOrUrl){
startMechanism.startUrlOrPathToJarFile = jarFilePathOrUrl;
}
@JsonIgnore
public void start(){
windowsStartedBeforeStartingSut.addAll(getWindows());
Thread t = ApplicationThreadRunner.start(startMechanism);
}
@JsonIgnore
public void stop(){
closeAllWindows();
}
@JsonIgnore
public Object getWindow(){
Set<Window> windows = getWindows();
log(LogLevel.DEBUG, "Found " + windows.size()+ " windows in JVM.");
if(windows.size() == 0) {
log(LogLevel.EXECUTION_PROBLEM, "Could not find any windows.");
return null;
}
if(windows.size() == 1) {
log(LogLevel.DEBUG, "Found one window.");
return windows.toArray()[0];
}
if(windows.size()> 1){
log(LogLevel.INFO, "Found more than one window. Returning the first one. Consider using the enumerator method implementation for specific window.");
return windows.toArray()[0];
}
return null;
}
@JsonIgnore
public static Set<Window> getWindows(){
Set<Window> windows = new HashSet<>();
Collections.addAll(windows, Window.getWindows());
Collections.addAll(windows, Window.getOwnerlessWindows());
ArrayList<Window> subWindows = new ArrayList<>();
for(Window window : windows){
for(Window subWindow : getSubWindowsRevursive(window)){
subWindows.add(subWindow);
}
}
for(Window subWindow : subWindows){
windows.add(subWindow);
}
for(Frame frame : Frame.getFrames()){
windows.add(frame);
windows.addAll(getSubWindowsRevursive(frame));
}
return windows;
}
private static ArrayList<Window> getSubWindowsRevursive(Window window){
ArrayList<Window> windows = new ArrayList<>();
Collections.addAll(windows, window.getOwnedWindows());
for(Window subWindow : windows){
Collections.addAll(getSubWindowsRevursive(subWindow));
}
return windows;
}
@JsonIgnore
public static ArrayList<Window> getWindowsForSUT(){
ArrayList<Window> windows = new ArrayList<>();
Window [] swingWindows = Window.getOwnerlessWindows ();
Collections.addAll(windows, swingWindows);
windows.removeAll(windowsStartedBeforeStartingSut);
return windows;
}
@JsonIgnore
public static void closeAllWindows(){
for(Window window : getWindows()){
closeSubWindows(window);
}
}
@JsonIgnore
private static void closeSubWindows(Window window){
Window[] subWindows = window.getOwnedWindows();
for(Window w : subWindows){
closeSubWindows(w);
}
window.dispose();
}
@JsonIgnore
public Object getWindow(int windowCount){
Set<Window> windows = getWindows();
log(LogLevel.DEBUG, "Found " + windows.size()+ " windows in JVM.");
if(windows.size() < windowCount) {
log(LogLevel.EXECUTION_PROBLEM, "Only found " + windows.size()+ " open windows, and request was for window " + windowCount + ".");
return null;
}
if(windows.size() == 1) {
log(LogLevel.DEBUG, "Found one window returning this although window count " + windowCount + " was requested.");
return windows.toArray()[0];
}
return windows.toArray()[windowCount];
}
@JsonIgnore
public void logCurrentWindows(){
logCurrentWindows(testCase);
}
@JsonIgnore
public static void logCurrentWindows(TestCase testCase) {
StringBuilder logMessage = new StringBuilder("Current active windows:" + System.lineSeparator());
for(Window w : getWindows()){
try{
Frame frame = (Frame) w;
logMessage.append("Window title: '").append(frame.getTitle()).append("'. Shown:").append(frame.isShowing()).append(System.lineSeparator());
continue;
} catch (Exception ignored){
testCase.log(LogLevel.DEBUG, "Could not retrieve title of Window as Frame. Error: " + ignored.getMessage());
}
try{
JFrame frame = (JFrame) w;
logMessage.append("Window title: '").append(frame.getTitle()).append("'. Shown:").append(frame.isShowing()).append(System.lineSeparator());
continue;
} catch (Exception ignored){
testCase.log(LogLevel.DEBUG, "Could not retrieve title of Window as JFrame. Error: " + ignored.getMessage());
}
logMessage.append("Could not find title of element of class '").append(w.getClass().toString()).append("' since it is not implemented");
}
if(testCase == null){
System.out.println(logMessage.toString());
} else {
testCase.log(LogLevel.INFO, logMessage.toString());
}
}
@JsonIgnore
public String saveToJsonFile(String filePath){
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(filePath), this);
} catch (IOException e) {
return e.toString();
}
return "ok";
}
@JsonIgnore
public static ApplicationUnderTest readFromJsonFile(String filePath){
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(new File(filePath), ApplicationUnderTest.class);
} catch (IOException e) {
System.out.println(e.toString());
}
TestCase testCase = new TestCase();
return new ApplicationUnderTest(testCase, new ApplicationStartMechanism(testCase));
}
@JsonIgnore
private void log(LogLevel logLevel, String message){
if(testCase == null){
System.out.println(message);
} else {
testCase.log(logLevel, message);
}
}
}
| apache-2.0 |
WuSicheng54321/Thinking-in-Java-4th | ThinkingInJava12/src/RethowNew.java | 762 | class OneException extends Exception{
public OneException(String s){
super(s);
}
}
class twoException extends Exception{
public twoException(String s){
super(s);
}
}
public class RethowNew {
public static void f() throws OneException{
System.out.println("originating the exception in f()");
throw new OneException("thrown from f()");
}
public static void main(String args[]){
try{
try{
f();
}catch(OneException e){
System.out.println("Caught in inner try,e.printStackTrace()");
e.printStackTrace(System.out);
throw new twoException("from inner try");
}
}catch(twoException e){
System.out.println("Caught in outer try,e.printStackTrace()");
e.printStackTrace(System.out);
}
}
}
| apache-2.0 |
goodwinnk/intellij-community | platform/util/src/com/intellij/openapi/util/io/FileUtil.java | 56963 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util.io;
import com.intellij.CommonBundle;
import com.intellij.Patches;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.*;
import com.intellij.util.concurrency.FixedFuture;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import com.intellij.util.containers.JBTreeTraverser;
import com.intellij.util.io.URLUtil;
import com.intellij.util.text.FilePathHashingStrategy;
import com.intellij.util.text.StringFactory;
import gnu.trove.TObjectHashingStrategy;
import org.intellij.lang.annotations.RegExp;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.regex.Pattern;
@SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "MethodOverridesStaticMethodOfSuperclass"})
public class FileUtil extends FileUtilRt {
static {
if (!Patches.USE_REFLECTION_TO_ACCESS_JDK7) throw new RuntimeException("Please migrate FileUtilRt to JDK8");
}
public static final String ASYNC_DELETE_EXTENSION = ".__del__";
public static final int REGEX_PATTERN_FLAGS = SystemInfo.isFileSystemCaseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
public static final TObjectHashingStrategy<String> PATH_HASHING_STRATEGY = FilePathHashingStrategy.create();
public static final TObjectHashingStrategy<File> FILE_HASHING_STRATEGY =
new TObjectHashingStrategy<File>() {
@Override
public int computeHashCode(File object) {
return fileHashCode(object);
}
@Override
public boolean equals(File o1, File o2) {
return filesEqual(o1, o2);
}
};
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil");
@NotNull
public static String join(@NotNull final String... parts) {
return StringUtil.join(parts, File.separator);
}
/**
* Gets the relative path from the {@code base} to the {@code file} regardless existence or the type of the {@code base}.
* <p>
* NOTE: if the file(not directory) passed as the {@code base} the result can not be used as a relative path from the {@code base} parent directory to the {@code file}
*
* @param base the base
* @param file the file
* @return the relative path from the {@code base} to the {@code file} or {@code null}
*/
@Nullable
public static String getRelativePath(File base, File file) {
return FileUtilRt.getRelativePath(base, file);
}
@Nullable
public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator) {
return FileUtilRt.getRelativePath(basePath, filePath, separator);
}
@Nullable
public static String getRelativePath(@NotNull String basePath,
@NotNull String filePath,
final char separator,
final boolean caseSensitive) {
return FileUtilRt.getRelativePath(basePath, filePath, separator, caseSensitive);
}
public static boolean isAbsolute(@NotNull String path) {
return !path.isEmpty() && new File(path).isAbsolute();
}
public static boolean exists(@Nullable String path) {
return path != null && new File(path).exists();
}
/**
* Check if the {@code ancestor} is an ancestor of {@code file}.
*
* @param ancestor supposed ancestor.
* @param file supposed descendant.
* @param strict if {@code false} then this method returns {@code true} if {@code ancestor} equals to {@code file}.
* @return {@code true} if {@code ancestor} is parent of {@code file}; {@code false} otherwise.
*/
public static boolean isAncestor(@NotNull File ancestor, @NotNull File file, boolean strict) {
return isAncestor(ancestor.getPath(), file.getPath(), strict);
}
public static boolean isAncestor(@NotNull String ancestor, @NotNull String file, boolean strict) {
return !ThreeState.NO.equals(isAncestorThreeState(ancestor, file, strict));
}
/**
* Checks if the {@code ancestor} is an ancestor of the {@code file}, and if it is an immediate parent or not.
*
* @param ancestor supposed ancestor.
* @param file supposed descendant.
* @param strict if {@code false}, the file can be ancestor of itself,
* i.e. the method returns {@code ThreeState.YES} if {@code ancestor} equals to {@code file}.
*
* @return {@code ThreeState.YES} if ancestor is an immediate parent of the file,
* {@code ThreeState.UNSURE} if ancestor is not immediate parent of the file,
* {@code ThreeState.NO} if ancestor is not a parent of the file at all.
*/
@NotNull
public static ThreeState isAncestorThreeState(@NotNull String ancestor, @NotNull String file, boolean strict) {
String ancestorPath = toCanonicalPath(ancestor);
String filePath = toCanonicalPath(file);
return startsWith(filePath, ancestorPath, strict, SystemInfo.isFileSystemCaseSensitive, true);
}
public static boolean startsWith(@NotNull String path, @NotNull String start) {
return !ThreeState.NO.equals(startsWith(path, start, false, SystemInfo.isFileSystemCaseSensitive, false));
}
public static boolean startsWith(@NotNull String path, @NotNull String start, boolean caseSensitive) {
return !ThreeState.NO.equals(startsWith(path, start, false, caseSensitive, false));
}
@NotNull
private static ThreeState startsWith(@NotNull String path, @NotNull String prefix, boolean strict, boolean caseSensitive,
boolean checkImmediateParent) {
final int pathLength = path.length();
final int prefixLength = prefix.length();
if (prefixLength == 0) return pathLength == 0 ? ThreeState.YES : ThreeState.UNSURE;
if (prefixLength > pathLength) return ThreeState.NO;
if (!path.regionMatches(!caseSensitive, 0, prefix, 0, prefixLength)) return ThreeState.NO;
if (pathLength == prefixLength) {
return strict ? ThreeState.NO : ThreeState.YES;
}
char lastPrefixChar = prefix.charAt(prefixLength - 1);
int slashOrSeparatorIdx = prefixLength;
if (lastPrefixChar == '/' || lastPrefixChar == File.separatorChar) {
slashOrSeparatorIdx = prefixLength - 1;
}
char next1 = path.charAt(slashOrSeparatorIdx);
if (next1 == '/' || next1 == File.separatorChar) {
if (!checkImmediateParent) return ThreeState.YES;
if (slashOrSeparatorIdx == pathLength - 1) return ThreeState.YES;
int idxNext = path.indexOf(next1, slashOrSeparatorIdx + 1);
idxNext = idxNext == -1 ? path.indexOf(next1 == '/' ? '\\' : '/', slashOrSeparatorIdx + 1) : idxNext;
return idxNext == -1 ? ThreeState.YES : ThreeState.UNSURE;
}
else {
return ThreeState.NO;
}
}
@Nullable
public static File findAncestor(@NotNull File f1, @NotNull File f2) {
File ancestor = f1;
while (ancestor != null && !isAncestor(ancestor, f2, false)) {
ancestor = ancestor.getParentFile();
}
return ancestor;
}
@Nullable
public static File getParentFile(@NotNull File file) {
return FileUtilRt.getParentFile(file);
}
@NotNull
public static byte[] loadFileBytes(@NotNull File file) throws IOException {
byte[] bytes;
final InputStream stream = new FileInputStream(file);
try {
final long len = file.length();
if (len < 0) {
throw new IOException("File length reported negative, probably doesn't exist");
}
if (isTooLarge(len)) {
throw new FileTooBigException("Attempt to load '" + file + "' in memory buffer, file length is " + len + " bytes.");
}
bytes = loadBytes(stream, (int)len);
}
finally {
stream.close();
}
return bytes;
}
@NotNull
public static byte[] loadFirstAndClose(@NotNull InputStream stream, int maxLength) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
copy(stream, maxLength, buffer);
}
finally {
stream.close();
}
return buffer.toByteArray();
}
@NotNull
public static String loadTextAndClose(@NotNull InputStream stream) throws IOException {
//noinspection IOResourceOpenedButNotSafelyClosed
return loadTextAndClose(new InputStreamReader(stream));
}
@NotNull
public static String loadTextAndClose(@NotNull Reader reader) throws IOException {
try {
return StringFactory.createShared(adaptiveLoadText(reader));
}
finally {
reader.close();
}
}
@NotNull
public static char[] adaptiveLoadText(@NotNull Reader reader) throws IOException {
char[] chars = new char[4096];
List<char[]> buffers = null;
int count = 0;
int total = 0;
while (true) {
int n = reader.read(chars, count, chars.length - count);
if (n <= 0) break;
count += n;
if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + reader);
total += n;
if (count == chars.length) {
if (buffers == null) {
buffers = new ArrayList<char[]>();
}
buffers.add(chars);
int newLength = Math.min(1024 * 1024, chars.length * 2);
chars = new char[newLength];
count = 0;
}
}
char[] result = new char[total];
if (buffers != null) {
for (char[] buffer : buffers) {
System.arraycopy(buffer, 0, result, result.length - total, buffer.length);
total -= buffer.length;
}
}
System.arraycopy(chars, 0, result, result.length - total, total);
return result;
}
@NotNull
public static byte[] adaptiveLoadBytes(@NotNull InputStream stream) throws IOException {
byte[] bytes = getThreadLocalBuffer();
List<byte[]> buffers = null;
int count = 0;
int total = 0;
while (true) {
int n = stream.read(bytes, count, bytes.length - count);
if (n <= 0) break;
count += n;
if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + stream);
total += n;
if (count == bytes.length) {
if (buffers == null) {
buffers = new ArrayList<byte[]>();
}
buffers.add(bytes);
int newLength = Math.min(1024 * 1024, bytes.length * 2);
bytes = new byte[newLength];
count = 0;
}
}
byte[] result = new byte[total];
if (buffers != null) {
for (byte[] buffer : buffers) {
System.arraycopy(buffer, 0, result, result.length - total, buffer.length);
total -= buffer.length;
}
}
System.arraycopy(bytes, 0, result, result.length - total, total);
return result;
}
@NotNull
public static Future<Void> asyncDelete(@NotNull File file) {
return asyncDelete(Collections.singleton(file));
}
@NotNull
public static Future<Void> asyncDelete(@NotNull Collection<File> files) {
List<File> tempFiles = new ArrayList<File>();
for (File file : files) {
final File tempFile = renameToTempFileOrDelete(file);
if (tempFile != null) {
tempFiles.add(tempFile);
}
}
if (!tempFiles.isEmpty()) {
return startDeletionThread(tempFiles.toArray(new File[0]));
}
return new FixedFuture<Void>(null);
}
private static Future<Void> startDeletionThread(@NotNull final File... tempFiles) {
final RunnableFuture<Void> deleteFilesTask = new FutureTask<Void>(new Runnable() {
@Override
public void run() {
final Thread currentThread = Thread.currentThread();
final int priority = currentThread.getPriority();
currentThread.setPriority(Thread.MIN_PRIORITY);
try {
for (File tempFile : tempFiles) {
delete(tempFile);
}
}
finally {
currentThread.setPriority(priority);
}
}
}, null);
try {
// attempt to execute on pooled thread
final Class<?> aClass = Class.forName("com.intellij.openapi.application.ApplicationManager");
final Method getApplicationMethod = aClass.getMethod("getApplication");
final Object application = getApplicationMethod.invoke(null);
final Method executeOnPooledThreadMethod = application.getClass().getMethod("executeOnPooledThread", Runnable.class);
executeOnPooledThreadMethod.invoke(application, deleteFilesTask);
}
catch (Exception ignored) {
new Thread(deleteFilesTask, "File deletion thread").start();
}
return deleteFilesTask;
}
@Nullable
private static File renameToTempFileOrDelete(@NotNull File file) {
String tempDir = getTempDirectory();
boolean isSameDrive = true;
if (SystemInfo.isWindows) {
String tempDirDrive = tempDir.substring(0, 2);
String fileDrive = file.getAbsolutePath().substring(0, 2);
isSameDrive = tempDirDrive.equalsIgnoreCase(fileDrive);
}
if (isSameDrive) {
// the optimization is reasonable only if destination dir is located on the same drive
final String originalFileName = file.getName();
File tempFile = getTempFile(originalFileName, tempDir);
if (file.renameTo(tempFile)) {
return tempFile;
}
}
delete(file);
return null;
}
private static File getTempFile(@NotNull String originalFileName, @NotNull String parent) {
int randomSuffix = (int)(System.currentTimeMillis() % 1000);
for (int i = randomSuffix; ; i++) {
String name = "___" + originalFileName + i + ASYNC_DELETE_EXTENSION;
File tempFile = new File(parent, name);
if (!tempFile.exists()) return tempFile;
}
}
public static boolean delete(@NotNull File file) {
if (NIOReflect.IS_AVAILABLE) {
return deleteRecursivelyNIO(file);
}
return deleteRecursively(file);
}
private static boolean deleteRecursively(@NotNull File file) {
FileAttributes attributes = FileSystemUtil.getAttributes(file);
if (attributes == null) return true;
if (attributes.isDirectory() && !attributes.isSymLink()) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
if (!deleteRecursively(child)) return false;
}
}
}
return deleteFile(file);
}
public static boolean createParentDirs(@NotNull File file) {
return FileUtilRt.createParentDirs(file);
}
public static boolean createDirectory(@NotNull File path) {
return FileUtilRt.createDirectory(path);
}
public static boolean createIfDoesntExist(@NotNull File file) {
return FileUtilRt.createIfNotExists(file);
}
public static boolean ensureCanCreateFile(@NotNull File file) {
return FileUtilRt.ensureCanCreateFile(file);
}
public static void copy(@NotNull File fromFile, @NotNull File toFile) throws IOException {
performCopy(fromFile, toFile, true);
}
public static void copyContent(@NotNull File fromFile, @NotNull File toFile) throws IOException {
performCopy(fromFile, toFile, false);
}
private static void performCopy(@NotNull File fromFile, @NotNull File toFile, final boolean syncTimestamp) throws IOException {
if (filesEqual(fromFile, toFile)) return;
final FileOutputStream fos = openOutputStream(toFile);
try {
final FileInputStream fis = new FileInputStream(fromFile);
try {
copy(fis, fos);
}
finally {
fis.close();
}
}
finally {
fos.close();
}
if (syncTimestamp) {
final long timeStamp = fromFile.lastModified();
if (timeStamp < 0) {
LOG.warn("Invalid timestamp " + timeStamp + " of '" + fromFile + "'");
}
else if (!toFile.setLastModified(timeStamp)) {
LOG.warn("Unable to set timestamp " + timeStamp + " to '" + toFile + "'");
}
}
if (SystemInfo.isUnix && fromFile.canExecute()) {
FileSystemUtil.clonePermissionsToExecute(fromFile.getPath(), toFile.getPath());
}
}
private static FileOutputStream openOutputStream(@NotNull final File file) throws IOException {
try {
return new FileOutputStream(file);
}
catch (FileNotFoundException e) {
final File parentFile = file.getParentFile();
if (parentFile == null) {
throw new IOException("Parent file is null for " + file.getPath(), e);
}
createParentDirs(file);
return new FileOutputStream(file);
}
}
public static void copy(@NotNull InputStream inputStream, @NotNull OutputStream outputStream) throws IOException {
FileUtilRt.copy(inputStream, outputStream);
}
public static void copy(@NotNull InputStream inputStream, int maxSize, @NotNull OutputStream outputStream) throws IOException {
copy(inputStream, (long)maxSize, outputStream);
}
public static void copy(@NotNull InputStream inputStream, long maxSize, @NotNull OutputStream outputStream) throws IOException {
final byte[] buffer = getThreadLocalBuffer();
long toRead = maxSize;
while (toRead > 0) {
int read = inputStream.read(buffer, 0, (int)Math.min(buffer.length, toRead));
if (read < 0) break;
toRead -= read;
outputStream.write(buffer, 0, read);
}
}
public static void copyFileOrDir(@NotNull File from, @NotNull File to) throws IOException {
copyFileOrDir(from, to, from.isDirectory());
}
public static void copyFileOrDir(@NotNull File from, @NotNull File to, boolean isDir) throws IOException {
if (isDir) {
copyDir(from, to);
}
else {
copy(from, to);
}
}
public static void copyDir(@NotNull File fromDir, @NotNull File toDir) throws IOException {
copyDir(fromDir, toDir, true);
}
/**
* Copies content of {@code fromDir} to {@code toDir}.
* It's equivalent to "cp -r fromDir/* toDir" unix command.
*
* @param fromDir source directory
* @param toDir destination directory
* @throws IOException in case of any IO troubles
*/
public static void copyDirContent(@NotNull File fromDir, @NotNull File toDir) throws IOException {
File[] children = ObjectUtils.notNull(fromDir.listFiles(), ArrayUtil.EMPTY_FILE_ARRAY);
for (File child : children) {
copyFileOrDir(child, new File(toDir, child.getName()));
}
}
public static void copyDir(@NotNull File fromDir, @NotNull File toDir, boolean copySystemFiles) throws IOException {
copyDir(fromDir, toDir, copySystemFiles ? null : new FileFilter() {
@Override
public boolean accept(@NotNull File file) {
return !StringUtil.startsWithChar(file.getName(), '.');
}
});
}
public static void copyDir(@NotNull File fromDir, @NotNull File toDir, @Nullable final FileFilter filter) throws IOException {
ensureExists(toDir);
if (isAncestor(fromDir, toDir, true)) {
LOG.error(fromDir.getAbsolutePath() + " is ancestor of " + toDir + ". Can't copy to itself.");
return;
}
File[] files = fromDir.listFiles();
if (files == null) throw new IOException(CommonBundle.message("exception.directory.is.invalid", fromDir.getPath()));
if (!fromDir.canRead()) throw new IOException(CommonBundle.message("exception.directory.is.not.readable", fromDir.getPath()));
for (File file : files) {
if (filter != null && !filter.accept(file)) {
continue;
}
if (file.isDirectory()) {
copyDir(file, new File(toDir, file.getName()), filter);
}
else {
copy(file, new File(toDir, file.getName()));
}
}
}
public static void ensureExists(@NotNull File dir) throws IOException {
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException(CommonBundle.message("exception.directory.can.not.create", dir.getPath()));
}
}
@NotNull
public static String getNameWithoutExtension(@NotNull File file) {
return getNameWithoutExtension(file.getName());
}
@NotNull
public static String getNameWithoutExtension(@NotNull String name) {
return FileUtilRt.getNameWithoutExtension(name);
}
public static String createSequentFileName(@NotNull File aParentFolder, @NotNull String aFilePrefix, @NotNull String aExtension) {
return findSequentNonexistentFile(aParentFolder, aFilePrefix, aExtension).getName();
}
@NotNull
public static File findSequentNonexistentFile(@NotNull File parentFolder, @NotNull String filePrefix, @NotNull String extension) {
int postfix = 0;
String ext = extension.isEmpty() ? "" : '.' + extension;
File candidate = new File(parentFolder, filePrefix + ext);
while (candidate.exists()) {
postfix++;
candidate = new File(parentFolder, filePrefix + postfix + ext);
}
return candidate;
}
@NotNull
public static String toSystemDependentName(@NotNull String aFileName) {
return FileUtilRt.toSystemDependentName(aFileName);
}
@NotNull
public static String toSystemIndependentName(@NotNull String aFileName) {
return FileUtilRt.toSystemIndependentName(aFileName);
}
/**
* Converts given path to canonical representation by eliminating '.'s, traversing '..'s, and omitting duplicate separators.
* Please note that this method is symlink-unfriendly (i.e. result of "/path/to/link/../next" most probably will differ from
* what {@link File#getCanonicalPath()} will return) - so use with care.<br>
* <br>
* If the path may contain symlinks, use {@link FileUtil#toCanonicalPath(String, boolean)} instead.
*/
@Contract("null -> null")
public static String toCanonicalPath(@Nullable String path) {
return toCanonicalPath(path, File.separatorChar, true);
}
/**
* When relative ../ parts do not escape outside of symlinks, the links are not expanded.<br>
* That is, in the best-case scenario the original non-expanded path is preserved.<br>
* <br>
* Otherwise, returns a fully resolved path using {@link File#getCanonicalPath()}.<br>
* <br>
* Consider the following case:
* <pre>
* root/
* dir1/
* link_to_dir1
* dir2/
* </pre>
* 'root/dir1/link_to_dir1/../dir2' should be resolved to 'root/dir2'
*/
@Contract("null, _ -> null")
public static String toCanonicalPath(@Nullable String path, boolean resolveSymlinksIfNecessary) {
return toCanonicalPath(path, File.separatorChar, true, resolveSymlinksIfNecessary);
}
@Contract("null, _ -> null")
public static String toCanonicalPath(@Nullable String path, char separatorChar) {
return toCanonicalPath(path, separatorChar, true);
}
@Contract("null -> null")
public static String toCanonicalUriPath(@Nullable String path) {
return toCanonicalPath(path, '/', false);
}
@Contract("null, _, _ -> null")
private static String toCanonicalPath(@Nullable String path, char separatorChar, boolean removeLastSlash) {
return toCanonicalPath(path, separatorChar, removeLastSlash, false);
}
@Contract("null, _, _, _ -> null")
private static String toCanonicalPath(@Nullable String path,
final char separatorChar,
final boolean removeLastSlash,
final boolean resolveSymlinks) {
if (path == null || path.isEmpty()) {
return path;
}
if (StringUtil.startsWithChar(path, '.')) {
if (path.length() == 1) {
return "";
}
char c = path.charAt(1);
if (c == '/' || c == separatorChar) {
path = path.substring(2);
}
}
path = path.replace(separatorChar, '/');
// trying to speedup the common case when there are no "//" or "/."
int index = -1;
do {
index = path.indexOf('/', index+1);
char next = index == path.length() - 1 ? 0 : path.charAt(index + 1);
if (next == '.' || next == '/') {
break;
}
}
while (index != -1);
if (index == -1) {
if (removeLastSlash) {
int start = processRoot(path, NullAppendable.INSTANCE);
int slashIndex = path.lastIndexOf('/');
return slashIndex != -1 && slashIndex > start ? StringUtil.trimTrailing(path, '/') : path;
}
return path;
}
final String finalPath = path;
NotNullProducer<String> realCanonicalPath = resolveSymlinks ? new NotNullProducer<String>() {
@NotNull
@Override
public String produce() {
try {
return new File(finalPath).getCanonicalPath().replace(separatorChar, '/');
}
catch (IOException ignore) {
// fall back to the default behavior
return toCanonicalPath(finalPath, separatorChar, removeLastSlash, false);
}
}
} : null;
StringBuilder result = new StringBuilder(path.length());
int start = processRoot(path, result);
int dots = 0;
boolean separator = true;
for (int i = start; i < path.length(); ++i) {
char c = path.charAt(i);
if (c == '/') {
if (!separator) {
if (!processDots(result, dots, start, resolveSymlinks)) {
return realCanonicalPath.produce();
}
dots = 0;
}
separator = true;
}
else if (c == '.') {
if (separator || dots > 0) {
++dots;
}
else {
result.append('.');
}
separator = false;
}
else {
if (dots > 0) {
StringUtil.repeatSymbol(result, '.', dots);
dots = 0;
}
result.append(c);
separator = false;
}
}
if (dots > 0) {
if (!processDots(result, dots, start, resolveSymlinks)) {
return realCanonicalPath.produce();
}
}
int lastChar = result.length() - 1;
if (removeLastSlash && lastChar >= 0 && result.charAt(lastChar) == '/' && lastChar > start) {
result.deleteCharAt(lastChar);
}
return result.toString();
}
private static int processRoot(@NotNull String path, @NotNull Appendable result) {
try {
if (SystemInfo.isWindows && path.length() > 1 && path.charAt(0) == '/' && path.charAt(1) == '/') {
result.append("//");
int hostStart = 2;
while (hostStart < path.length() && path.charAt(hostStart) == '/') hostStart++;
if (hostStart == path.length()) return hostStart;
int hostEnd = path.indexOf('/', hostStart);
if (hostEnd < 0) hostEnd = path.length();
result.append(path, hostStart, hostEnd);
result.append('/');
int shareStart = hostEnd;
while (shareStart < path.length() && path.charAt(shareStart) == '/') shareStart++;
if (shareStart == path.length()) return shareStart;
int shareEnd = path.indexOf('/', shareStart);
if (shareEnd < 0) shareEnd = path.length();
result.append(path, shareStart, shareEnd);
result.append('/');
return shareEnd;
}
if (!path.isEmpty() && path.charAt(0) == '/') {
result.append('/');
return 1;
}
if (path.length() > 2 && path.charAt(1) == ':' && path.charAt(2) == '/') {
result.append(path, 0, 3);
return 3;
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
return 0;
}
@Contract("_, _, _, false -> true")
private static boolean processDots(@NotNull StringBuilder result, int dots, int start, boolean resolveSymlinks) {
if (dots == 2) {
int pos = -1;
if (!StringUtil.endsWith(result, "/../") && !StringUtil.equals(result, "../")) {
pos = StringUtil.lastIndexOf(result, '/', start, result.length() - 1);
if (pos >= 0) {
++pos; // separator found, trim to next char
}
else if (start > 0) {
pos = start; // path is absolute, trim to root ('/..' -> '/')
}
else if (result.length() > 0) {
pos = 0; // path is relative, trim to default ('a/..' -> '')
}
}
if (pos >= 0) {
if (resolveSymlinks && FileSystemUtil.isSymLink(new File(result.toString()))) {
return false;
}
result.delete(pos, result.length());
}
else {
result.append("../"); // impossible to traverse, keep as-is
}
}
else if (dots != 1) {
StringUtil.repeatSymbol(result, '.', dots);
result.append('/');
}
return true;
}
/**
* converts back slashes to forward slashes
* removes double slashes inside the path, e.g. "x/y//z" => "x/y/z"
*/
@NotNull
public static String normalize(@NotNull String path) {
int start = 0;
boolean separator = false;
if (SystemInfo.isWindows) {
if (path.startsWith("//")) {
start = 2;
separator = true;
}
else if (path.startsWith("\\\\")) {
return normalizeTail(0, path, false);
}
}
for (int i = start; i < path.length(); ++i) {
final char c = path.charAt(i);
if (c == '/') {
if (separator) {
return normalizeTail(i, path, true);
}
separator = true;
}
else if (c == '\\') {
return normalizeTail(i, path, separator);
}
else {
separator = false;
}
}
return path;
}
@NotNull
private static String normalizeTail(int prefixEnd, @NotNull String path, boolean separator) {
final StringBuilder result = new StringBuilder(path.length());
result.append(path, 0, prefixEnd);
int start = prefixEnd;
if (start==0 && SystemInfo.isWindows && (path.startsWith("//") || path.startsWith("\\\\"))) {
start = 2;
result.append("//");
separator = true;
}
for (int i = start; i < path.length(); ++i) {
final char c = path.charAt(i);
if (c == '/' || c == '\\') {
if (!separator) result.append('/');
separator = true;
}
else {
result.append(c);
separator = false;
}
}
return result.toString();
}
@NotNull
public static String unquote(@NotNull String urlString) {
urlString = urlString.replace('/', File.separatorChar);
return URLUtil.unescapePercentSequences(urlString);
}
public static boolean isFilePathAcceptable(@NotNull File root, @Nullable FileFilter fileFilter) {
if (fileFilter == null) return true;
File file = root;
do {
if (!fileFilter.accept(file)) return false;
file = file.getParentFile();
}
while (file != null);
return true;
}
public static boolean rename(@NotNull File source, @NotNull String newName) throws IOException {
File target = new File(source.getParent(), newName);
if (!SystemInfo.isFileSystemCaseSensitive && newName.equalsIgnoreCase(source.getName())) {
File intermediate = createTempFile(source.getParentFile(), source.getName(), ".tmp", false, false);
return source.renameTo(intermediate) && intermediate.renameTo(target);
}
else {
return source.renameTo(target);
}
}
public static void rename(@NotNull File source, @NotNull File target) throws IOException {
if (source.renameTo(target)) return;
if (!source.exists()) return;
copy(source, target);
delete(source);
}
public static boolean filesEqual(@Nullable File file1, @Nullable File file2) {
// on MacOS java.io.File.equals() is incorrectly case-sensitive
return pathsEqual(file1 == null ? null : file1.getPath(),
file2 == null ? null : file2.getPath());
}
public static boolean pathsEqual(@Nullable String path1, @Nullable String path2) {
if (path1 == path2) return true;
if (path1 == null || path2 == null) return false;
path1 = toCanonicalPath(path1);
path2 = toCanonicalPath(path2);
return PATH_HASHING_STRATEGY.equals(path1, path2);
}
/**
* optimized version of pathsEqual - it only compares pure names, without file separators
*/
public static boolean namesEqual(@Nullable String name1, @Nullable String name2) {
if (name1 == name2) return true;
if (name1 == null || name2 == null) return false;
return PATH_HASHING_STRATEGY.equals(name1, name2);
}
public static int compareFiles(@Nullable File file1, @Nullable File file2) {
return comparePaths(file1 == null ? null : file1.getPath(), file2 == null ? null : file2.getPath());
}
public static int comparePaths(@Nullable String path1, @Nullable String path2) {
path1 = path1 == null ? null : toSystemIndependentName(path1);
path2 = path2 == null ? null : toSystemIndependentName(path2);
return StringUtil.compare(path1, path2, !SystemInfo.isFileSystemCaseSensitive);
}
public static int fileHashCode(@Nullable File file) {
return pathHashCode(file == null ? null : file.getPath());
}
public static int pathHashCode(@Nullable String path) {
return StringUtil.isEmpty(path) ? 0 : PATH_HASHING_STRATEGY.computeHashCode(toCanonicalPath(path));
}
/**
* @deprecated this method returns extension converted to lower case, this may not be correct for case-sensitive FS.
* Use {@link FileUtilRt#getExtension(String)} instead to get the unchanged extension.
* If you need to check whether a file has a specified extension use {@link FileUtilRt#extensionEquals(String, String)}
*/
@Deprecated
@SuppressWarnings("StringToUpperCaseOrToLowerCaseWithoutLocale")
@NotNull
public static String getExtension(@NotNull String fileName) {
return FileUtilRt.getExtension(fileName).toLowerCase();
}
@NotNull
public static String resolveShortWindowsName(@NotNull String path) throws IOException {
return SystemInfo.isWindows && containsWindowsShortName(path) ? new File(path).getCanonicalPath() : path;
}
public static boolean containsWindowsShortName(@NotNull String path) {
if (StringUtil.containsChar(path, '~')) {
path = toSystemIndependentName(path);
int start = 0;
while (start < path.length()) {
int end = path.indexOf('/', start);
if (end < 0) end = path.length();
// "How Windows Generates 8.3 File Names from Long File Names", https://support.microsoft.com/en-us/kb/142982
int dot = path.lastIndexOf('.', end);
if (dot < start) dot = end;
if (dot - start > 2 && dot - start <= 8 && end - dot - 1 <= 3 &&
path.charAt(dot - 2) == '~' && Character.isDigit(path.charAt(dot - 1))) {
return true;
}
start = end + 1;
}
}
return false;
}
public static void collectMatchedFiles(@NotNull File root, @NotNull Pattern pattern, @NotNull List<File> outFiles) {
collectMatchedFiles(root, root, pattern, outFiles);
}
private static void collectMatchedFiles(@NotNull File absoluteRoot,
@NotNull File root,
@NotNull Pattern pattern,
@NotNull List<? super File> files) {
final File[] dirs = root.listFiles();
if (dirs == null) return;
for (File dir : dirs) {
if (dir.isFile()) {
final String relativePath = getRelativePath(absoluteRoot, dir);
if (relativePath != null) {
final String path = toSystemIndependentName(relativePath);
if (pattern.matcher(path).matches()) {
files.add(dir);
}
}
}
else {
collectMatchedFiles(absoluteRoot, dir, pattern, files);
}
}
}
@RegExp
@NotNull
public static String convertAntToRegexp(@NotNull String antPattern) {
return convertAntToRegexp(antPattern, true);
}
/**
* @param antPattern ant-style path pattern
* @return java regexp pattern.
* Note that no matter whether forward or backward slashes were used in the antPattern
* the returned regexp pattern will use forward slashes ('/') as file separators.
* Paths containing windows-style backslashes must be converted before matching against the resulting regexp
* @see FileUtil#toSystemIndependentName
*/
@RegExp
@NotNull
public static String convertAntToRegexp(@NotNull String antPattern, boolean ignoreStartingSlash) {
final StringBuilder builder = new StringBuilder();
int asteriskCount = 0;
boolean recursive = true;
final int start =
ignoreStartingSlash && (StringUtil.startsWithChar(antPattern, '/') || StringUtil.startsWithChar(antPattern, '\\')) ? 1 : 0;
for (int idx = start; idx < antPattern.length(); idx++) {
final char ch = antPattern.charAt(idx);
if (ch == '*') {
asteriskCount++;
continue;
}
final boolean foundRecursivePattern = recursive && asteriskCount == 2 && (ch == '/' || ch == '\\');
final boolean asterisksFound = asteriskCount > 0;
asteriskCount = 0;
recursive = ch == '/' || ch == '\\';
if (foundRecursivePattern) {
builder.append("(?:[^/]+/)*?");
continue;
}
if (asterisksFound) {
builder.append("[^/]*?");
}
if (ch == '(' ||
ch == ')' ||
ch == '[' ||
ch == ']' ||
ch == '^' ||
ch == '$' ||
ch == '.' ||
ch == '{' ||
ch == '}' ||
ch == '+' ||
ch == '|') {
// quote regexp-specific symbols
builder.append('\\').append(ch);
continue;
}
if (ch == '?') {
builder.append("[^/]{1}");
continue;
}
if (ch == '\\') {
builder.append('/');
continue;
}
builder.append(ch);
}
// handle ant shorthand: my_package/test/ is interpreted as if it were my_package/test/**
final boolean isTrailingSlash = builder.length() > 0 && builder.charAt(builder.length() - 1) == '/';
if (asteriskCount == 0 && isTrailingSlash || recursive && asteriskCount == 2) {
if (isTrailingSlash) {
builder.setLength(builder.length() - 1);
}
if (builder.length() == 0) {
builder.append(".*");
}
else {
builder.append("(?:$|/.+)");
}
}
else if (asteriskCount > 0) {
builder.append("[^/]*?");
}
return builder.toString();
}
public static boolean moveDirWithContent(@NotNull File fromDir, @NotNull File toDir) {
if (!toDir.exists()) return fromDir.renameTo(toDir);
File[] files = fromDir.listFiles();
if (files == null) return false;
boolean success = true;
for (File fromFile : files) {
File toFile = new File(toDir, fromFile.getName());
success = success && fromFile.renameTo(toFile);
}
//noinspection ResultOfMethodCallIgnored
fromDir.delete();
return success;
}
@NotNull
public static String sanitizeFileName(@NotNull String name) {
return sanitizeFileName(name, true);
}
@NotNull
public static String sanitizeFileName(@NotNull String name, boolean strict) {
return sanitizeFileName(name, strict, "_");
}
@NotNull
public static String sanitizeFileName(@NotNull String name, boolean strict, String replacement) {
StringBuilder result = null;
int last = 0;
int length = name.length();
for (int i = 0; i < length; i++) {
char c = name.charAt(i);
boolean appendReplacement = true;
if (c > 0 && c < 255) {
if (strict
? Character.isLetterOrDigit(c) || c == '_'
: Character.isJavaIdentifierPart(c) || c == ' ' || c == '@' || c == '-') {
continue;
}
}
else {
appendReplacement = false;
}
if (result == null) {
result = new StringBuilder();
}
if (last < i) {
result.append(name, last, i);
}
if (appendReplacement) {
result.append(replacement);
}
last = i + 1;
}
if (result == null) {
return name;
}
if (last < length) {
result.append(name, last, length);
}
return result.toString();
}
public static boolean canExecute(@NotNull File file) {
return file.canExecute();
}
public static boolean canWrite(@NotNull String path) {
FileAttributes attributes = FileSystemUtil.getAttributes(path);
return attributes != null && attributes.isWritable();
}
public static void setReadOnlyAttribute(@NotNull String path, boolean readOnlyFlag) {
boolean writableFlag = !readOnlyFlag;
if (!new File(path).setWritable(writableFlag, false) && canWrite(path) != writableFlag) {
LOG.warn("Can't set writable attribute of '" + path + "' to '" + readOnlyFlag + "'");
}
}
public static void appendToFile(@NotNull File file, @NotNull String text) throws IOException {
writeToFile(file, text.getBytes(CharsetToolkit.UTF8_CHARSET), true);
}
public static void writeToFile(@NotNull File file, @NotNull byte[] text) throws IOException {
writeToFile(file, text, false);
}
public static void writeToFile(@NotNull File file, @NotNull String text) throws IOException {
writeToFile(file, text, false);
}
public static void writeToFile(@NotNull File file, @NotNull String text, boolean append) throws IOException {
writeToFile(file, text.getBytes(CharsetToolkit.UTF8_CHARSET), append);
}
public static void writeToFile(@NotNull File file, @NotNull byte[] text, int off, int len) throws IOException {
writeToFile(file, text, off, len, false);
}
public static void writeToFile(@NotNull File file, @NotNull byte[] text, boolean append) throws IOException {
writeToFile(file, text, 0, text.length, append);
}
private static void writeToFile(@NotNull File file, @NotNull byte[] text, int off, int len, boolean append) throws IOException {
createParentDirs(file);
OutputStream stream = new FileOutputStream(file, append);
try {
stream.write(text, off, len);
}
finally {
stream.close();
}
}
@NotNull
public static JBTreeTraverser<File> fileTraverser(@Nullable File root) {
return FILE_TRAVERSER.withRoot(root);
}
private static final JBTreeTraverser<File> FILE_TRAVERSER = JBTreeTraverser.from(new Function<File, Iterable<File>>() {
@Override
public Iterable<File> fun(File file) {
return file != null && file.isDirectory() ? JBIterable.of(file.listFiles()) : JBIterable.<File>empty();
}
});
public static boolean processFilesRecursively(@NotNull File root, @NotNull Processor<File> processor) {
return fileTraverser(root).bfsTraversal().processEach(processor);
}
/**
* @see FileUtil#fileTraverser(File)
*/
@Deprecated
public static boolean processFilesRecursively(@NotNull File root, @NotNull Processor<File> processor,
@Nullable final Processor<File> directoryFilter) {
final LinkedList<File> queue = new LinkedList<File>();
queue.add(root);
while (!queue.isEmpty()) {
final File file = queue.removeFirst();
if (!processor.process(file)) return false;
if (directoryFilter != null && (!file.isDirectory() || !directoryFilter.process(file))) continue;
final File[] children = file.listFiles();
if (children != null) {
ContainerUtil.addAll(queue, children);
}
}
return true;
}
@Nullable
public static File findFirstThatExist(@NotNull String... paths) {
for (String path : paths) {
if (!StringUtil.isEmptyOrSpaces(path)) {
File file = new File(toSystemDependentName(path));
if (file.exists()) return file;
}
}
return null;
}
@NotNull
public static List<File> findFilesByMask(@NotNull Pattern pattern, @NotNull File dir) {
final ArrayList<File> found = new ArrayList<File>();
final File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
found.addAll(findFilesByMask(pattern, file));
}
else if (pattern.matcher(file.getName()).matches()) {
found.add(file);
}
}
}
return found;
}
@NotNull
public static List<File> findFilesOrDirsByMask(@NotNull Pattern pattern, @NotNull File dir) {
final ArrayList<File> found = new ArrayList<File>();
final File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (pattern.matcher(file.getName()).matches()) {
found.add(file);
}
if (file.isDirectory()) {
found.addAll(findFilesOrDirsByMask(pattern, file));
}
}
}
return found;
}
/**
* Returns empty string for empty path.
* First checks whether provided path is a path of a file with sought-for name.
* Unless found, checks if provided file was a directory. In this case checks existence
* of child files with given names in order "as provided". Finally checks filename among
* brother-files of provided. Returns null if nothing found.
*
* @return path of the first of found files or empty string or null.
*/
@Nullable
public static String findFileInProvidedPath(String providedPath, String... fileNames) {
if (StringUtil.isEmpty(providedPath)) {
return "";
}
File providedFile = new File(providedPath);
if (providedFile.exists() && ArrayUtil.indexOf(fileNames, providedFile.getName()) >= 0) {
return toSystemDependentName(providedFile.getPath());
}
if (providedFile.isDirectory()) { //user chose folder with file
for (String fileName : fileNames) {
File file = new File(providedFile, fileName);
if (fileName.equals(file.getName()) && file.exists()) {
return toSystemDependentName(file.getPath());
}
}
}
providedFile = providedFile.getParentFile(); //users chose wrong file in same directory
if (providedFile != null && providedFile.exists()) {
for (String fileName : fileNames) {
File file = new File(providedFile, fileName);
if (fileName.equals(file.getName()) && file.exists()) {
return toSystemDependentName(file.getPath());
}
}
}
return null;
}
public static boolean isAbsolutePlatformIndependent(@NotNull String path) {
return isUnixAbsolutePath(path) || isWindowsAbsolutePath(path);
}
public static boolean isUnixAbsolutePath(@NotNull String path) {
return path.startsWith("/");
}
public static boolean isWindowsAbsolutePath(@NotNull String path) {
boolean ok = path.length() >= 2 && Character.isLetter(path.charAt(0)) && path.charAt(1) == ':';
if (ok && path.length() > 2) {
char separatorChar = path.charAt(2);
ok = separatorChar == '/' || separatorChar == '\\';
}
return ok;
}
@Contract("null -> null; !null -> !null")
public static String getLocationRelativeToUserHome(@Nullable String path) {
return getLocationRelativeToUserHome(path, true);
}
@Contract("null,_ -> null; !null,_ -> !null")
public static String getLocationRelativeToUserHome(@Nullable String path, boolean unixOnly) {
if (path == null) return null;
if (SystemInfo.isUnix || !unixOnly) {
File projectDir = new File(path);
File userHomeDir = new File(SystemProperties.getUserHome());
if (isAncestor(userHomeDir, projectDir, true)) {
return '~' + File.separator + getRelativePath(userHomeDir, projectDir);
}
}
return path;
}
@NotNull
public static String expandUserHome(@NotNull String path) {
if (path.startsWith("~/") || path.startsWith("~\\")) {
path = SystemProperties.getUserHome() + path.substring(1);
}
return path;
}
@NotNull
public static File[] notNullize(@Nullable File[] files) {
return notNullize(files, ArrayUtil.EMPTY_FILE_ARRAY);
}
@NotNull
public static File[] notNullize(@Nullable File[] files, @NotNull File[] defaultFiles) {
return files == null ? defaultFiles : files;
}
public static boolean isHashBangLine(@Nullable CharSequence firstCharsIfText, @NotNull String marker) {
if (firstCharsIfText == null) {
return false;
}
if (!StringUtil.startsWith(firstCharsIfText, "#!")) {
return false;
}
final int lineBreak = StringUtil.indexOf(firstCharsIfText, '\n', 2);
return lineBreak >= 0 && StringUtil.indexOf(firstCharsIfText, marker, 2, lineBreak) != -1;
}
@NotNull
public static File createTempDirectory(@NotNull String prefix, @Nullable String suffix) throws IOException {
return FileUtilRt.createTempDirectory(prefix, suffix);
}
@NotNull
public static File createTempDirectory(@NotNull String prefix, @Nullable String suffix, boolean deleteOnExit)
throws IOException {
return FileUtilRt.createTempDirectory(prefix, suffix, deleteOnExit);
}
@NotNull
public static File createTempDirectory(@NotNull File dir, @NotNull String prefix, @Nullable String suffix)
throws IOException {
return FileUtilRt.createTempDirectory(dir, prefix, suffix);
}
@NotNull
public static File createTempDirectory(@NotNull File dir,
@NotNull String prefix,
@Nullable String suffix,
boolean deleteOnExit) throws IOException {
return FileUtilRt.createTempDirectory(dir, prefix, suffix, deleteOnExit);
}
@NotNull
public static File createTempFile(@NotNull String prefix, @Nullable String suffix) throws IOException {
return FileUtilRt.createTempFile(prefix, suffix);
}
@NotNull
public static File createTempFile(@NotNull String prefix, @Nullable String suffix, boolean deleteOnExit)
throws IOException {
return FileUtilRt.createTempFile(prefix, suffix, deleteOnExit);
}
@NotNull
public static File createTempFile(File dir, @NotNull String prefix, @Nullable String suffix) throws IOException {
return FileUtilRt.createTempFile(dir, prefix, suffix);
}
@NotNull
public static File createTempFile(File dir, @NotNull String prefix, @Nullable String suffix, boolean create)
throws IOException {
return FileUtilRt.createTempFile(dir, prefix, suffix, create);
}
@NotNull
public static File createTempFile(File dir,
@NotNull String prefix,
@Nullable String suffix,
boolean create,
boolean deleteOnExit) throws IOException {
return FileUtilRt.createTempFile(dir, prefix, suffix, create, deleteOnExit);
}
@NotNull
public static String getTempDirectory() {
return FileUtilRt.getTempDirectory();
}
@TestOnly
public static void resetCanonicalTempPathCache(final String tempPath) {
FileUtilRt.resetCanonicalTempPathCache(tempPath);
}
@NotNull
public static File generateRandomTemporaryPath() throws IOException {
return FileUtilRt.generateRandomTemporaryPath();
}
public static void setExecutableAttribute(@NotNull String path, boolean executableFlag) throws IOException {
FileUtilRt.setExecutableAttribute(path, executableFlag);
}
public static void setLastModified(@NotNull File file, long timeStamp) throws IOException {
if (!file.setLastModified(timeStamp)) {
LOG.warn(file.getPath());
}
}
@NotNull
public static String loadFile(@NotNull File file) throws IOException {
return FileUtilRt.loadFile(file);
}
@NotNull
public static String loadFile(@NotNull File file, boolean convertLineSeparators) throws IOException {
return FileUtilRt.loadFile(file, convertLineSeparators);
}
@NotNull
public static String loadFile(@NotNull File file, @Nullable String encoding) throws IOException {
return FileUtilRt.loadFile(file, encoding);
}
@NotNull
public static String loadFile(@NotNull File file, @NotNull Charset encoding) throws IOException {
return String.valueOf(FileUtilRt.loadFileText(file, encoding));
}
@NotNull
public static String loadFile(@NotNull File file, @Nullable String encoding, boolean convertLineSeparators) throws IOException {
return FileUtilRt.loadFile(file, encoding, convertLineSeparators);
}
@NotNull
public static char[] loadFileText(@NotNull File file) throws IOException {
return FileUtilRt.loadFileText(file);
}
@NotNull
public static char[] loadFileText(@NotNull File file, @Nullable String encoding) throws IOException {
return FileUtilRt.loadFileText(file, encoding);
}
@NotNull
public static char[] loadText(@NotNull Reader reader, int length) throws IOException {
return FileUtilRt.loadText(reader, length);
}
@NotNull
public static List<String> loadLines(@NotNull File file) throws IOException {
return FileUtilRt.loadLines(file);
}
@NotNull
public static List<String> loadLines(@NotNull File file, @Nullable String encoding) throws IOException {
return FileUtilRt.loadLines(file, encoding);
}
@NotNull
public static List<String> loadLines(@NotNull String path) throws IOException {
return FileUtilRt.loadLines(path);
}
@NotNull
public static List<String> loadLines(@NotNull String path, @Nullable String encoding) throws IOException {
return FileUtilRt.loadLines(path, encoding);
}
@NotNull
public static List<String> loadLines(@NotNull BufferedReader reader) throws IOException {
return FileUtilRt.loadLines(reader);
}
@NotNull
public static byte[] loadBytes(@NotNull InputStream stream) throws IOException {
return FileUtilRt.loadBytes(stream);
}
@NotNull
public static byte[] loadBytes(@NotNull InputStream stream, int length) throws IOException {
return FileUtilRt.loadBytes(stream, length);
}
@NotNull
public static List<String> splitPath(@NotNull String path) {
ArrayList<String> list = new ArrayList<String>();
int index = 0;
int nextSeparator;
while ((nextSeparator = path.indexOf(File.separatorChar, index)) != -1) {
list.add(path.substring(index, nextSeparator));
index = nextSeparator + 1;
}
list.add(path.substring(index));
return list;
}
public static boolean isJarOrZip(@NotNull File file) {
if (file.isDirectory()) {
return false;
}
final String name = file.getName();
return StringUtil.endsWithIgnoreCase(name, ".jar") || StringUtil.endsWithIgnoreCase(name, ".zip");
}
public static boolean visitFiles(@NotNull File root, @NotNull Processor<? super File> processor) {
if (!processor.process(root)) {
return false;
}
File[] children = root.listFiles();
if (children != null) {
for (File child : children) {
if (!visitFiles(child, processor)) {
return false;
}
}
}
return true;
}
/**
* Like {@link Properties#load(Reader)}, but preserves the order of key/value pairs.
*/
@NotNull
public static Map<String, String> loadProperties(@NotNull Reader reader) throws IOException {
final Map<String, String> map = ContainerUtil.newLinkedHashMap();
new Properties() {
@Override
public synchronized Object put(Object key, Object value) {
map.put(String.valueOf(key), String.valueOf(value));
//noinspection UseOfPropertiesAsHashtable
return super.put(key, value);
}
}.load(reader);
return map;
}
public static boolean isRootPath(@NotNull String path) {
return path.equals("/") || path.matches("[a-zA-Z]:[/\\\\]");
}
public static boolean deleteWithRenaming(File file) {
File tempFileNameForDeletion = findSequentNonexistentFile(file.getParentFile(), file.getName(), "");
boolean success = file.renameTo(tempFileNameForDeletion);
return delete(success ? tempFileNameForDeletion:file);
}
public static boolean isFileSystemCaseSensitive(@NotNull String path) throws FileNotFoundException {
FileAttributes attributes = FileSystemUtil.getAttributes(path);
if (attributes == null) {
throw new FileNotFoundException(path);
}
FileAttributes upper = FileSystemUtil.getAttributes(path.toUpperCase(Locale.ENGLISH));
FileAttributes lower = FileSystemUtil.getAttributes(path.toLowerCase(Locale.ENGLISH));
return !(attributes.equals(upper) && attributes.equals(lower));
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/searchmem/MemSearchResultToProgramLocationTableRowMapper.java | 1204 | /* ###
* 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 ghidra.app.plugin.core.searchmem;
import ghidra.framework.plugintool.ServiceProvider;
import ghidra.program.model.listing.Program;
import ghidra.program.util.ProgramLocation;
import ghidra.util.search.memory.MemSearchResult;
import ghidra.util.table.ProgramLocationTableRowMapper;
public class MemSearchResultToProgramLocationTableRowMapper
extends ProgramLocationTableRowMapper<MemSearchResult, ProgramLocation> {
@Override
public ProgramLocation map(MemSearchResult rowObject, Program program,
ServiceProvider serviceProvider) {
return new ProgramLocation(program, rowObject.getAddress());
}
}
| apache-2.0 |
0XDE57/SpaceProject | core/src/com/spaceproject/systems/WorldLoadingSystem.java | 2069 | package com.spaceproject.systems;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.EntitySystem;
import com.badlogic.gdx.utils.Array;
import com.spaceproject.SpaceProject;
import com.spaceproject.components.AIComponent;
import com.spaceproject.components.PlanetComponent;
import com.spaceproject.config.WorldConfig;
import com.spaceproject.generation.EntityFactory;
import com.spaceproject.screens.GameScreen;
import com.spaceproject.utility.Mappers;
public class WorldLoadingSystem extends EntitySystem {
@Override
public void addedToEngine(Engine engine) {
initMobs(engine);
}
private void initMobs(Engine engine) {
WorldConfig worldCFG = SpaceProject.configManager.getConfig(WorldConfig.class);
int mapSize = GameScreen.getCurrentPlanet().getComponent(PlanetComponent.class).mapSize;
//a placeholder to add dummy objects for now
// test ships
int position = mapSize * worldCFG.tileSize / 2;//set position to middle of planet
Array<Entity> basicShipCluster = EntityFactory.createBasicShip(position + 10, position + 10, GameScreen.inSpace());
for (Entity e : basicShipCluster) {
engine.addEntity(e);
}
Array<Entity> basicShipCluster2 = EntityFactory.createBasicShip(position - 10, position + 10, GameScreen.inSpace());
for (Entity e : basicShipCluster2) {
engine.addEntity(e);
}
Entity aiTest = EntityFactory.createCharacterAI(position, position + 10);
Mappers.AI.get(aiTest).state = AIComponent.State.dumbwander;
engine.addEntity(aiTest);
/*
Entity aiTest2 = EntityFactory.createCharacterAI(position, position - 500);
Mappers.AI.get(aiTest2).State = AIComponent.State.takeOffPlanet;
engine.addEntity(aiTest2);
*/
engine.addEntity(EntityFactory.createWall(position + 5, position + 5, 8, 16));
engine.addEntity(EntityFactory.createWall(position + 9, position + 5, 16, 8));
}
}
| apache-2.0 |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/logging/DevelopmentLogger.java | 2130 | /*
* Copyright (C) 2015 Saúl Díaz
*
* 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.sefford.material.sample.common.logging;
import android.content.Context;
import android.util.Log;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* Development Logger based on Jorge Rodriguez <tylosan@gmail.com> on how things should log on debug
*
* @author Saul Diaz <sefford@gmail.com>
* @author Jorge Rodriguez <tylosan@gmail.com>
*/
@Singleton
public class DevelopmentLogger implements Logger {
@Inject
public DevelopmentLogger() {
}
@Override
public void bind(Context context) {
// Nothing for DevelopmentLogger
}
@Override
public void identify(long userId) {
// This is a Production feature
}
@Override
public void e(String logtag, String message) {
Log.e(logtag, message);
}
@Override
public void e(String logtag, String message, Throwable e) {
Log.e(logtag, message, e);
}
@Override
public void d(String logtag, String message) {
Log.d(logtag, message);
}
@Override
public void w(String logtag, String message) {
Log.w(logtag, message);
}
@Override
public void w(String logtag, String message, Throwable e) {
Log.w(logtag, message, e);
}
@Override
public void v(String logtag, String message) {
Log.v(logtag, message);
}
@Override
public void printPerformanceLog(String tag, String element, long start) {
d(tag, "(" + element + "):" + (System.currentTimeMillis() - start) + "ms");
}
}
| apache-2.0 |
cf0566/CarMarket | src/com/cpic/carmarket/bean/FormDataInfoDetails4.java | 861 | package com.cpic.carmarket.bean;
import java.util.ArrayList;
public class FormDataInfoDetails4 {
private String score;
private String score_content;
private ArrayList<String> img;
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getScore_content() {
return score_content;
}
public void setScore_content(String score_content) {
this.score_content = score_content;
}
public ArrayList<String> getImg() {
return img;
}
public void setImg(ArrayList<String> img) {
this.img = img;
}
@Override
public String toString() {
return "FormDataInfoDetails4 [score=" + score + ", score_content="
+ score_content + ", img=" + img + "]";
}
public FormDataInfoDetails4() {
super();
// TODO Auto-generated constructor stub
}
}
| apache-2.0 |
hortonworks/cloudbreak | freeipa/src/test/java/com/sequenceiq/freeipa/service/freeipa/user/ums/UmsUsersStateProviderDispatcherTest.java | 5491 | package com.sequenceiq.freeipa.service.freeipa.user.ums;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.sequenceiq.cloudbreak.auth.crn.CrnResourceDescriptor;
import com.sequenceiq.cloudbreak.auth.crn.CrnTestUtil;
import com.sequenceiq.freeipa.service.freeipa.user.model.UmsUsersState;
import com.sequenceiq.freeipa.service.freeipa.user.model.UsersState;
import io.grpc.StatusRuntimeException;
@ExtendWith(MockitoExtension.class)
class UmsUsersStateProviderDispatcherTest {
private static final String ACCOUNT_ID = UUID.randomUUID().toString();
private static final Set<String> ENVIRONMENT_CRNS = Set.of(
CrnTestUtil.getEnvironmentCrnBuilder()
.setAccountId(ACCOUNT_ID)
.setResource(UUID.randomUUID().toString())
.build()
.toString()
);
@Mock
private DefaultUmsUsersStateProvider defaultUmsUsersStateProvider;
@Mock
private BulkUmsUsersStateProvider bulkUmsUsersStateProvider;
@InjectMocks
private UmsUsersStateProviderDispatcher underTest;
@Test
void testFullSync() {
Set<String> userCrns = Set.of();
Set<String> machineUserCrns = Set.of();
Map<String, UmsUsersState> expected = createExpectedResponse();
when(bulkUmsUsersStateProvider.get(anyString(), any(Set.class), any(Optional.class)))
.thenReturn(expected);
Optional<String> requestIdOptional = Optional.of(UUID.randomUUID().toString());
Map<String, UmsUsersState> response = underTest.getEnvToUmsUsersStateMap(
ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional);
assertEquals(expected, response);
verify(bulkUmsUsersStateProvider).get(ACCOUNT_ID, ENVIRONMENT_CRNS, requestIdOptional);
verify(defaultUmsUsersStateProvider, never()).get(anyString(), any(Set.class),
any(Set.class), any(Set.class), any(Optional.class), anyBoolean());
}
@Test
void testBulkFallsBackToDefault() {
Set<String> userCrns = Set.of();
Set<String> machineUserCrns = Set.of();
when(bulkUmsUsersStateProvider.get(anyString(), any(Set.class), any(Optional.class)))
.thenThrow(StatusRuntimeException.class);
Map<String, UmsUsersState> expected = createExpectedResponse();
when(defaultUmsUsersStateProvider.get(anyString(), any(Set.class),
any(Set.class), any(Set.class), any(Optional.class), anyBoolean()))
.thenReturn(expected);
Optional<String> requestIdOptional = Optional.of(UUID.randomUUID().toString());
Map<String, UmsUsersState> response = underTest.getEnvToUmsUsersStateMap(
ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional);
assertEquals(expected, response);
verify(bulkUmsUsersStateProvider).get(ACCOUNT_ID, ENVIRONMENT_CRNS, requestIdOptional);
verify(defaultUmsUsersStateProvider).get(ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional, true);
}
@Test
void testPartialSync() {
Set<String> userCrns = Set.of(createActorCrn(CrnResourceDescriptor.USER));
Set<String> machineUserCrns = Set.of(createActorCrn(CrnResourceDescriptor.MACHINE_USER));
Map<String, UmsUsersState> expected = createExpectedResponse();
when(defaultUmsUsersStateProvider.get(anyString(), any(Set.class),
any(Set.class), any(Set.class), any(Optional.class), anyBoolean()))
.thenReturn(expected);
Optional<String> requestIdOptional = Optional.of(UUID.randomUUID().toString());
Map<String, UmsUsersState> response = underTest.getEnvToUmsUsersStateMap(
ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional);
assertEquals(expected, response);
verify(bulkUmsUsersStateProvider, never()).get(ACCOUNT_ID, ENVIRONMENT_CRNS, requestIdOptional);
verify(defaultUmsUsersStateProvider).get(ACCOUNT_ID, ENVIRONMENT_CRNS,
userCrns, machineUserCrns, requestIdOptional, false);
}
private Map<String, UmsUsersState> createExpectedResponse() {
return ENVIRONMENT_CRNS.stream()
.collect(Collectors.toMap(Function.identity(),
env -> UmsUsersState.newBuilder()
.setUsersState(UsersState.newBuilder().build())
.build()));
}
private String createActorCrn(CrnResourceDescriptor resourceDescriptor) {
return CrnTestUtil.getCustomCrnBuilder(resourceDescriptor)
.setAccountId(ACCOUNT_ID)
.build()
.toString();
}
} | apache-2.0 |
hortonworks/cloudbreak | cloud-template/src/main/java/com/sequenceiq/cloudbreak/cloud/template/compute/CloudFailureHandler.java | 11934 | package com.sequenceiq.cloudbreak.cloud.template.compute;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Service;
import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext;
import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException;
import com.sequenceiq.cloudbreak.cloud.exception.RolledbackResourcesException;
import com.sequenceiq.cloudbreak.cloud.model.CloudInstance;
import com.sequenceiq.cloudbreak.cloud.model.CloudResource;
import com.sequenceiq.cloudbreak.cloud.model.CloudResourceStatus;
import com.sequenceiq.cloudbreak.cloud.model.Group;
import com.sequenceiq.cloudbreak.cloud.model.InstanceTemplate;
import com.sequenceiq.cloudbreak.cloud.model.ResourceStatus;
import com.sequenceiq.cloudbreak.cloud.model.Variant;
import com.sequenceiq.cloudbreak.cloud.template.ComputeResourceBuilder;
import com.sequenceiq.cloudbreak.cloud.template.context.ResourceBuilderContext;
import com.sequenceiq.cloudbreak.cloud.template.init.ResourceBuilders;
import com.sequenceiq.common.api.type.AdjustmentType;
import com.sequenceiq.common.api.type.ResourceType;
@Service
public class CloudFailureHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(CloudFailureHandler.class);
private static final double ONE_HUNDRED = 100.0;
@Inject
private AsyncTaskExecutor resourceBuilderExecutor;
@Inject
private ResourceActionFactory resourceActionFactory;
public void rollbackIfNecessary(CloudFailureContext cloudFailureContext, List<CloudResourceStatus> failuresList, List<CloudResourceStatus> resourceStatuses,
Group group, ResourceBuilders resourceBuilders, Integer requestedNodeCount) {
if (failuresList.isEmpty()) {
return;
}
LOGGER.debug("Roll back the following resources: {}", failuresList);
doRollback(cloudFailureContext, failuresList, resourceStatuses, group, requestedNodeCount, resourceBuilders);
}
private void doRollback(CloudFailureContext cloudFailureContext, List<CloudResourceStatus> failuresList, List<CloudResourceStatus> resourceStatuses,
Group group, Integer requestedNodeCount, ResourceBuilders resourceBuilders) {
Set<Long> failures = failureCount(failuresList);
ScaleContext stx = cloudFailureContext.getStx();
AuthenticatedContext auth = cloudFailureContext.getAuth();
ResourceBuilderContext ctx = cloudFailureContext.getCtx();
if (stx.getAdjustmentType() == null && !failures.isEmpty()) {
LOGGER.info("Failure policy is null so error will be thrown");
throwError(failuresList);
}
LOGGER.info("Adjustment type is {}", stx.getAdjustmentType());
switch (stx.getAdjustmentType()) {
case EXACT:
if (stx.getThreshold() > requestedNodeCount - failures.size()) {
LOGGER.info("Number of failures is more than the threshold ({}) so error will be thrown", stx.getThreshold());
rollbackEverythingAndThrowException(failuresList, resourceStatuses, group, resourceBuilders, stx, auth, ctx);
} else if (!failures.isEmpty()) {
LOGGER.info("Decrease node counts because threshold was higher");
handleExceptions(auth, resourceStatuses, group, ctx, resourceBuilders, failures, stx.getUpscale());
}
break;
case PERCENTAGE:
double calculatedPercentage = calculatePercentage(failures.size(), requestedNodeCount);
Double threshold = Double.valueOf(stx.getThreshold());
if (threshold > calculatedPercentage) {
LOGGER.info("Calculated percentage ({}) is lower than threshold, do rollback ({})", calculatedPercentage, threshold);
rollbackEverythingAndThrowException(failuresList, resourceStatuses, group, resourceBuilders, stx, auth, ctx);
} else if (!failures.isEmpty()) {
LOGGER.info("Decrease node counts because threshold was higher");
handleExceptions(auth, resourceStatuses, group, ctx, resourceBuilders, failures, stx.getUpscale());
}
break;
case BEST_EFFORT:
LOGGER.info("Decrease node counts because threshold was higher");
handleExceptions(auth, resourceStatuses, group, ctx, resourceBuilders, failures, stx.getUpscale());
break;
default:
LOGGER.info("Unsupported adjustment type so error will throw");
rollbackEverythingAndThrowException(failuresList, resourceStatuses, group, resourceBuilders, stx, auth, ctx);
break;
}
}
private void rollbackEverythingAndThrowException(List<CloudResourceStatus> failuresList, List<CloudResourceStatus> resourceStatuses,
Group group, ResourceBuilders resourceBuilders, ScaleContext stx, AuthenticatedContext auth, ResourceBuilderContext ctx) {
Set<Long> rollbackIds = resourceStatuses.stream().map(CloudResourceStatus::getPrivateId).collect(Collectors.toSet());
doRollback(auth, resourceStatuses, rollbackIds, group, ctx, resourceBuilders, stx.getUpscale());
throwRolledbackException(failuresList);
}
private Set<Long> failureCount(Collection<CloudResourceStatus> failedResourceRequestResults) {
Set<Long> ids = new HashSet<>(failedResourceRequestResults.size());
for (CloudResourceStatus failedResourceRequestResult : failedResourceRequestResults) {
if (ResourceStatus.FAILED.equals(failedResourceRequestResult.getStatus())) {
ids.add(failedResourceRequestResult.getPrivateId());
}
}
return ids;
}
private double calculatePercentage(double failedResourceRequestResults, double requestedNodeCount) {
double calculatedPercentage = (requestedNodeCount - failedResourceRequestResults) / requestedNodeCount * ONE_HUNDRED;
LOGGER.info("Calculated percentage: {}", calculatedPercentage);
return calculatedPercentage;
}
private void handleExceptions(AuthenticatedContext auth, List<CloudResourceStatus> cloudResourceStatuses, Group group,
ResourceBuilderContext ctx, ResourceBuilders resourceBuilders, Collection<Long> ids, Boolean upscale) {
List<CloudResource> resources = new ArrayList<>(cloudResourceStatuses.size());
for (CloudResourceStatus exception : cloudResourceStatuses) {
if (ResourceStatus.FAILED.equals(exception.getStatus()) || ids.contains(exception.getPrivateId())) {
LOGGER.info("Failed to create instance with id '" + exception.getPrivateId() + "'. Reason: " + exception.getStatusReason());
resources.add(exception.getCloudResource());
}
}
if (!resources.isEmpty()) {
LOGGER.info("Resource list not empty so rollback will start.Resource list size is: " + resources.size());
doRollback(auth, cloudResourceStatuses, ids, group, ctx, resourceBuilders, upscale);
}
}
private void doRollback(AuthenticatedContext auth, List<CloudResourceStatus> statuses, Collection<Long> rollbackIds, Group group,
ResourceBuilderContext ctx, ResourceBuilders resourceBuilders, Boolean upscale) {
Variant variant = auth.getCloudContext().getVariant();
LOGGER.info("Rollback resources for the following private ids: {}", rollbackIds);
if (getRemovableInstanceTemplates(group, rollbackIds).size() <= 0 && !upscale) {
LOGGER.info("InstanceGroup node count lower than 1 which is incorrect so error will be thrown");
throwError(statuses);
} else {
Map<ResourceType, ComputeResourceBuilder<ResourceBuilderContext>> resourceBuilderMap = getResourceBuilderMap(resourceBuilders, variant);
for (CloudResourceStatus cloudResourceStatus : statuses) {
try {
if (rollbackIds.contains(cloudResourceStatus.getPrivateId())) {
ComputeResourceBuilder<ResourceBuilderContext> resourceBuilderForType =
resourceBuilderMap.get(cloudResourceStatus.getCloudResource().getType());
deleteResource(auth, ctx, resourceBuilderForType, cloudResourceStatus);
}
} catch (Exception e) {
LOGGER.warn("Resource can not be deleted. Reason: " + e.getMessage(), e);
}
}
}
}
@NotNull
private Map<ResourceType, ComputeResourceBuilder<ResourceBuilderContext>> getResourceBuilderMap(ResourceBuilders resourceBuilders, Variant variant) {
List<ComputeResourceBuilder<ResourceBuilderContext>> computeResourceBuilders = resourceBuilders.compute(variant);
Map<ResourceType, ComputeResourceBuilder<ResourceBuilderContext>> resourceBuilderMap = new HashMap<>();
for (ComputeResourceBuilder<ResourceBuilderContext> resourceBuilder : computeResourceBuilders) {
resourceBuilderMap.put(resourceBuilder.resourceType(), resourceBuilder);
}
return resourceBuilderMap;
}
private void deleteResource(AuthenticatedContext auth, ResourceBuilderContext ctx, ComputeResourceBuilder<ResourceBuilderContext> resourceBuilder,
CloudResourceStatus cloudResourceStatus) throws ExecutionException, InterruptedException {
ResourceDeletionCallablePayload payload = new ResourceDeletionCallablePayload(ctx, auth, cloudResourceStatus.getCloudResource(),
resourceBuilder, false);
ResourceDeletionCallable deletionCallable = resourceActionFactory.buildDeletionCallable(payload);
resourceBuilderExecutor.submit(deletionCallable).get();
}
private Collection<InstanceTemplate> getRemovableInstanceTemplates(Group group, Collection<Long> ids) {
Collection<InstanceTemplate> instanceTemplates = new ArrayList<>();
for (CloudInstance cloudInstance : group.getInstances()) {
InstanceTemplate instanceTemplate = cloudInstance.getTemplate();
if (!ids.contains(instanceTemplate.getPrivateId())) {
instanceTemplates.add(instanceTemplate);
}
}
return instanceTemplates;
}
private void throwRolledbackException(List<CloudResourceStatus> statuses) {
throw new RolledbackResourcesException("Resources are rolled back because successful node count was lower than threshold. "
+ statuses.size() + " nodes are failed. Error reason: " + statuses.get(0).getStatusReason());
}
private void throwError(List<CloudResourceStatus> statuses) {
throw new CloudConnectorException(statuses.get(0).getStatusReason());
}
public static class ScaleContext {
private final Boolean upscale;
private final AdjustmentType adjustmentType;
private final Long threshold;
public ScaleContext(Boolean upscale, AdjustmentType adjustmentType, Long threshold) {
this.upscale = upscale;
this.adjustmentType = adjustmentType;
this.threshold = threshold;
}
public Boolean getUpscale() {
return upscale;
}
public AdjustmentType getAdjustmentType() {
return adjustmentType;
}
public Long getThreshold() {
return threshold;
}
}
}
| apache-2.0 |
lmjacksoniii/hazelcast | hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/atomicreference/AtomicReferenceApplyMessageTask.java | 2725 | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.impl.protocol.task.atomicreference;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.AtomicReferenceApplyCodec;
import com.hazelcast.client.impl.protocol.task.AbstractPartitionMessageTask;
import com.hazelcast.concurrent.atomicreference.AtomicReferenceService;
import com.hazelcast.concurrent.atomicreference.operations.ApplyOperation;
import com.hazelcast.instance.Node;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.security.permission.ActionConstants;
import com.hazelcast.security.permission.AtomicReferencePermission;
import com.hazelcast.spi.Operation;
import java.security.Permission;
public class AtomicReferenceApplyMessageTask
extends AbstractPartitionMessageTask<AtomicReferenceApplyCodec.RequestParameters> {
public AtomicReferenceApplyMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
super(clientMessage, node, connection);
}
@Override
protected Operation prepareOperation() {
return new ApplyOperation(parameters.name, parameters.function);
}
@Override
protected AtomicReferenceApplyCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) {
return AtomicReferenceApplyCodec.decodeRequest(clientMessage);
}
@Override
protected ClientMessage encodeResponse(Object response) {
return AtomicReferenceApplyCodec.encodeResponse((Data) response);
}
@Override
public String getServiceName() {
return AtomicReferenceService.SERVICE_NAME;
}
@Override
public Permission getRequiredPermission() {
return new AtomicReferencePermission(parameters.name, ActionConstants.ACTION_READ);
}
@Override
public String getDistributedObjectName() {
return parameters.name;
}
@Override
public String getMethodName() {
return "apply";
}
@Override
public Object[] getParameters() {
return new Object[]{parameters.function};
}
}
| apache-2.0 |
pericles-project/ProcessCompiler | src/generated-sources/java/org/omg/spec/bpmn/_20100524/model/TCorrelationProperty.java | 3706 |
package org.omg.spec.bpmn._20100524.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
/**
* <p>Java class for tCorrelationProperty complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="tCorrelationProperty">
* <complexContent>
* <extension base="{http://www.omg.org/spec/BPMN/20100524/MODEL}tRootElement">
* <sequence>
* <element ref="{http://www.omg.org/spec/BPMN/20100524/MODEL}correlationPropertyRetrievalExpression" maxOccurs="unbounded"/>
* </sequence>
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}QName" />
* <anyAttribute processContents='lax' namespace='##other'/>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tCorrelationProperty", propOrder = {
"correlationPropertyRetrievalExpressions"
})
public class TCorrelationProperty
extends TRootElement
{
@XmlElement(name = "correlationPropertyRetrievalExpression", required = true)
protected List<CorrelationPropertyRetrievalExpression> correlationPropertyRetrievalExpressions;
@XmlAttribute(name = "name")
protected String name;
@XmlAttribute(name = "type")
protected QName type;
/**
* Gets the value of the correlationPropertyRetrievalExpressions property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the correlationPropertyRetrievalExpressions property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCorrelationPropertyRetrievalExpressions().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CorrelationPropertyRetrievalExpression }
*
*
*/
public List<CorrelationPropertyRetrievalExpression> getCorrelationPropertyRetrievalExpressions() {
if (correlationPropertyRetrievalExpressions == null) {
correlationPropertyRetrievalExpressions = new ArrayList<CorrelationPropertyRetrievalExpression>();
}
return this.correlationPropertyRetrievalExpressions;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link QName }
*
*/
public QName getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link QName }
*
*/
public void setType(QName value) {
this.type = value;
}
}
| apache-2.0 |
zoozooll/MyExercise | shelves/Shelves/src/org/curiouscreature/android/shelves/util/ImportUtilities.java | 3539 | /*
* Copyright (C) 2008 Romain Guy
*
* 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.curiouscreature.android.shelves.util;
import android.graphics.Bitmap;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import org.curiouscreature.android.shelves.provider.BooksStore;
public final class ImportUtilities {
private static final String CACHE_DIRECTORY = "shelves/books";
private static final String IMPORT_FILE = "library.txt";
private ImportUtilities() {
}
public static File getCacheDirectory() {
return IOUtilities.getExternalFile(CACHE_DIRECTORY);
}
public static ArrayList<String> loadItems() throws IOException {
ArrayList<String> list = new ArrayList<String>();
File importFile = IOUtilities.getExternalFile(IMPORT_FILE);
if (!importFile.exists()) return list;
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(importFile)),
IOUtilities.IO_BUFFER_SIZE);
String line;
// Read the CSV headers
in.readLine();
while ((line = in.readLine()) != null) {
final int index = line.indexOf('\t');
final int length = line.length();
// Only one field, we grab the entire line
if (index == -1 && length > 0) {
list.add(line);
// Only one field, the first one is empty
} else if (index != length - 1) {
list.add(line.substring(index + 1));
// We have two fields or the second one is empty
} else {
list.add(line.substring(0, index));
}
}
} finally {
IOUtilities.closeStream(in);
}
return list;
}
public static boolean addBookCoverToCache(BooksStore.Book book, Bitmap bitmap) {
File cacheDirectory;
try {
cacheDirectory = ensureCache();
} catch (IOException e) {
return false;
}
File coverFile = new File(cacheDirectory, book.getInternalId());
FileOutputStream out = null;
try {
out = new FileOutputStream(coverFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (FileNotFoundException e) {
return false;
} finally {
IOUtilities.closeStream(out);
}
return true;
}
private static File ensureCache() throws IOException {
File cacheDirectory = getCacheDirectory();
if (!cacheDirectory.exists()) {
cacheDirectory.mkdirs();
new File(cacheDirectory, ".nomedia").createNewFile();
}
return cacheDirectory;
}
}
| apache-2.0 |
renato2099/giraph-gora | giraph-core/src/main/java/org/apache/giraph/conf/GiraphConstants.java | 42694 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.giraph.conf;
import org.apache.giraph.aggregators.AggregatorWriter;
import org.apache.giraph.aggregators.TextAggregatorWriter;
import org.apache.giraph.combiner.Combiner;
import org.apache.giraph.edge.ByteArrayEdges;
import org.apache.giraph.edge.OutEdges;
import org.apache.giraph.factories.ComputationFactory;
import org.apache.giraph.factories.DefaultComputationFactory;
import org.apache.giraph.factories.DefaultEdgeValueFactory;
import org.apache.giraph.factories.DefaultIncomingMessageValueFactory;
import org.apache.giraph.factories.DefaultOutgoingMessageValueFactory;
import org.apache.giraph.factories.DefaultVertexIdFactory;
import org.apache.giraph.factories.DefaultVertexValueFactory;
import org.apache.giraph.factories.EdgeValueFactory;
import org.apache.giraph.factories.MessageValueFactory;
import org.apache.giraph.factories.VertexIdFactory;
import org.apache.giraph.factories.VertexValueFactory;
import org.apache.giraph.graph.Computation;
import org.apache.giraph.graph.DefaultVertexResolver;
import org.apache.giraph.graph.Language;
import org.apache.giraph.graph.VertexResolver;
import org.apache.giraph.io.EdgeInputFormat;
import org.apache.giraph.io.EdgeOutputFormat;
import org.apache.giraph.io.VertexInputFormat;
import org.apache.giraph.io.VertexOutputFormat;
import org.apache.giraph.io.filters.DefaultEdgeInputFilter;
import org.apache.giraph.io.filters.DefaultVertexInputFilter;
import org.apache.giraph.io.filters.EdgeInputFilter;
import org.apache.giraph.io.filters.VertexInputFilter;
import org.apache.giraph.job.DefaultJobObserver;
import org.apache.giraph.job.GiraphJobObserver;
import org.apache.giraph.master.DefaultMasterCompute;
import org.apache.giraph.master.MasterCompute;
import org.apache.giraph.master.MasterObserver;
import org.apache.giraph.partition.GraphPartitionerFactory;
import org.apache.giraph.partition.HashPartitionerFactory;
import org.apache.giraph.partition.Partition;
import org.apache.giraph.partition.SimplePartition;
import org.apache.giraph.worker.DefaultWorkerContext;
import org.apache.giraph.worker.WorkerContext;
import org.apache.giraph.worker.WorkerObserver;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Constants used all over Giraph for configuration.
*/
// CHECKSTYLE: stop InterfaceIsTypeCheck
public interface GiraphConstants {
/** 1KB in bytes */
int ONE_KB = 1024;
/** Computation class - required */
ClassConfOption<Computation> COMPUTATION_CLASS =
ClassConfOption.create("giraph.computationClass", null,
Computation.class, "Computation class - required");
/** Computation factory class - optional */
ClassConfOption<ComputationFactory> COMPUTATION_FACTORY_CLASS =
ClassConfOption.create("giraph.computation.factory.class",
DefaultComputationFactory.class, ComputationFactory.class,
"Computation factory class - optional");
/** TypesHolder, used if Computation not set - optional */
ClassConfOption<TypesHolder> TYPES_HOLDER_CLASS =
ClassConfOption.create("giraph.typesHolder", null,
TypesHolder.class,
"TypesHolder, used if Computation not set - optional");
/** Language user's graph types are implemented in */
PerGraphTypeEnumConfOption<Language> GRAPH_TYPE_LANGUAGES =
PerGraphTypeEnumConfOption.create("giraph.types.language",
Language.class, Language.JAVA,
"Language user graph types (IVEMM) are implemented in");
/** Whether user graph types need wrappers */
PerGraphTypeBooleanConfOption GRAPH_TYPES_NEEDS_WRAPPERS =
new PerGraphTypeBooleanConfOption("giraph.jython.type.wrappers",
false, "Whether user graph types (IVEMM) need Jython wrappers");
/** Vertex id factory class - optional */
ClassConfOption<VertexIdFactory> VERTEX_ID_FACTORY_CLASS =
ClassConfOption.create("giraph.vertexIdFactoryClass",
DefaultVertexIdFactory.class, VertexIdFactory.class,
"Vertex ID factory class - optional");
/** Vertex value factory class - optional */
ClassConfOption<VertexValueFactory> VERTEX_VALUE_FACTORY_CLASS =
ClassConfOption.create("giraph.vertexValueFactoryClass",
DefaultVertexValueFactory.class, VertexValueFactory.class,
"Vertex value factory class - optional");
/** Edge value factory class - optional */
ClassConfOption<EdgeValueFactory> EDGE_VALUE_FACTORY_CLASS =
ClassConfOption.create("giraph.edgeValueFactoryClass",
DefaultEdgeValueFactory.class, EdgeValueFactory.class,
"Edge value factory class - optional");
/** Incoming message value factory class - optional */
ClassConfOption<MessageValueFactory>
INCOMING_MESSAGE_VALUE_FACTORY_CLASS =
ClassConfOption.create("giraph.incomingMessageValueFactoryClass",
DefaultIncomingMessageValueFactory.class, MessageValueFactory.class,
"Incoming message value factory class - optional");
/** Outgoing message value factory class - optional */
ClassConfOption<MessageValueFactory>
OUTGOING_MESSAGE_VALUE_FACTORY_CLASS =
ClassConfOption.create("giraph.outgoingMessageValueFactoryClass",
DefaultOutgoingMessageValueFactory.class, MessageValueFactory.class,
"Outgoing message value factory class - optional");
/** Vertex edges class - optional */
ClassConfOption<OutEdges> VERTEX_EDGES_CLASS =
ClassConfOption.create("giraph.outEdgesClass", ByteArrayEdges.class,
OutEdges.class, "Vertex edges class - optional");
/** Vertex edges class to be used during edge input only - optional */
ClassConfOption<OutEdges> INPUT_VERTEX_EDGES_CLASS =
ClassConfOption.create("giraph.inputOutEdgesClass",
ByteArrayEdges.class, OutEdges.class,
"Vertex edges class to be used during edge input only - optional");
/** Class for Master - optional */
ClassConfOption<MasterCompute> MASTER_COMPUTE_CLASS =
ClassConfOption.create("giraph.masterComputeClass",
DefaultMasterCompute.class, MasterCompute.class,
"Class for Master - optional");
/** Classes for Master Observer - optional */
ClassConfOption<MasterObserver> MASTER_OBSERVER_CLASSES =
ClassConfOption.create("giraph.master.observers",
null, MasterObserver.class, "Classes for Master Observer - optional");
/** Classes for Worker Observer - optional */
ClassConfOption<WorkerObserver> WORKER_OBSERVER_CLASSES =
ClassConfOption.create("giraph.worker.observers", null,
WorkerObserver.class, "Classes for Worker Observer - optional");
/** Vertex combiner class - optional */
ClassConfOption<Combiner> VERTEX_COMBINER_CLASS =
ClassConfOption.create("giraph.combinerClass", null, Combiner.class,
"Vertex combiner class - optional");
/** Vertex resolver class - optional */
ClassConfOption<VertexResolver> VERTEX_RESOLVER_CLASS =
ClassConfOption.create("giraph.vertexResolverClass",
DefaultVertexResolver.class, VertexResolver.class,
"Vertex resolver class - optional");
/** Which language computation is implemented in */
EnumConfOption<Language> COMPUTATION_LANGUAGE =
EnumConfOption.create("giraph.computation.language",
Language.class, Language.JAVA,
"Which language computation is implemented in");
/**
* Option of whether to create vertexes that were not existent before but
* received messages
*/
BooleanConfOption RESOLVER_CREATE_VERTEX_ON_MSGS =
new BooleanConfOption("giraph.vertex.resolver.create.on.msgs", true,
"Option of whether to create vertexes that were not existent " +
"before but received messages");
/** Graph partitioner factory class - optional */
ClassConfOption<GraphPartitionerFactory> GRAPH_PARTITIONER_FACTORY_CLASS =
ClassConfOption.create("giraph.graphPartitionerFactoryClass",
HashPartitionerFactory.class, GraphPartitionerFactory.class,
"Graph partitioner factory class - optional");
/** Observer class to watch over job status - optional */
ClassConfOption<GiraphJobObserver> JOB_OBSERVER_CLASS =
ClassConfOption.create("giraph.jobObserverClass",
DefaultJobObserver.class, GiraphJobObserver.class,
"Observer class to watch over job status - optional");
// At least one of the input format classes is required.
/** VertexInputFormat class */
ClassConfOption<VertexInputFormat> VERTEX_INPUT_FORMAT_CLASS =
ClassConfOption.create("giraph.vertexInputFormatClass", null,
VertexInputFormat.class, "VertexInputFormat class (at least " +
"one of the input format classes is required)");
/** EdgeInputFormat class */
ClassConfOption<EdgeInputFormat> EDGE_INPUT_FORMAT_CLASS =
ClassConfOption.create("giraph.edgeInputFormatClass", null,
EdgeInputFormat.class, "EdgeInputFormat class");
/** EdgeInputFilter class */
ClassConfOption<EdgeInputFilter> EDGE_INPUT_FILTER_CLASS =
ClassConfOption.create("giraph.edgeInputFilterClass",
DefaultEdgeInputFilter.class, EdgeInputFilter.class,
"EdgeInputFilter class");
/** VertexInputFilter class */
ClassConfOption<VertexInputFilter> VERTEX_INPUT_FILTER_CLASS =
ClassConfOption.create("giraph.vertexInputFilterClass",
DefaultVertexInputFilter.class, VertexInputFilter.class,
"VertexInputFilter class");
/** VertexOutputFormat class */
ClassConfOption<VertexOutputFormat> VERTEX_OUTPUT_FORMAT_CLASS =
ClassConfOption.create("giraph.vertexOutputFormatClass", null,
VertexOutputFormat.class, "VertexOutputFormat class");
/** EdgeOutputFormat sub-directory */
StrConfOption VERTEX_OUTPUT_FORMAT_SUBDIR =
new StrConfOption("giraph.vertex.output.subdir", "",
"VertexOutputFormat sub-directory");
/** EdgeOutputFormat class */
ClassConfOption<EdgeOutputFormat> EDGE_OUTPUT_FORMAT_CLASS =
ClassConfOption.create("giraph.edgeOutputFormatClass", null,
EdgeOutputFormat.class, "EdgeOutputFormat class");
/** EdgeOutputFormat sub-directory */
StrConfOption EDGE_OUTPUT_FORMAT_SUBDIR =
new StrConfOption("giraph.edge.output.subdir", "edges",
"EdgeOutputFormat sub-directory");
/** GiraphTextOuputFormat Separator */
StrConfOption GIRAPH_TEXT_OUTPUT_FORMAT_SEPARATOR =
new StrConfOption("giraph.textoutputformat.separator", "\t",
"GiraphTextOuputFormat Separator");
/** Reverse values in the output */
BooleanConfOption GIRAPH_TEXT_OUTPUT_FORMAT_REVERSE =
new BooleanConfOption("giraph.textoutputformat.reverse", false,
"Reverse values in the output");
/**
* If you use this option, instead of having saving vertices in the end of
* application, saveVertex will be called right after each vertex.compute()
* is called.
* NOTE: This feature doesn't work well with checkpointing - if you restart
* from a checkpoint you won't have any output from previous supersteps.
*/
BooleanConfOption DO_OUTPUT_DURING_COMPUTATION =
new BooleanConfOption("giraph.doOutputDuringComputation", false,
"If you use this option, instead of having saving vertices in the " +
"end of application, saveVertex will be called right after each " +
"vertex.compute() is called." +
"NOTE: This feature doesn't work well with checkpointing - if you " +
"restart from a checkpoint you won't have any ouptut from previous " +
"supresteps.");
/**
* Vertex output format thread-safe - if your VertexOutputFormat allows
* several vertexWriters to be created and written to in parallel,
* you should set this to true.
*/
BooleanConfOption VERTEX_OUTPUT_FORMAT_THREAD_SAFE =
new BooleanConfOption("giraph.vertexOutputFormatThreadSafe", false,
"Vertex output format thread-safe - if your VertexOutputFormat " +
"allows several vertexWriters to be created and written to in " +
"parallel, you should set this to true.");
/** Number of threads for writing output in the end of the application */
IntConfOption NUM_OUTPUT_THREADS =
new IntConfOption("giraph.numOutputThreads", 1,
"Number of threads for writing output in the end of the application");
/** conf key for comma-separated list of jars to export to YARN workers */
StrConfOption GIRAPH_YARN_LIBJARS =
new StrConfOption("giraph.yarn.libjars", "",
"conf key for comma-separated list of jars to export to YARN workers");
/** Name of the XML file that will export our Configuration to YARN workers */
String GIRAPH_YARN_CONF_FILE = "giraph-conf.xml";
/** Giraph default heap size for all tasks when running on YARN profile */
int GIRAPH_YARN_TASK_HEAP_MB_DEFAULT = 1024;
/** Name of Giraph property for user-configurable heap memory per worker */
IntConfOption GIRAPH_YARN_TASK_HEAP_MB = new IntConfOption(
"giraph.yarn.task.heap.mb", GIRAPH_YARN_TASK_HEAP_MB_DEFAULT,
"Name of Giraph property for user-configurable heap memory per worker");
/** Default priority level in YARN for our task containers */
int GIRAPH_YARN_PRIORITY = 10;
/** Is this a pure YARN job (i.e. no MapReduce layer managing Giraph tasks) */
BooleanConfOption IS_PURE_YARN_JOB =
new BooleanConfOption("giraph.pure.yarn.job", false,
"Is this a pure YARN job (i.e. no MapReduce layer managing Giraph " +
"tasks)");
/** Vertex index class */
ClassConfOption<WritableComparable> VERTEX_ID_CLASS =
ClassConfOption.create("giraph.vertexIdClass", null,
WritableComparable.class, "Vertex index class");
/** Vertex value class */
ClassConfOption<Writable> VERTEX_VALUE_CLASS =
ClassConfOption.create("giraph.vertexValueClass", null, Writable.class,
"Vertex value class");
/** Edge value class */
ClassConfOption<Writable> EDGE_VALUE_CLASS =
ClassConfOption.create("giraph.edgeValueClass", null, Writable.class,
"Edge value class");
/** Incoming message value class */
ClassConfOption<Writable> INCOMING_MESSAGE_VALUE_CLASS =
ClassConfOption.create("giraph.incomingMessageValueClass", null,
Writable.class, "Incoming message value class");
/** Outgoing message value class */
ClassConfOption<Writable> OUTGOING_MESSAGE_VALUE_CLASS =
ClassConfOption.create("giraph.outgoingMessageValueClass", null,
Writable.class, "Outgoing message value class");
/** Worker context class */
ClassConfOption<WorkerContext> WORKER_CONTEXT_CLASS =
ClassConfOption.create("giraph.workerContextClass",
DefaultWorkerContext.class, WorkerContext.class,
"Worker contextclass");
/** AggregatorWriter class - optional */
ClassConfOption<AggregatorWriter> AGGREGATOR_WRITER_CLASS =
ClassConfOption.create("giraph.aggregatorWriterClass",
TextAggregatorWriter.class, AggregatorWriter.class,
"AggregatorWriter class - optional");
/** Partition class - optional */
ClassConfOption<Partition> PARTITION_CLASS =
ClassConfOption.create("giraph.partitionClass", SimplePartition.class,
Partition.class, "Partition class - optional");
/**
* Minimum number of simultaneous workers before this job can run (int)
*/
String MIN_WORKERS = "giraph.minWorkers";
/**
* Maximum number of simultaneous worker tasks started by this job (int).
*/
String MAX_WORKERS = "giraph.maxWorkers";
/**
* Separate the workers and the master tasks. This is required
* to support dynamic recovery. (boolean)
*/
BooleanConfOption SPLIT_MASTER_WORKER =
new BooleanConfOption("giraph.SplitMasterWorker", true,
"Separate the workers and the master tasks. This is required to " +
"support dynamic recovery. (boolean)");
/** Indicates whether this job is run in an internal unit test */
BooleanConfOption LOCAL_TEST_MODE =
new BooleanConfOption("giraph.localTestMode", false,
"Indicates whether this job is run in an internal unit test");
/** Override the Hadoop log level and set the desired log level. */
StrConfOption LOG_LEVEL = new StrConfOption("giraph.logLevel", "info",
"Override the Hadoop log level and set the desired log level.");
/** Use thread level debugging? */
BooleanConfOption LOG_THREAD_LAYOUT =
new BooleanConfOption("giraph.logThreadLayout", false,
"Use thread level debugging?");
/** Configuration key to enable jmap printing */
BooleanConfOption JMAP_ENABLE =
new BooleanConfOption("giraph.jmap.histo.enable", false,
"Configuration key to enable jmap printing");
/** Configuration key for msec to sleep between calls */
IntConfOption JMAP_SLEEP_MILLIS =
new IntConfOption("giraph.jmap.histo.msec", SECONDS.toMillis(30),
"Configuration key for msec to sleep between calls");
/** Configuration key for how many lines to print */
IntConfOption JMAP_PRINT_LINES =
new IntConfOption("giraph.jmap.histo.print_lines", 30,
"Configuration key for how many lines to print");
/**
* Minimum percent of the maximum number of workers that have responded
* in order to continue progressing. (float)
*/
FloatConfOption MIN_PERCENT_RESPONDED =
new FloatConfOption("giraph.minPercentResponded", 100.0f,
"Minimum percent of the maximum number of workers that have " +
"responded in order to continue progressing. (float)");
/** Enable the Metrics system */
BooleanConfOption METRICS_ENABLE =
new BooleanConfOption("giraph.metrics.enable", false,
"Enable the Metrics system");
/** Directory in HDFS to write master metrics to, instead of stderr */
StrConfOption METRICS_DIRECTORY =
new StrConfOption("giraph.metrics.directory", "",
"Directory in HDFS to write master metrics to, instead of stderr");
/**
* ZooKeeper comma-separated list (if not set,
* will start up ZooKeeper locally)
*/
String ZOOKEEPER_LIST = "giraph.zkList";
/** ZooKeeper session millisecond timeout */
IntConfOption ZOOKEEPER_SESSION_TIMEOUT =
new IntConfOption("giraph.zkSessionMsecTimeout", MINUTES.toMillis(1),
"ZooKeeper session millisecond timeout");
/** Polling interval to check for the ZooKeeper server data */
IntConfOption ZOOKEEPER_SERVERLIST_POLL_MSECS =
new IntConfOption("giraph.zkServerlistPollMsecs", SECONDS.toMillis(3),
"Polling interval to check for the ZooKeeper server data");
/** Number of nodes (not tasks) to run Zookeeper on */
IntConfOption ZOOKEEPER_SERVER_COUNT =
new IntConfOption("giraph.zkServerCount", 1,
"Number of nodes (not tasks) to run Zookeeper on");
/** ZooKeeper port to use */
IntConfOption ZOOKEEPER_SERVER_PORT =
new IntConfOption("giraph.zkServerPort", 22181, "ZooKeeper port to use");
/** Location of the ZooKeeper jar - Used internally, not meant for users */
String ZOOKEEPER_JAR = "giraph.zkJar";
/** Local ZooKeeper directory to use */
String ZOOKEEPER_DIR = "giraph.zkDir";
/** Max attempts for handling ZooKeeper connection loss */
IntConfOption ZOOKEEPER_OPS_MAX_ATTEMPTS =
new IntConfOption("giraph.zkOpsMaxAttempts", 3,
"Max attempts for handling ZooKeeper connection loss");
/**
* Msecs to wait before retrying a failed ZooKeeper op due to connection loss.
*/
IntConfOption ZOOKEEPER_OPS_RETRY_WAIT_MSECS =
new IntConfOption("giraph.zkOpsRetryWaitMsecs", SECONDS.toMillis(5),
"Msecs to wait before retrying a failed ZooKeeper op due to " +
"connection loss.");
/** TCP backlog (defaults to number of workers) */
IntConfOption TCP_BACKLOG = new IntConfOption("giraph.tcpBacklog", 1,
"TCP backlog (defaults to number of workers)");
/** How big to make the encoder buffer? */
IntConfOption NETTY_REQUEST_ENCODER_BUFFER_SIZE =
new IntConfOption("giraph.nettyRequestEncoderBufferSize", 32 * ONE_KB,
"How big to make the encoder buffer?");
/** Whether or not netty request encoder should use direct byte buffers */
BooleanConfOption NETTY_REQUEST_ENCODER_USE_DIRECT_BUFFERS =
new BooleanConfOption("giraph.nettyRequestEncoderUseDirectBuffers",
false, "Whether or not netty request encoder " +
"should use direct byte buffers");
/** Netty client threads */
IntConfOption NETTY_CLIENT_THREADS =
new IntConfOption("giraph.nettyClientThreads", 4, "Netty client threads");
/** Netty server threads */
IntConfOption NETTY_SERVER_THREADS =
new IntConfOption("giraph.nettyServerThreads", 16,
"Netty server threads");
/** Use the execution handler in netty on the client? */
BooleanConfOption NETTY_CLIENT_USE_EXECUTION_HANDLER =
new BooleanConfOption("giraph.nettyClientUseExecutionHandler", true,
"Use the execution handler in netty on the client?");
/** Netty client execution threads (execution handler) */
IntConfOption NETTY_CLIENT_EXECUTION_THREADS =
new IntConfOption("giraph.nettyClientExecutionThreads", 8,
"Netty client execution threads (execution handler)");
/** Where to place the netty client execution handle? */
StrConfOption NETTY_CLIENT_EXECUTION_AFTER_HANDLER =
new StrConfOption("giraph.nettyClientExecutionAfterHandler",
"requestEncoder",
"Where to place the netty client execution handle?");
/** Use the execution handler in netty on the server? */
BooleanConfOption NETTY_SERVER_USE_EXECUTION_HANDLER =
new BooleanConfOption("giraph.nettyServerUseExecutionHandler", true,
"Use the execution handler in netty on the server?");
/** Netty server execution threads (execution handler) */
IntConfOption NETTY_SERVER_EXECUTION_THREADS =
new IntConfOption("giraph.nettyServerExecutionThreads", 8,
"Netty server execution threads (execution handler)");
/** Where to place the netty server execution handle? */
StrConfOption NETTY_SERVER_EXECUTION_AFTER_HANDLER =
new StrConfOption("giraph.nettyServerExecutionAfterHandler",
"requestFrameDecoder",
"Where to place the netty server execution handle?");
/** Netty simulate a first request closed */
BooleanConfOption NETTY_SIMULATE_FIRST_REQUEST_CLOSED =
new BooleanConfOption("giraph.nettySimulateFirstRequestClosed", false,
"Netty simulate a first request closed");
/** Netty simulate a first response failed */
BooleanConfOption NETTY_SIMULATE_FIRST_RESPONSE_FAILED =
new BooleanConfOption("giraph.nettySimulateFirstResponseFailed", false,
"Netty simulate a first response failed");
/** Max resolve address attempts */
IntConfOption MAX_RESOLVE_ADDRESS_ATTEMPTS =
new IntConfOption("giraph.maxResolveAddressAttempts", 5,
"Max resolve address attempts");
/** Msecs to wait between waiting for all requests to finish */
IntConfOption WAITING_REQUEST_MSECS =
new IntConfOption("giraph.waitingRequestMsecs", SECONDS.toMillis(15),
"Msecs to wait between waiting for all requests to finish");
/** Millseconds to wait for an event before continuing */
IntConfOption EVENT_WAIT_MSECS =
new IntConfOption("giraph.eventWaitMsecs", SECONDS.toMillis(30),
"Millseconds to wait for an event before continuing");
/**
* Maximum milliseconds to wait before giving up trying to get the minimum
* number of workers before a superstep (int).
*/
IntConfOption MAX_MASTER_SUPERSTEP_WAIT_MSECS =
new IntConfOption("giraph.maxMasterSuperstepWaitMsecs",
MINUTES.toMillis(10),
"Maximum milliseconds to wait before giving up trying to get the " +
"minimum number of workers before a superstep (int).");
/** Milliseconds for a request to complete (or else resend) */
IntConfOption MAX_REQUEST_MILLISECONDS =
new IntConfOption("giraph.maxRequestMilliseconds", MINUTES.toMillis(10),
"Milliseconds for a request to complete (or else resend)");
/** Netty max connection failures */
IntConfOption NETTY_MAX_CONNECTION_FAILURES =
new IntConfOption("giraph.nettyMaxConnectionFailures", 1000,
"Netty max connection failures");
/** Initial port to start using for the IPC communication */
IntConfOption IPC_INITIAL_PORT =
new IntConfOption("giraph.ipcInitialPort", 30000,
"Initial port to start using for the IPC communication");
/** Maximum bind attempts for different IPC ports */
IntConfOption MAX_IPC_PORT_BIND_ATTEMPTS =
new IntConfOption("giraph.maxIpcPortBindAttempts", 20,
"Maximum bind attempts for different IPC ports");
/**
* Fail first IPC port binding attempt, simulate binding failure
* on real grid testing
*/
BooleanConfOption FAIL_FIRST_IPC_PORT_BIND_ATTEMPT =
new BooleanConfOption("giraph.failFirstIpcPortBindAttempt", false,
"Fail first IPC port binding attempt, simulate binding failure " +
"on real grid testing");
/** Client send buffer size */
IntConfOption CLIENT_SEND_BUFFER_SIZE =
new IntConfOption("giraph.clientSendBufferSize", 512 * ONE_KB,
"Client send buffer size");
/** Client receive buffer size */
IntConfOption CLIENT_RECEIVE_BUFFER_SIZE =
new IntConfOption("giraph.clientReceiveBufferSize", 32 * ONE_KB,
"Client receive buffer size");
/** Server send buffer size */
IntConfOption SERVER_SEND_BUFFER_SIZE =
new IntConfOption("giraph.serverSendBufferSize", 32 * ONE_KB,
"Server send buffer size");
/** Server receive buffer size */
IntConfOption SERVER_RECEIVE_BUFFER_SIZE =
new IntConfOption("giraph.serverReceiveBufferSize", 512 * ONE_KB,
"Server receive buffer size");
/** Maximum size of messages (in bytes) per peer before flush */
IntConfOption MAX_MSG_REQUEST_SIZE =
new IntConfOption("giraph.msgRequestSize", 512 * ONE_KB,
"Maximum size of messages (in bytes) per peer before flush");
/**
* How much bigger than the average per partition size to make initial per
* partition buffers.
* If this value is A, message request size is M,
* and a worker has P partitions, than its initial partition buffer size
* will be (M / P) * (1 + A).
*/
FloatConfOption ADDITIONAL_MSG_REQUEST_SIZE =
new FloatConfOption("giraph.additionalMsgRequestSize", 0.2f,
"How much bigger than the average per partition size to make " +
"initial per partition buffers. If this value is A, message " +
"request size is M, and a worker has P partitions, than its " +
"initial partition buffer size will be (M / P) * (1 + A).");
/** Maximum size of edges (in bytes) per peer before flush */
IntConfOption MAX_EDGE_REQUEST_SIZE =
new IntConfOption("giraph.edgeRequestSize", 512 * ONE_KB,
"Maximum size of edges (in bytes) per peer before flush");
/**
* Additional size (expressed as a ratio) of each per-partition buffer on
* top of the average size.
*/
FloatConfOption ADDITIONAL_EDGE_REQUEST_SIZE =
new FloatConfOption("giraph.additionalEdgeRequestSize", 0.2f,
"Additional size (expressed as a ratio) of each per-partition " +
"buffer on top of the average size.");
/** Maximum number of mutations per partition before flush */
IntConfOption MAX_MUTATIONS_PER_REQUEST =
new IntConfOption("giraph.maxMutationsPerRequest", 100,
"Maximum number of mutations per partition before flush");
/**
* Use message size encoding (typically better for complex objects,
* not meant for primitive wrapped messages)
*/
BooleanConfOption USE_MESSAGE_SIZE_ENCODING =
new BooleanConfOption("giraph.useMessageSizeEncoding", false,
"Use message size encoding (typically better for complex objects, " +
"not meant for primitive wrapped messages)");
/** Number of channels used per server */
IntConfOption CHANNELS_PER_SERVER =
new IntConfOption("giraph.channelsPerServer", 1,
"Number of channels used per server");
/** Number of flush threads per peer */
String MSG_NUM_FLUSH_THREADS = "giraph.msgNumFlushThreads";
/** Number of threads for vertex computation */
IntConfOption NUM_COMPUTE_THREADS =
new IntConfOption("giraph.numComputeThreads", 1,
"Number of threads for vertex computation");
/** Number of threads for input split loading */
IntConfOption NUM_INPUT_THREADS =
new IntConfOption("giraph.numInputThreads", 1,
"Number of threads for input split loading");
/** Minimum stragglers of the superstep before printing them out */
IntConfOption PARTITION_LONG_TAIL_MIN_PRINT =
new IntConfOption("giraph.partitionLongTailMinPrint", 1,
"Minimum stragglers of the superstep before printing them out");
/** Use superstep counters? (boolean) */
BooleanConfOption USE_SUPERSTEP_COUNTERS =
new BooleanConfOption("giraph.useSuperstepCounters", true,
"Use superstep counters? (boolean)");
/**
* Input split sample percent - Used only for sampling and testing, rather
* than an actual job. The idea is that to test, you might only want a
* fraction of the actual input splits from your VertexInputFormat to
* load (values should be [0, 100]).
*/
FloatConfOption INPUT_SPLIT_SAMPLE_PERCENT =
new FloatConfOption("giraph.inputSplitSamplePercent", 100f,
"Input split sample percent - Used only for sampling and testing, " +
"rather than an actual job. The idea is that to test, you might " +
"only want a fraction of the actual input splits from your " +
"VertexInputFormat to load (values should be [0, 100]).");
/**
* To limit outlier vertex input splits from producing too many vertices or
* to help with testing, the number of vertices loaded from an input split
* can be limited. By default, everything is loaded.
*/
LongConfOption INPUT_SPLIT_MAX_VERTICES =
new LongConfOption("giraph.InputSplitMaxVertices", -1,
"To limit outlier vertex input splits from producing too many " +
"vertices or to help with testing, the number of vertices loaded " +
"from an input split can be limited. By default, everything is " +
"loaded.");
/**
* To limit outlier vertex input splits from producing too many vertices or
* to help with testing, the number of edges loaded from an input split
* can be limited. By default, everything is loaded.
*/
LongConfOption INPUT_SPLIT_MAX_EDGES =
new LongConfOption("giraph.InputSplitMaxEdges", -1,
"To limit outlier vertex input splits from producing too many " +
"vertices or to help with testing, the number of edges loaded " +
"from an input split can be limited. By default, everything is " +
"loaded.");
/**
* To minimize network usage when reading input splits,
* each worker can prioritize splits that reside on its host.
* This, however, comes at the cost of increased load on ZooKeeper.
* Hence, users with a lot of splits and input threads (or with
* configurations that can't exploit locality) may want to disable it.
*/
BooleanConfOption USE_INPUT_SPLIT_LOCALITY =
new BooleanConfOption("giraph.useInputSplitLocality", true,
"To minimize network usage when reading input splits, each worker " +
"can prioritize splits that reside on its host. " +
"This, however, comes at the cost of increased load on ZooKeeper. " +
"Hence, users with a lot of splits and input threads (or with " +
"configurations that can't exploit locality) may want to disable " +
"it.");
/** Multiplier for the current workers squared */
FloatConfOption PARTITION_COUNT_MULTIPLIER =
new FloatConfOption("giraph.masterPartitionCountMultiplier", 1.0f,
"Multiplier for the current workers squared");
/** Overrides default partition count calculation if not -1 */
IntConfOption USER_PARTITION_COUNT =
new IntConfOption("giraph.userPartitionCount", -1,
"Overrides default partition count calculation if not -1");
/** Vertex key space size for
* {@link org.apache.giraph.partition.SimpleRangeWorkerPartitioner}
*/
String PARTITION_VERTEX_KEY_SPACE_SIZE = "giraph.vertexKeySpaceSize";
/** Java opts passed to ZooKeeper startup */
StrConfOption ZOOKEEPER_JAVA_OPTS =
new StrConfOption("giraph.zkJavaOpts",
"-Xmx512m -XX:ParallelGCThreads=4 -XX:+UseConcMarkSweepGC " +
"-XX:CMSInitiatingOccupancyFraction=70 -XX:MaxGCPauseMillis=100",
"Java opts passed to ZooKeeper startup");
/**
* How often to checkpoint (i.e. 0, means no checkpoint,
* 1 means every superstep, 2 is every two supersteps, etc.).
*/
IntConfOption CHECKPOINT_FREQUENCY =
new IntConfOption("giraph.checkpointFrequency", 0,
"How often to checkpoint (i.e. 0, means no checkpoint, 1 means " +
"every superstep, 2 is every two supersteps, etc.).");
/**
* Delete checkpoints after a successful job run?
*/
BooleanConfOption CLEANUP_CHECKPOINTS_AFTER_SUCCESS =
new BooleanConfOption("giraph.cleanupCheckpointsAfterSuccess", true,
"Delete checkpoints after a successful job run?");
/**
* An application can be restarted manually by selecting a superstep. The
* corresponding checkpoint must exist for this to work. The user should
* set a long value. Default is start from scratch.
*/
String RESTART_SUPERSTEP = "giraph.restartSuperstep";
/**
* Base ZNode for Giraph's state in the ZooKeeper cluster. Must be a root
* znode on the cluster beginning with "/"
*/
String BASE_ZNODE_KEY = "giraph.zkBaseZNode";
/**
* If ZOOKEEPER_LIST is not set, then use this directory to manage
* ZooKeeper
*/
StrConfOption ZOOKEEPER_MANAGER_DIRECTORY =
new StrConfOption("giraph.zkManagerDirectory",
"_bsp/_defaultZkManagerDir",
"If ZOOKEEPER_LIST is not set, then use this directory to manage " +
"ZooKeeper");
/** Number of ZooKeeper client connection attempts before giving up. */
IntConfOption ZOOKEEPER_CONNECTION_ATTEMPTS =
new IntConfOption("giraph.zkConnectionAttempts", 10,
"Number of ZooKeeper client connection attempts before giving up.");
/** This directory has/stores the available checkpoint files in HDFS. */
StrConfOption CHECKPOINT_DIRECTORY =
new StrConfOption("giraph.checkpointDirectory", "_bsp/_checkpoints/",
"This directory has/stores the available checkpoint files in HDFS.");
/**
* Comma-separated list of directories in the local file system for
* out-of-core messages.
*/
StrConfOption MESSAGES_DIRECTORY =
new StrConfOption("giraph.messagesDirectory", "_bsp/_messages/",
"Comma-separated list of directories in the local file system for " +
"out-of-core messages.");
/** Whether or not to use out-of-core messages */
BooleanConfOption USE_OUT_OF_CORE_MESSAGES =
new BooleanConfOption("giraph.useOutOfCoreMessages", false,
"Whether or not to use out-of-core messages");
/**
* If using out-of-core messaging, it tells how much messages do we keep
* in memory.
*/
IntConfOption MAX_MESSAGES_IN_MEMORY =
new IntConfOption("giraph.maxMessagesInMemory", 1000000,
"If using out-of-core messaging, it tells how much messages do we " +
"keep in memory.");
/** Size of buffer when reading and writing messages out-of-core. */
IntConfOption MESSAGES_BUFFER_SIZE =
new IntConfOption("giraph.messagesBufferSize", 8 * ONE_KB,
"Size of buffer when reading and writing messages out-of-core.");
/**
* Comma-separated list of directories in the local filesystem for
* out-of-core partitions.
*/
StrConfOption PARTITIONS_DIRECTORY =
new StrConfOption("giraph.partitionsDirectory", "_bsp/_partitions",
"Comma-separated list of directories in the local filesystem for " +
"out-of-core partitions.");
/** Enable out-of-core graph. */
BooleanConfOption USE_OUT_OF_CORE_GRAPH =
new BooleanConfOption("giraph.useOutOfCoreGraph", false,
"Enable out-of-core graph.");
/** Directory to write YourKit snapshots to */
String YOURKIT_OUTPUT_DIR = "giraph.yourkit.outputDir";
/** Default directory to write YourKit snapshots to */
String YOURKIT_OUTPUT_DIR_DEFAULT = "/tmp/giraph/%JOB_ID%/%TASK_ID%";
/** Maximum number of partitions to hold in memory for each worker. */
IntConfOption MAX_PARTITIONS_IN_MEMORY =
new IntConfOption("giraph.maxPartitionsInMemory", 10,
"Maximum number of partitions to hold in memory for each worker.");
/** Keep the zookeeper output for debugging? Default is to remove it. */
BooleanConfOption KEEP_ZOOKEEPER_DATA =
new BooleanConfOption("giraph.keepZooKeeperData", false,
"Keep the zookeeper output for debugging? Default is to remove it.");
/** Default ZooKeeper tick time. */
int DEFAULT_ZOOKEEPER_TICK_TIME = 6000;
/** Default ZooKeeper init limit (in ticks). */
int DEFAULT_ZOOKEEPER_INIT_LIMIT = 10;
/** Default ZooKeeper sync limit (in ticks). */
int DEFAULT_ZOOKEEPER_SYNC_LIMIT = 5;
/** Default ZooKeeper snap count. */
int DEFAULT_ZOOKEEPER_SNAP_COUNT = 50000;
/** Default ZooKeeper maximum client connections. */
int DEFAULT_ZOOKEEPER_MAX_CLIENT_CNXNS = 10000;
/** ZooKeeper minimum session timeout */
IntConfOption ZOOKEEPER_MIN_SESSION_TIMEOUT =
new IntConfOption("giraph.zKMinSessionTimeout", MINUTES.toMillis(10),
"ZooKeeper minimum session timeout");
/** ZooKeeper maximum session timeout */
IntConfOption ZOOKEEPER_MAX_SESSION_TIMEOUT =
new IntConfOption("giraph.zkMaxSessionTimeout", MINUTES.toMillis(15),
"ZooKeeper maximum session timeout");
/** ZooKeeper force sync */
BooleanConfOption ZOOKEEPER_FORCE_SYNC =
new BooleanConfOption("giraph.zKForceSync", false,
"ZooKeeper force sync");
/** ZooKeeper skip ACLs */
BooleanConfOption ZOOKEEPER_SKIP_ACL =
new BooleanConfOption("giraph.ZkSkipAcl", true, "ZooKeeper skip ACLs");
/**
* Whether to use SASL with DIGEST and Hadoop Job Tokens to authenticate
* and authorize Netty BSP Clients to Servers.
*/
BooleanConfOption AUTHENTICATE =
new BooleanConfOption("giraph.authenticate", false,
"Whether to use SASL with DIGEST and Hadoop Job Tokens to " +
"authenticate and authorize Netty BSP Clients to Servers.");
/** Use unsafe serialization? */
BooleanConfOption USE_UNSAFE_SERIALIZATION =
new BooleanConfOption("giraph.useUnsafeSerialization", true,
"Use unsafe serialization?");
/**
* Use BigDataIO for messages? If there are super-vertices in the
* graph which receive a lot of messages (total serialized size of messages
* goes beyond the maximum size of a byte array), setting this option to true
* will remove that limit. The maximum memory available for a single vertex
* will be limited to the maximum heap size available.
*/
BooleanConfOption USE_BIG_DATA_IO_FOR_MESSAGES =
new BooleanConfOption("giraph.useBigDataIOForMessages", false,
"Use BigDataIO for messages?");
/**
* Maximum number of attempts a master/worker will retry before killing
* the job. This directly maps to the number of map task attempts in
* Hadoop.
*/
IntConfOption MAX_TASK_ATTEMPTS =
new IntConfOption("mapred.map.max.attempts", -1,
"Maximum number of attempts a master/worker will retry before " +
"killing the job. This directly maps to the number of map task " +
"attempts in Hadoop.");
/** Interface to use for hostname resolution */
StrConfOption DNS_INTERFACE =
new StrConfOption("giraph.dns.interface", "default",
"Interface to use for hostname resolution");
/** Server for hostname resolution */
StrConfOption DNS_NAMESERVER =
new StrConfOption("giraph.dns.nameserver", "default",
"Server for hostname resolution");
/**
* The application will halt after this many supersteps is completed. For
* instance, if it is set to 3, the application will run at most 0, 1,
* and 2 supersteps and then go into the shutdown superstep.
*/
IntConfOption MAX_NUMBER_OF_SUPERSTEPS =
new IntConfOption("giraph.maxNumberOfSupersteps", 1,
"The application will halt after this many supersteps is " +
"completed. For instance, if it is set to 3, the application will " +
"run at most 0, 1, and 2 supersteps and then go into the shutdown " +
"superstep.");
/**
* The application will not mutate the graph topology (the edges). It is used
* to optimise out-of-core graph, by not writing back edges every time.
*/
BooleanConfOption STATIC_GRAPH =
new BooleanConfOption("giraph.isStaticGraph", false,
"The application will not mutate the graph topology (the edges). " +
"It is used to optimise out-of-core graph, by not writing back " +
"edges every time.");
/**
* This option will enable communication optimization for one-to-all
* message sending. For multiple target ids on the same machine,
* we only send one message to all the targets.
*/
BooleanConfOption ONE_TO_ALL_MSG_SENDING =
new BooleanConfOption("giraph.oneToAllMsgSending", false, "Enable " +
"one-to-all message sending strategy");
}
// CHECKSTYLE: resume InterfaceIsTypeCheck
| apache-2.0 |
kubernetes-client/java | fluent/src/main/java/io/kubernetes/client/openapi/models/V2beta2PodsMetricStatusFluentImpl.java | 8148 | /*
Copyright 2022 The Kubernetes 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 io.kubernetes.client.openapi.models;
/** Generated */
public class V2beta2PodsMetricStatusFluentImpl<
A extends io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent<A>>
extends io.kubernetes.client.fluent.BaseFluent<A>
implements io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent<A> {
public V2beta2PodsMetricStatusFluentImpl() {}
public V2beta2PodsMetricStatusFluentImpl(
io.kubernetes.client.openapi.models.V2beta2PodsMetricStatus instance) {
this.withCurrent(instance.getCurrent());
this.withMetric(instance.getMetric());
}
private io.kubernetes.client.openapi.models.V2beta2MetricValueStatusBuilder current;
private io.kubernetes.client.openapi.models.V2beta2MetricIdentifierBuilder metric;
/**
* This method has been deprecated, please use method buildCurrent instead.
*
* @return The buildable object.
*/
@java.lang.Deprecated
public io.kubernetes.client.openapi.models.V2beta2MetricValueStatus getCurrent() {
return this.current != null ? this.current.build() : null;
}
public io.kubernetes.client.openapi.models.V2beta2MetricValueStatus buildCurrent() {
return this.current != null ? this.current.build() : null;
}
public A withCurrent(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus current) {
_visitables.get("current").remove(this.current);
if (current != null) {
this.current =
new io.kubernetes.client.openapi.models.V2beta2MetricValueStatusBuilder(current);
_visitables.get("current").add(this.current);
}
return (A) this;
}
public java.lang.Boolean hasCurrent() {
return this.current != null;
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.CurrentNested<A>
withNewCurrent() {
return new io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluentImpl
.CurrentNestedImpl();
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.CurrentNested<A>
withNewCurrentLike(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus item) {
return new io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluentImpl
.CurrentNestedImpl(item);
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.CurrentNested<A>
editCurrent() {
return withNewCurrentLike(getCurrent());
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.CurrentNested<A>
editOrNewCurrent() {
return withNewCurrentLike(
getCurrent() != null
? getCurrent()
: new io.kubernetes.client.openapi.models.V2beta2MetricValueStatusBuilder().build());
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.CurrentNested<A>
editOrNewCurrentLike(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus item) {
return withNewCurrentLike(getCurrent() != null ? getCurrent() : item);
}
/**
* This method has been deprecated, please use method buildMetric instead.
*
* @return The buildable object.
*/
@java.lang.Deprecated
public io.kubernetes.client.openapi.models.V2beta2MetricIdentifier getMetric() {
return this.metric != null ? this.metric.build() : null;
}
public io.kubernetes.client.openapi.models.V2beta2MetricIdentifier buildMetric() {
return this.metric != null ? this.metric.build() : null;
}
public A withMetric(io.kubernetes.client.openapi.models.V2beta2MetricIdentifier metric) {
_visitables.get("metric").remove(this.metric);
if (metric != null) {
this.metric = new io.kubernetes.client.openapi.models.V2beta2MetricIdentifierBuilder(metric);
_visitables.get("metric").add(this.metric);
}
return (A) this;
}
public java.lang.Boolean hasMetric() {
return this.metric != null;
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.MetricNested<A>
withNewMetric() {
return new io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluentImpl
.MetricNestedImpl();
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.MetricNested<A>
withNewMetricLike(io.kubernetes.client.openapi.models.V2beta2MetricIdentifier item) {
return new io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluentImpl
.MetricNestedImpl(item);
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.MetricNested<A>
editMetric() {
return withNewMetricLike(getMetric());
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.MetricNested<A>
editOrNewMetric() {
return withNewMetricLike(
getMetric() != null
? getMetric()
: new io.kubernetes.client.openapi.models.V2beta2MetricIdentifierBuilder().build());
}
public io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.MetricNested<A>
editOrNewMetricLike(io.kubernetes.client.openapi.models.V2beta2MetricIdentifier item) {
return withNewMetricLike(getMetric() != null ? getMetric() : item);
}
public boolean equals(java.lang.Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
V2beta2PodsMetricStatusFluentImpl that = (V2beta2PodsMetricStatusFluentImpl) o;
if (current != null ? !current.equals(that.current) : that.current != null) return false;
if (metric != null ? !metric.equals(that.metric) : that.metric != null) return false;
return true;
}
public int hashCode() {
return java.util.Objects.hash(current, metric, super.hashCode());
}
public class CurrentNestedImpl<N>
extends io.kubernetes.client.openapi.models.V2beta2MetricValueStatusFluentImpl<
io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.CurrentNested<N>>
implements io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.CurrentNested<N>,
io.kubernetes.client.fluent.Nested<N> {
CurrentNestedImpl(io.kubernetes.client.openapi.models.V2beta2MetricValueStatus item) {
this.builder =
new io.kubernetes.client.openapi.models.V2beta2MetricValueStatusBuilder(this, item);
}
CurrentNestedImpl() {
this.builder = new io.kubernetes.client.openapi.models.V2beta2MetricValueStatusBuilder(this);
}
io.kubernetes.client.openapi.models.V2beta2MetricValueStatusBuilder builder;
public N and() {
return (N) V2beta2PodsMetricStatusFluentImpl.this.withCurrent(builder.build());
}
public N endCurrent() {
return and();
}
}
public class MetricNestedImpl<N>
extends io.kubernetes.client.openapi.models.V2beta2MetricIdentifierFluentImpl<
io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.MetricNested<N>>
implements io.kubernetes.client.openapi.models.V2beta2PodsMetricStatusFluent.MetricNested<N>,
io.kubernetes.client.fluent.Nested<N> {
MetricNestedImpl(io.kubernetes.client.openapi.models.V2beta2MetricIdentifier item) {
this.builder =
new io.kubernetes.client.openapi.models.V2beta2MetricIdentifierBuilder(this, item);
}
MetricNestedImpl() {
this.builder = new io.kubernetes.client.openapi.models.V2beta2MetricIdentifierBuilder(this);
}
io.kubernetes.client.openapi.models.V2beta2MetricIdentifierBuilder builder;
public N and() {
return (N) V2beta2PodsMetricStatusFluentImpl.this.withMetric(builder.build());
}
public N endMetric() {
return and();
}
}
}
| apache-2.0 |
vdmeer/skb-java-base | src/main/java/de/vandermeer/skb/base/shell/Ci_Exit.java | 1970 | /* Copyright 2014 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.base.shell;
import org.apache.commons.lang3.StringUtils;
import de.vandermeer.skb.base.managers.MessageMgr;
/**
* An interpreter for the 'exit' shell command.
*
* @author Sven van der Meer <vdmeer.sven@mykolab.com>
* @version v0.2.0 build 170404 (04-Apr-17) for Java 1.8
* @since v0.0.10
*/
public class Ci_Exit extends AbstractCommandInterpreter {
/** The command for exit. */
public static final SkbShellCommand EXIT = SkbShellFactory.newCommand("exit", SkbShellFactory.SIMPLE_COMMANDS, "exit the shell", null);
/** The command for quit. */
public static final SkbShellCommand QUIT = SkbShellFactory.newCommand("quit", SkbShellFactory.SIMPLE_COMMANDS, "exit the shell", null);
/** The command for bye. */
public static final SkbShellCommand BYE = SkbShellFactory.newCommand("bye", SkbShellFactory.SIMPLE_COMMANDS, "exit the shell", null);
/**
* Returns an new 'exit' command interpreter.
*/
public Ci_Exit(){
super(new SkbShellCommand[]{EXIT, QUIT, BYE});
}
@Override
public int interpretCommand(String command, LineParser lp, MessageMgr mm) {
if(StringUtils.isBlank(command) || lp==null){
return -3;
}
if(!EXIT.getCommand().equals(command) && !QUIT.getCommand().equals(command) && !BYE.getCommand().equals(command)){
return -1;
}
return -2;
}
}
| apache-2.0 |
ifgeny87/Inno-Classroom-Work | src/main/java/ru/innolearn/day26/patterns/adapter/Main.java | 884 | package ru.innolearn.day26.patterns.adapter;
/**
* Пример Адаптера через наследование.
*
* Адаптер - Объект, обеспечивающий взаимодействие двух других объектов, один из которых использует, а другой предоставляет несовместимый с первым интерфейс.
*
* Created in project Inno-Classroom-Work on 18.01.17
*/
public class Main
{
public static void main(String[] args)
{
Chief ch = new ChiefAdapter();
Object dish = ch.makeLunch();
System.out.println(dish);
}
}
// Target
interface Chief
{
Object makeLunch();
}
// Adaptee
class Plumber
{
public Object getCake()
{
return "Cake";
}
}
// Adapter
class ChiefAdapter extends Plumber implements Chief
{
public Object makeLunch()
{
return getCake();
}
} | apache-2.0 |
lunisolar/magma | magma-basics/src/main/java/eu/lunisolar/magma/basics/meta/functional/type/MetaSupplier.java | 992 | /*
* This file is part of "lunisolar-magma".
*
* (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/).
*
* 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 eu.lunisolar.magma.basics.meta.functional.type;
import eu.lunisolar.magma.basics.meta.functional.MetaFunctionalInterface;
/** Meta interface for Supplier interfaces. */
public interface MetaSupplier extends MetaFunctionalInterface {
@Override default boolean isSupplier() {
return true;
}
}
| apache-2.0 |
gavanx/pdflearn | pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/function/PDFunctionType4.java | 3340 | /*
* 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.pdfbox.pdmodel.common.function;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.pdmodel.common.PDRange;
import org.apache.pdfbox.pdmodel.common.function.type4.ExecutionContext;
import org.apache.pdfbox.pdmodel.common.function.type4.InstructionSequence;
import org.apache.pdfbox.pdmodel.common.function.type4.InstructionSequenceBuilder;
import org.apache.pdfbox.pdmodel.common.function.type4.Operators;
import java.io.IOException;
/**
* This class represents a Type 4 (PostScript calculator) function in a PDF document.
* <p>
* See section 3.9.4 of the PDF 1.4 Reference.
*/
public class PDFunctionType4 extends PDFunction {
private static final Operators OPERATORS = new Operators();
private final InstructionSequence instructions;
/**
* Constructor.
*
* @param functionStream The function stream.
* @throws IOException if an I/O error occurs while reading the function
*/
public PDFunctionType4(COSBase functionStream) throws IOException {
super(functionStream);
byte[] bytes = getPDStream().toByteArray();
String string = new String(bytes, "ISO-8859-1");
this.instructions = InstructionSequenceBuilder.parse(string);
}
/**
* {@inheritDoc}
*/
public int getFunctionType() {
return 4;
}
/**
* {@inheritDoc}
*/
public float[] eval(float[] input) throws IOException {
//Setup the input values
ExecutionContext context = new ExecutionContext(OPERATORS);
for (int i = 0; i < input.length; i++) {
PDRange domain = getDomainForInput(i);
float value = clipToRange(input[i], domain.getMin(), domain.getMax());
context.getStack().push(value);
}
//Execute the type 4 function.
instructions.execute(context);
//Extract the output values
int numberOfOutputValues = getNumberOfOutputParameters();
int numberOfActualOutputValues = context.getStack().size();
if (numberOfActualOutputValues < numberOfOutputValues) {
throw new IllegalStateException("The type 4 function returned " + numberOfActualOutputValues + " values but the Range entry indicates that " + numberOfOutputValues + " values be returned.");
}
float[] outputValues = new float[numberOfOutputValues];
for (int i = numberOfOutputValues - 1; i >= 0; i--) {
PDRange range = getRangeForOutput(i);
outputValues[i] = context.popReal();
outputValues[i] = clipToRange(outputValues[i], range.getMin(), range.getMax());
}
//Return the resulting array
return outputValues;
}
}
| apache-2.0 |
anyflow/lannister | server/src/main/java/net/anyflow/lannister/plugin/DefaultAuthenticator.java | 1368 | /*
* Copyright 2016 The Lannister 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 net.anyflow.lannister.plugin;
public class DefaultAuthenticator implements Authenticator {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DefaultAuthenticator.class);
@Override
public Plugin clone() {
return new DefaultAuthenticator();
}
@Override
public boolean isValid(String clientId) {
if (logger.isDebugEnabled()) {
logger.debug("DefaultAuthenticator.isValid() called [clientId={}]", clientId);
}
return true;
}
@Override
public boolean isValid(String clientId, String userName, String password) {
if (logger.isDebugEnabled()) {
logger.debug("DefaultAuthenticator.isValid() called [clientId={}, userName={}, password={}]", clientId,
userName, password);
}
return true;
}
} | apache-2.0 |
tonilopezmr/Game-of-Thrones | app/src/main/java/es/npatarino/android/gotchallenge/common/di/activity/ActivityScope.java | 371 | /**
* Copyright (C) 2015 android10.org. All rights reserved.
*
* @author Fernando Cejas (the android10 coder)
*/
package es.npatarino.android.gotchallenge.common.di.activity;
import javax.inject.Scope;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Scope
@Retention(RUNTIME)
public @interface ActivityScope {
}
| apache-2.0 |
d3sw/conductor | contribs/src/main/java/com/netflix/conductor/contribs/condition/OriginalTitleKeysActionCondition.java | 1530 | package com.netflix.conductor.contribs.condition;
import com.netflix.conductor.core.events.JavaEventCondition;
import com.netflix.conductor.core.events.ScriptEvaluator;
import java.util.Objects;
public class OriginalTitleKeysActionCondition implements JavaEventCondition {
@Override
public boolean evalBool(Object payload) throws Exception {
Object featureId = ScriptEvaluator.evalJqAsObject(".data.originalTitleKeys.featureId", payload);
Object seasonId = ScriptEvaluator.evalJqAsObject(".data.originalTitleKeys.seasonId", payload);
Object episodeId = ScriptEvaluator.evalJqAsObject(".data.originalTitleKeys.episodeId", payload);
Object seriesId = ScriptEvaluator.evalJqAsObject(".data.originalTitleKeys.seriesId", payload);
Object franchiseId = ScriptEvaluator.evalJqAsObject(".data.originalTitleKeys.franchiseId", payload);
Object franchiseVersionId = ScriptEvaluator.evalJqAsObject(".data.originalTitleKeys.franchiseVersionId", payload);
Object seriesVersionId = ScriptEvaluator.evalJqAsObject(".data.originalTitleKeys.seriesVersionId", payload);
Object seasonVersionId = ScriptEvaluator.evalJqAsObject(".data.originalTitleKeys.seasonVersionId", payload);
return (Objects.nonNull(featureId) || (Objects.nonNull(seasonId) && Objects.nonNull(episodeId) && Objects.nonNull(seriesId)) ||
(Objects.nonNull(franchiseId) && Objects.nonNull(franchiseVersionId)) || (Objects.nonNull(seriesId) && Objects.nonNull(seriesVersionId)) ||
(Objects.nonNull(seasonId) && Objects.nonNull(seasonVersionId)));
}
}
| apache-2.0 |
christophd/citrus | vintage/citrus-java-dsl/src/test/java/com/consol/citrus/dsl/design/SeleniumTestDesignerTest.java | 12243 | /*
* Copyright 2006-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.dsl.design;
import com.consol.citrus.TestCase;
import com.consol.citrus.selenium.actions.AlertAction;
import com.consol.citrus.selenium.actions.CheckInputAction;
import com.consol.citrus.selenium.actions.ClearBrowserCacheAction;
import com.consol.citrus.selenium.actions.ClickAction;
import com.consol.citrus.selenium.actions.CloseWindowAction;
import com.consol.citrus.selenium.actions.FindElementAction;
import com.consol.citrus.selenium.actions.GetStoredFileAction;
import com.consol.citrus.selenium.actions.HoverAction;
import com.consol.citrus.selenium.actions.JavaScriptAction;
import com.consol.citrus.selenium.actions.NavigateAction;
import com.consol.citrus.selenium.actions.OpenWindowAction;
import com.consol.citrus.selenium.actions.SetInputAction;
import com.consol.citrus.selenium.actions.StartBrowserAction;
import com.consol.citrus.selenium.actions.StopBrowserAction;
import com.consol.citrus.selenium.actions.StoreFileAction;
import com.consol.citrus.selenium.actions.SwitchWindowAction;
import com.consol.citrus.selenium.actions.WaitUntilAction;
import com.consol.citrus.selenium.endpoint.SeleniumBrowser;
import com.consol.citrus.dsl.UnitTestSupport;
import org.mockito.Mockito;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @author Christoph Deppisch
* @since 2.7
*/
public class SeleniumTestDesignerTest extends UnitTestSupport {
private SeleniumBrowser seleniumBrowser = Mockito.mock(SeleniumBrowser.class);
@Test
public void testSeleniumBuilder() {
MockTestDesigner builder = new MockTestDesigner(context) {
@Override
public void configure() {
selenium().start(seleniumBrowser);
selenium().navigate("http://localhost:9090");
selenium().find().element(By.id("target"));
selenium().find().element("class-name", "${cssClass}")
.tagName("button")
.enabled(false)
.displayed(false)
.text("Click Me!")
.style("color", "red")
.attribute("type", "submit");
selenium().click().element(By.linkText("Click Me!"));
selenium().hover().element(By.linkText("Hover Me!"));
selenium().setInput("Citrus").element(By.name("username"));
selenium().checkInput(false).element(By.xpath("//input[@type='checkbox']"));
selenium().javascript("alert('Hello!')")
.errors("This went wrong!");
selenium().alert().text("Hello!").accept();
selenium().clearCache();
selenium().store("classpath:download/file.txt");
selenium().getStored("file.txt");
selenium().open().window("my_window");
selenium().focus().window("my_window");
selenium().close().window("my_window");
selenium().waitUntil().hidden().element(By.name("hiddenButton"));
selenium().stop();
}
};
builder.configure();
TestCase test = builder.getTestCase();
int actionIndex = 0;
Assert.assertEquals(test.getActionCount(), 18);
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), StartBrowserAction.class);
StartBrowserAction startBrowserAction = (StartBrowserAction) test.getActions().get(actionIndex++);
Assert.assertEquals(startBrowserAction.getName(), "selenium:start");
Assert.assertNotNull(startBrowserAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), NavigateAction.class);
NavigateAction navigateAction = (NavigateAction) test.getActions().get(actionIndex++);
Assert.assertEquals(navigateAction.getName(), "selenium:navigate");
Assert.assertEquals(navigateAction.getPage(), "http://localhost:9090");
Assert.assertNull(navigateAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), FindElementAction.class);
FindElementAction findElementAction = (FindElementAction) test.getActions().get(actionIndex++);
Assert.assertEquals(findElementAction.getName(), "selenium:find");
Assert.assertEquals(findElementAction.getBy(), By.id("target"));
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), FindElementAction.class);
findElementAction = (FindElementAction) test.getActions().get(actionIndex++);
Assert.assertEquals(findElementAction.getName(), "selenium:find");
Assert.assertEquals(findElementAction.getProperty(), "class-name");
Assert.assertEquals(findElementAction.getPropertyValue(), "${cssClass}");
Assert.assertEquals(findElementAction.getTagName(), "button");
Assert.assertEquals(findElementAction.getText(), "Click Me!");
Assert.assertFalse(findElementAction.isEnabled());
Assert.assertFalse(findElementAction.isDisplayed());
Assert.assertEquals(findElementAction.getStyles().size(), 1L);
Assert.assertEquals(findElementAction.getStyles().get("color"), "red");
Assert.assertEquals(findElementAction.getAttributes().size(), 1L);
Assert.assertEquals(findElementAction.getAttributes().get("type"), "submit");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), ClickAction.class);
ClickAction clickAction = (ClickAction) test.getActions().get(actionIndex++);
Assert.assertEquals(clickAction.getName(), "selenium:click");
Assert.assertEquals(clickAction.getBy(), By.linkText("Click Me!"));
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), HoverAction.class);
HoverAction hoverAction = (HoverAction) test.getActions().get(actionIndex++);
Assert.assertEquals(hoverAction.getName(), "selenium:hover");
Assert.assertEquals(hoverAction.getBy(), By.linkText("Hover Me!"));
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), SetInputAction.class);
SetInputAction setInputAction = (SetInputAction) test.getActions().get(actionIndex++);
Assert.assertEquals(setInputAction.getName(), "selenium:set-input");
Assert.assertEquals(setInputAction.getBy(), By.name("username"));
Assert.assertEquals(setInputAction.getValue(), "Citrus");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), CheckInputAction.class);
CheckInputAction checkInputAction = (CheckInputAction) test.getActions().get(actionIndex++);
Assert.assertEquals(checkInputAction.getName(), "selenium:check-input");
Assert.assertEquals(checkInputAction.getBy(), By.xpath("//input[@type='checkbox']"));
Assert.assertFalse(checkInputAction.isChecked());
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), JavaScriptAction.class);
JavaScriptAction javaScriptAction = (JavaScriptAction) test.getActions().get(actionIndex++);
Assert.assertEquals(javaScriptAction.getName(), "selenium:javascript");
Assert.assertEquals(javaScriptAction.getScript(), "alert('Hello!')");
Assert.assertEquals(javaScriptAction.getExpectedErrors().size(), 1L);
Assert.assertEquals(javaScriptAction.getExpectedErrors().get(0), "This went wrong!");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), AlertAction.class);
AlertAction alertAction = (AlertAction) test.getActions().get(actionIndex++);
Assert.assertEquals(alertAction.getName(), "selenium:alert");
Assert.assertEquals(alertAction.getText(), "Hello!");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), ClearBrowserCacheAction.class);
ClearBrowserCacheAction clearBrowserCacheAction = (ClearBrowserCacheAction) test.getActions().get(actionIndex++);
Assert.assertEquals(clearBrowserCacheAction.getName(), "selenium:clear-cache");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), StoreFileAction.class);
StoreFileAction storeFileAction = (StoreFileAction) test.getActions().get(actionIndex++);
Assert.assertEquals(storeFileAction.getName(), "selenium:store-file");
Assert.assertEquals(storeFileAction.getFilePath(), "classpath:download/file.txt");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), GetStoredFileAction.class);
GetStoredFileAction getStoredFileAction = (GetStoredFileAction) test.getActions().get(actionIndex++);
Assert.assertEquals(getStoredFileAction.getName(), "selenium:get-stored-file");
Assert.assertEquals(getStoredFileAction.getFileName(), "file.txt");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), OpenWindowAction.class);
OpenWindowAction openWindowAction = (OpenWindowAction) test.getActions().get(actionIndex++);
Assert.assertEquals(openWindowAction.getName(), "selenium:open-window");
Assert.assertEquals(openWindowAction.getWindowName(), "my_window");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), SwitchWindowAction.class);
SwitchWindowAction switchWindowAction = (SwitchWindowAction) test.getActions().get(actionIndex++);
Assert.assertEquals(switchWindowAction.getName(), "selenium:switch-window");
Assert.assertEquals(switchWindowAction.getWindowName(), "my_window");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), CloseWindowAction.class);
CloseWindowAction closeWindowAction = (CloseWindowAction) test.getActions().get(actionIndex++);
Assert.assertEquals(closeWindowAction.getName(), "selenium:close-window");
Assert.assertEquals(closeWindowAction.getWindowName(), "my_window");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), WaitUntilAction.class);
WaitUntilAction waitUntilAction = (WaitUntilAction) test.getActions().get(actionIndex++);
Assert.assertEquals(waitUntilAction.getName(), "selenium:wait");
Assert.assertEquals(waitUntilAction.getBy(), By.name("hiddenButton"));
Assert.assertEquals(waitUntilAction.getCondition(), "hidden");
Assert.assertNull(findElementAction.getBrowser());
Assert.assertEquals(test.getActions().get(actionIndex).getClass(), StopBrowserAction.class);
StopBrowserAction stopBrowserAction = (StopBrowserAction) test.getActions().get(actionIndex);
Assert.assertEquals(stopBrowserAction.getName(), "selenium:stop");
Assert.assertNull(stopBrowserAction.getBrowser());
}
}
| apache-2.0 |
ly20050516/PictureServer | src/com/ly/user/User.java | 357 | package com.ly.user;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| apache-2.0 |
ecarm002/incubator-asterixdb | asterixdb/asterix-algebra/src/main/java/org/apache/asterix/optimizer/rules/DisjunctivePredicateToJoinRule.java | 10264 | /*
* 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.asterix.optimizer.rules;
import java.util.HashSet;
import java.util.List;
import org.apache.asterix.metadata.declared.MetadataProvider;
import org.apache.asterix.om.base.AOrderedList;
import org.apache.asterix.om.constants.AsterixConstantValue;
import org.apache.asterix.om.functions.BuiltinFunctions;
import org.apache.asterix.om.types.AOrderedListType;
import org.apache.asterix.om.types.IAType;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.commons.lang3.mutable.MutableObject;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.IOptimizationContext;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalExpressionTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.BroadcastExpressionAnnotation;
import org.apache.hyracks.algebricks.core.algebra.expressions.ConstantExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.IndexedNLJoinExpressionAnnotation;
import org.apache.hyracks.algebricks.core.algebra.expressions.ScalarFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.UnnestingFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.VariableReferenceExpression;
import org.apache.hyracks.algebricks.core.algebra.functions.AlgebricksBuiltinFunctions;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.core.algebra.functions.IFunctionInfo;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.EmptyTupleSourceOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.InnerJoinOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.SelectOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.UnnestOperator;
import org.apache.hyracks.algebricks.core.rewriter.base.IAlgebraicRewriteRule;
import org.apache.hyracks.api.exceptions.SourceLocation;
public class DisjunctivePredicateToJoinRule implements IAlgebraicRewriteRule {
@Override
public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
throws AlgebricksException {
MetadataProvider metadataProvider = (MetadataProvider) context.getMetadataProvider();
if (metadataProvider.isBlockingOperatorDisabled()) {
return false;
}
SelectOperator select;
if ((select = asSelectOperator(opRef)) == null) {
return false;
}
AbstractFunctionCallExpression condEx;
if ((condEx = asFunctionCallExpression(select.getCondition(), AlgebricksBuiltinFunctions.OR)) == null) {
return false;
}
List<Mutable<ILogicalExpression>> args = condEx.getArguments();
VariableReferenceExpression varEx = null;
IAType valType = null;
HashSet<AsterixConstantValue> values = new HashSet<AsterixConstantValue>();
for (Mutable<ILogicalExpression> arg : args) {
AbstractFunctionCallExpression fctCall;
if ((fctCall = asFunctionCallExpression(arg, AlgebricksBuiltinFunctions.EQ)) == null) {
return false;
}
boolean haveConst = false;
boolean haveVar = false;
List<Mutable<ILogicalExpression>> fctArgs = fctCall.getArguments();
for (Mutable<ILogicalExpression> fctArg : fctArgs) {
final ILogicalExpression argExpr = fctArg.getValue();
switch (argExpr.getExpressionTag()) {
case CONSTANT:
haveConst = true;
AsterixConstantValue value = (AsterixConstantValue) ((ConstantExpression) argExpr).getValue();
if (valType == null) {
valType = value.getObject().getType();
} else if (!isCompatible(valType, value.getObject().getType())) {
return false;
}
values.add(value);
break;
case VARIABLE:
haveVar = true;
final VariableReferenceExpression varArg = (VariableReferenceExpression) argExpr;
if (varEx == null) {
varEx = varArg;
} else if (!varEx.getVariableReference().equals(varArg.getVariableReference())) {
return false;
}
break;
default:
return false;
}
}
if (!(haveVar && haveConst)) {
return false;
}
}
SourceLocation sourceLoc = select.getSourceLocation();
AOrderedList list = new AOrderedList(new AOrderedListType(valType, "orderedlist"));
for (AsterixConstantValue value : values) {
list.add(value.getObject());
}
EmptyTupleSourceOperator ets = new EmptyTupleSourceOperator();
context.computeAndSetTypeEnvironmentForOperator(ets);
ILogicalExpression cExp = new ConstantExpression(new AsterixConstantValue(list));
Mutable<ILogicalExpression> mutCExp = new MutableObject<>(cExp);
IFunctionInfo scanFctInfo = BuiltinFunctions.getAsterixFunctionInfo(BuiltinFunctions.SCAN_COLLECTION);
UnnestingFunctionCallExpression scanExp = new UnnestingFunctionCallExpression(scanFctInfo, mutCExp);
scanExp.setSourceLocation(sourceLoc);
LogicalVariable scanVar = context.newVar();
UnnestOperator unn = new UnnestOperator(scanVar, new MutableObject<>(scanExp));
unn.setSourceLocation(sourceLoc);
unn.getInputs().add(new MutableObject<>(ets));
context.computeAndSetTypeEnvironmentForOperator(unn);
IFunctionInfo eqFctInfo = BuiltinFunctions.getAsterixFunctionInfo(AlgebricksBuiltinFunctions.EQ);
AbstractFunctionCallExpression eqExp = new ScalarFunctionCallExpression(eqFctInfo);
eqExp.setSourceLocation(sourceLoc);
VariableReferenceExpression scanVarRef = new VariableReferenceExpression(scanVar);
scanVarRef.setSourceLocation(sourceLoc);
eqExp.getArguments().add(new MutableObject<>(scanVarRef));
eqExp.getArguments().add(new MutableObject<>(varEx.cloneExpression()));
eqExp.getAnnotations().put(IndexedNLJoinExpressionAnnotation.INSTANCE,
IndexedNLJoinExpressionAnnotation.INSTANCE);
BroadcastExpressionAnnotation bcast = new BroadcastExpressionAnnotation();
bcast.setObject(BroadcastExpressionAnnotation.BroadcastSide.LEFT); // Broadcast the OR predicates branch.
eqExp.getAnnotations().put(BroadcastExpressionAnnotation.BROADCAST_ANNOTATION_KEY, bcast);
InnerJoinOperator jOp = new InnerJoinOperator(new MutableObject<>(eqExp));
jOp.setSourceLocation(sourceLoc);
jOp.getInputs().add(new MutableObject<>(unn));
jOp.getInputs().add(select.getInputs().get(0));
opRef.setValue(jOp);
context.computeAndSetTypeEnvironmentForOperator(jOp);
return true;
}
@Override
public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context) {
return false;
}
/**
* This checks the compatibility the types of the constants to ensure that the comparison behaves as expected
* when joining. Right now this compatibility is defined as type equality, but it could we relaxed.
* Once type promotion works correctly in all parts of the system, this check should not be needed anymore.
* (see https://code.google.com/p/asterixdb/issues/detail?id=716)
*
* @param t1
* one type
* @param t2
* another type
* @return true, if types are equal
*/
private static boolean isCompatible(IAType t1, IAType t2) {
return t1.equals(t2);
}
// some helpers
private static SelectOperator asSelectOperator(ILogicalOperator op) {
return op.getOperatorTag() == LogicalOperatorTag.SELECT ? (SelectOperator) op : null;
}
private static SelectOperator asSelectOperator(Mutable<ILogicalOperator> op) {
return asSelectOperator(op.getValue());
}
private static AbstractFunctionCallExpression asFunctionCallExpression(ILogicalExpression ex,
FunctionIdentifier fi) {
AbstractFunctionCallExpression fctCall = (ex.getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL
? (AbstractFunctionCallExpression) ex : null);
if (fctCall != null && (fi == null || fctCall.getFunctionIdentifier().equals(fi)))
return fctCall;
return null;
}
private static AbstractFunctionCallExpression asFunctionCallExpression(Mutable<ILogicalExpression> ex,
FunctionIdentifier fi) {
return asFunctionCallExpression(ex.getValue(), fi);
}
}
| apache-2.0 |
KurtTaylan/ocpJavaSE8preparation | src/chapter1AdvancedClassDesign/chapter1_2InstanceofExample/App.java | 2238 | package chapter1AdvancedClassDesign.chapter1_2InstanceofExample;
import chapter1AdvancedClassDesign.chapter1_2InstanceofExample.animalHierachy.Animal;
import chapter1AdvancedClassDesign.chapter1_2InstanceofExample.animalHierachy.HeavyAnimal;
import chapter1AdvancedClassDesign.chapter1_2InstanceofExample.animalHierachy.LightAnimal;
import chapter1AdvancedClassDesign.chapter1_2InstanceofExample.animals.Bird;
import chapter1AdvancedClassDesign.chapter1_2InstanceofExample.animals.Elephant;
import chapter1AdvancedClassDesign.chapter1_2InstanceofExample.animals.Hippo;
public class App {
public static void main(String[] args) {
HeavyAnimal elephant = new Elephant();
HeavyAnimal hippo = new Hippo();
/* 'instanceof' Checks cases and return boolean value */
boolean case1 = hippo instanceof HeavyAnimal;
boolean case2 = elephant instanceof HeavyAnimal;
boolean case3 = hippo instanceof Elephant;
System.out.println(case1);
System.out.println(case2);
System.out.println(case3);
/* "null" is not an object,so referencing it is returns false value */
HeavyAnimal nullElephant = null;
boolean case4 = nullElephant instanceof Object ;
System.out.println(case4);
/* interesting point; Doesn't compile because hippo is not an elephant-
* Hippo does not extend elephant directly or indirectly */
/* Hippo hippoOrigin = new Hippo();
boolean case5 = hippoOrigin instanceof Elephant;*/ // Doesnt compile
/* 'instanceof' can let you check unrelated interfaces at compile time */
Hippo heavyHippo = new Hippo();
boolean case5 = heavyHippo instanceof LightAnimal;
System.out.println(case5);
/*Generally 'instanceof' is using object type checks on API to work with interfaces
* Trying to passing animalTypes */
LightAnimal bird = new Bird();
workWithAnimals(hippo);
workWithAnimals(elephant);
workWithAnimals(bird);
}
private static void workWithAnimals(Animal animal) {
// Checking upcoming instance types
if (animal instanceof HeavyAnimal) {
((HeavyAnimal) animal).showWeight();
} else if (animal instanceof LightAnimal) {
((LightAnimal) animal).showHowLightWeight();
} else {
throw new RuntimeException("Unsupported animal");
}
}
}
| apache-2.0 |
aphex-/opusproto | project/editor/src/com/nukethemoon/tools/opusproto/editor/ui/sampler/formular/AContinentForm.java | 3152 | package com.nukethemoon.tools.opusproto.editor.ui.sampler.formular;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.nukethemoon.tools.opusproto.sampler.Samplers;
import com.nukethemoon.tools.opusproto.editor.ui.Styles;
import com.nukethemoon.tools.opusproto.editor.ui.sampler.AbstractSamplerForm;
import com.nukethemoon.tools.opusproto.editor.ui.sampler.InputTable;
import com.nukethemoon.tools.opusproto.sampler.acontinent.AContinentConfig;
import com.nukethemoon.tools.opusproto.sampler.AbstractSampler;
import com.nukethemoon.tools.opusproto.sampler.AbstractSamplerConfiguration;
public class AContinentForm extends AbstractSamplerForm {
private final InputTable inputTable;
private final String NAME_ITERATIONS = "iterations";
private final String NAME_GROWTH = "itr. growth";
private final String NAME_SIZE = "size";
private final String NAME_EDGE = "edge";
private final CheckBox cbSmoothEdge;
public AContinentForm(Skin skin, AbstractSampler sampler, Samplers pool) {
super(skin, sampler, pool);
inputTable = new InputTable(skin);
inputTable.setBackground(Styles.INNER_BACKGROUND);
inputTable.addEntry(NAME_ITERATIONS, 60);
inputTable.addEntry(NAME_GROWTH, 60);
inputTable.addEntry(NAME_SIZE, 60);
inputTable.addEntry(NAME_EDGE, 60);
inputTable.setEntryValueListener(new InputTable.EntryValueListener() {
@Override
public void onChange(String entryName, String entryValue) {
notifyChanges();
}
});
add(inputTable);
row();
cbSmoothEdge = new CheckBox("Smooth edge", skin);
cbSmoothEdge.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
notifyChanges();
}
});
add(cbSmoothEdge);
}
@Override
public boolean applyToConfig(AbstractSamplerConfiguration config) {
AContinentConfig c = ((AContinentConfig) config);
if (containsValidInteger(inputTable.getTextField(NAME_ITERATIONS))) {
if (containsValidFloat(inputTable.getTextField(NAME_GROWTH))) {
if (containsValidFloat(inputTable.getTextField(NAME_SIZE))) {
if (containsValidFloat(inputTable.getTextField(NAME_EDGE))) {
c.iterations = Integer.parseInt(inputTable.getTextField(NAME_ITERATIONS).getText());
c.growth = Float.parseFloat(inputTable.getTextField(NAME_GROWTH).getText());
c.size = Float.parseFloat(inputTable.getTextField(NAME_SIZE).getText());
c.edge = Float.parseFloat(inputTable.getTextField(NAME_EDGE).getText());
c.smoothEdge = cbSmoothEdge.isChecked();
return true;
}
}
}
}
return false;
}
@Override
public void loadFromConfig(AbstractSamplerConfiguration config) {
AContinentConfig c = ((AContinentConfig) config);
inputTable.getTextField(NAME_ITERATIONS).setText(c.iterations + "");
inputTable.getTextField(NAME_GROWTH).setText(c.growth + "");
inputTable.getTextField(NAME_SIZE).setText(c.size + "");
inputTable.getTextField(NAME_EDGE).setText(c.edge + "");
cbSmoothEdge.setChecked(c.smoothEdge);
}
}
| apache-2.0 |
joewalnes/idea-community | platform/platform-api/src/com/intellij/openapi/application/RunResult.java | 2371 | /*
* 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.openapi.application;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
public class RunResult<T> extends Result<T> {
private BaseActionRunnable<T> myActionRunnable;
private Throwable myThrowable;
protected RunResult() {
}
public RunResult(BaseActionRunnable<T> action) {
myActionRunnable = action;
}
public RunResult<T> run() {
try {
myActionRunnable.run(this);
} catch (ProcessCanceledException e) {
throw e; // this exception may occur from time to time and it shouldn't be catched
} catch (Throwable throwable) {
myThrowable = throwable;
if (!myActionRunnable.isSilentExecution()) {
if (throwable instanceof RuntimeException) throw (RuntimeException)throwable;
if (throwable instanceof Error) throw (Error)throwable;
else throw new RuntimeException(myThrowable);
}
}
finally {
myActionRunnable = null;
}
return this;
}
public T getResultObject() {
return myResult;
}
public RunResult logException(Logger logger) {
if (hasException()) {
logger.error(myThrowable);
}
return this;
}
public RunResult<T> throwException() {
if (hasException()) {
if (myThrowable instanceof RuntimeException) {
throw (RuntimeException)myThrowable;
}
if (myThrowable instanceof Error) {
throw (Error)myThrowable;
}
throw new RuntimeException(myThrowable);
}
return this;
}
public boolean hasException() {
return myThrowable != null;
}
public Throwable getThrowable() {
return myThrowable;
}
public void setThrowable(Exception throwable) {
myThrowable = throwable;
}
}
| apache-2.0 |
hhFate/FateCms | fate-model/src/main/java/fate/webapp/blog/model/FileListItem.java | 1499 | package fate.webapp.blog.model;
/**
* 用于从赛利亚OSS获取到文件信息后,经过处理之后返回给页面的格式
* @author Fate
*
*/
public class FileListItem {
/**
* 文件名
*/
private String fileName;
/**
* 用于显示的文件名(不带后缀)
*/
private String showName;
/**
* 处理过后的用于显示的文件大小
*/
private String fileSize;
/**
* 此处的文件类型关系到css样式,所以没采用Int
*/
private String type;
/**
* 处理过后的上传时间
*/
private String uploadDate;
/**
* 跳转地址,如果是文件夹则进入下级目录;如果是文件,则打开文件
*/
private String url;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getShowName() {
return showName;
}
public void setShowName(String showName) {
this.showName = showName;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUploadDate() {
return uploadDate;
}
public void setUploadDate(String uploadDate) {
this.uploadDate = uploadDate;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| apache-2.0 |
lyft/scoop | scoop-basics/src/main/java/com/example/scoop/basics/ui/Keyboard.java | 2288 | package com.example.scoop.basics.ui;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.IBinder;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import java.security.InvalidParameterException;
public final class Keyboard {
private static InputMethodManager getInputManager(Context paramContext) {
return (InputMethodManager) paramContext.getSystemService(Context.INPUT_METHOD_SERVICE);
}
public static void hideKeyboard(Context paramContext, IBinder paramIBindViewer) {
getInputManager(paramContext).hideSoftInputFromWindow(paramIBindViewer, 0);
}
public static void hideKeyboard(View paramView) {
hideKeyboard(paramView.getContext(), paramView.getWindowToken());
}
public static void showKeyboard(final View paramView) {
paramView.requestFocus();
paramView.post(new Runnable() {
@Override
public void run() {
getInputManager(paramView.getContext()).showSoftInput(paramView, 0);
}
});
}
public static void showOnStart(View view) {
setSoftInputMode(view,
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
}
public static void hideOnStart(View view) {
setSoftInputMode(view,
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private static void setSoftInputMode(View view, int inputMode) {
Context context = view.getContext();
getWindow(context).setSoftInputMode(inputMode);
}
private static Window getWindow(Context context) {
if (context instanceof Activity) {
Activity activity = (Activity) context;
return activity.getWindow();
} else if (context instanceof ContextWrapper) {
ContextWrapper contextWrapper = (ContextWrapper) context;
return getWindow(contextWrapper.getBaseContext());
} else {
throw new InvalidParameterException("Cannot find activity context");
}
}
} | apache-2.0 |
DICE-UNC/cas | cas-server-core/src/test/java/org/jasig/cas/mock/MockAuthenticationMetaDataPopulator.java | 1375 | /*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.mock;
import org.jasig.cas.authentication.AuthenticationBuilder;
import org.jasig.cas.authentication.AuthenticationMetaDataPopulator;
import org.jasig.cas.authentication.Credential;
/**
* @author Marvin S. Addison
* @since 3.0.0
*/
public class MockAuthenticationMetaDataPopulator implements AuthenticationMetaDataPopulator {
@Override
public void populateAttributes(final AuthenticationBuilder builder, final Credential credential) {}
@Override
public boolean supports(final Credential credential) {
return true;
}
}
| apache-2.0 |