repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
joewalnes/idea-community | platform/platform-impl/src/com/intellij/util/CachedValueImpl.java | 1483 | /*
* 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.
*/
/*
* Created by IntelliJ IDEA.
* User: mike
* Date: Jun 6, 2002
* Time: 5:41:42 PM
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij.util;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import org.jetbrains.annotations.NotNull;
public abstract class CachedValueImpl<T> extends CachedValueBase<T> implements CachedValue<T> {
private final CachedValueProvider<T> myProvider;
public CachedValueImpl(@NotNull CachedValueProvider<T> provider) {
myProvider = provider;
}
@Override
protected <P> CachedValueProvider.Result<T> doCompute(P param) {
return myProvider.compute();
}
public CachedValueProvider<T> getValueProvider() {
return myProvider;
}
@Override
public T getValue() {
return getValueWithLock(null);
}
}
| apache-2.0 |
tsadoklf/Ardom | julie/src/main/java/ardom/julie/ui/recycler_view/adapters/DayInfoSummaryFlexibleAdapter.java | 910 | package ardom.julie.ui.recycler_view.adapters;
import android.support.annotation.Nullable;
import java.util.List;
import ardom.common.ui.recycler_view.listItems.ListItemBase;
import eu.davidea.flexibleadapter.FlexibleAdapter;
/**
* Created by tsadoklf on 13/12/2016.
*/
public class DayInfoSummaryFlexibleAdapter extends FlexibleAdapter<ListItemBase> {
private List<ListItemBase> mItems;
public DayInfoSummaryFlexibleAdapter(@Nullable List<ListItemBase> items) {
super(items);
mItems = items;
}
public DayInfoSummaryFlexibleAdapter(@Nullable List<ListItemBase> items, @Nullable Object listeners) {
super(items, listeners);
mItems = items;
}
public DayInfoSummaryFlexibleAdapter(@Nullable List<ListItemBase> items, @Nullable Object listeners, boolean stableIds) {
super(items, listeners, stableIds);
mItems = items;
}
}
| apache-2.0 |
jbertram/activemq-artemis-old | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/NettyConnectorWithHTTPUpgradeTest.java | 11157 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.transports.netty;
import java.util.HashMap;
import java.util.Map;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQExceptionType;
import org.apache.activemq.artemis.api.core.ActiveMQNotConnectedException;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.tests.util.UnitTestCase;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptor;
import org.apache.activemq.artemis.core.remoting.impl.netty.PartialPooledByteBufAllocator;
import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServers;
import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static io.netty.handler.codec.http.HttpHeaders.Names.UPGRADE;
import static io.netty.handler.codec.http.HttpResponseStatus.SWITCHING_PROTOCOLS;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import static org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.MAGIC_NUMBER;
import static org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.SEC_ACTIVEMQ_REMOTING_ACCEPT;
import static org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.SEC_ACTIVEMQ_REMOTING_KEY;
import static org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.createExpectedResponse;
import static org.apache.activemq.artemis.tests.util.RandomUtil.randomString;
/**
* Test that Netty Connector can connect to a Web Server and upgrade from a HTTP request to its remoting protocol.
*/
public class NettyConnectorWithHTTPUpgradeTest extends UnitTestCase
{
private static final SimpleString QUEUE = new SimpleString("NettyConnectorWithHTTPUpgradeTest");
private static final int HTTP_PORT = 8080;
private Configuration conf;
private ActiveMQServer server;
private ServerLocator locator;
private String acceptorName;
private NioEventLoopGroup bossGroup;
private NioEventLoopGroup workerGroup;
@Override
@Before
public void setUp() throws Exception
{
super.setUp();
HashMap<String, Object> httpParams = new HashMap<String, Object>();
// This prop controls the usage of HTTP Get + Upgrade from Netty connector
httpParams.put(TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME, true);
httpParams.put(TransportConstants.PORT_PROP_NAME, HTTP_PORT);
acceptorName = randomString();
HashMap<String, Object> emptyParams = new HashMap<>();
conf = createDefaultConfig()
.setSecurityEnabled(false)
.addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, httpParams, acceptorName))
.addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, emptyParams, randomString()));
server = addServer(ActiveMQServers.newActiveMQServer(conf, false));
server.start();
locator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NETTY_CONNECTOR_FACTORY, httpParams));
addServerLocator(locator);
// THe web server owns the HTTP port, not ActiveMQ.
startWebServer(HTTP_PORT);
}
@After
public void tearDown() throws Exception
{
stopWebServer();
super.tearDown();
}
@Test
public void sendAndReceiveOverHTTPPort() throws Exception
{
ClientSessionFactory sf = createSessionFactory(locator);
ClientSession session = sf.createSession(false, true, true);
session.createQueue(QUEUE, QUEUE, null, false);
ClientProducer producer = session.createProducer(QUEUE);
final int numMessages = 100;
for (int i = 0; i < numMessages; i++)
{
ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE,
false,
0,
System.currentTimeMillis(),
(byte) 1);
message.getBodyBuffer().writeString("sendAndReceiveOverHTTPPort");
producer.send(message);
}
ClientConsumer consumer = session.createConsumer(QUEUE);
session.start();
for (int i = 0; i < numMessages; i++)
{
ClientMessage message2 = consumer.receive();
assertNotNull(message2);
assertEquals("sendAndReceiveOverHTTPPort", message2.getBodyBuffer().readString());
message2.acknowledge();
}
session.close();
}
@Test
public void HTTPUpgradeConnectorUsingNormalAcceptor() throws Exception
{
HashMap<String, Object> params = new HashMap<>();
// create a new locator that points an HTTP-upgrade connector to the normal acceptor
params.put(TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME, true);
long start = System.currentTimeMillis();
locator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NETTY_CONNECTOR_FACTORY, params));
Exception e = null;
try
{
createSessionFactory(locator);
// we shouldn't ever get here
fail();
}
catch (Exception x)
{
e = x;
}
// make sure we failed *before* the HTTP hand-shake timeout elapsed (which is hard-coded to 30 seconds, see org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.HttpUpgradeHandler.awaitHandshake())
assertTrue((System.currentTimeMillis() - start) < 30000);
assertNotNull(e);
assertTrue(e instanceof ActiveMQNotConnectedException);
assertTrue(((ActiveMQException) e).getType() == ActiveMQExceptionType.NOT_CONNECTED);
}
private void startWebServer(int port) throws InterruptedException
{
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>()
{
@Override
protected void initChannel(SocketChannel ch) throws Exception
{
// create a HTTP server
ChannelPipeline p = ch.pipeline();
p.addLast("decoder", new HttpRequestDecoder());
p.addLast("encoder", new HttpResponseEncoder());
p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>()
{
// handle HTTP GET + Upgrade with a handshake specific to ActiveMQ remoting.
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
{
if (msg instanceof HttpRequest)
{
HttpRequest request = (HttpRequest) msg;
for (Map.Entry<String, String> entry : request.headers())
{
System.out.println(entry);
}
String upgrade = request.headers().get(UPGRADE);
String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS);
response.headers().set(UPGRADE, upgrade);
response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey));
ctx.writeAndFlush(response);
// when the handshake is successful, the HTTP handlers are removed
ctx.pipeline().remove("decoder");
ctx.pipeline().remove("encoder");
ctx.pipeline().remove(this);
System.out.println("HTTP handshake sent, transferring channel");
// transfer the control of the channel to the Netty Acceptor
NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService().getAcceptor(acceptorName);
acceptor.transfer(ctx.channel());
// at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones.
}
}
});
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
{
ctx.flush();
}
});
b.bind(port).sync();
}
private void stopWebServer()
{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
| apache-2.0 |
Bai-Jie/VoiceBroadcastDevice | app/src/main/java/gq/baijie/voicebroadcastdevice/entity/Sound.java | 1287 | package gq.baijie.voicebroadcastdevice.entity;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import static gq.baijie.voicebroadcastdevice.storage.database.Contract.PATH_SOUND;
import static gq.baijie.voicebroadcastdevice.storage.database.Contract.Sound.COLUMN_FILE_NAME;
import static gq.baijie.voicebroadcastdevice.storage.database.Contract.Sound.COLUMN_TITLE;
import static gq.baijie.voicebroadcastdevice.storage.database.Contract.Sound._ID;
@DatabaseTable(tableName = PATH_SOUND)
public class Sound {
@DatabaseField(columnName = _ID, generatedId = true)
private long mId;
@DatabaseField(columnName = COLUMN_TITLE, canBeNull = false)
private String mTitle;
@DatabaseField(columnName = COLUMN_FILE_NAME, canBeNull = false)
private String mFileName;
public long getId() {
return mId;
}
public Sound setId(long id) {
mId = id;
return this;
}
public String getTitle() {
return mTitle;
}
public Sound setTitle(String title) {
mTitle = title;
return this;
}
public String getFileName() {
return mFileName;
}
public Sound setFileName(String fileName) {
mFileName = fileName;
return this;
}
}
| apache-2.0 |
akarnokd/RxJava2Extensions | src/test/java/hu/akarnokd/rxjava2/operators/ObservableFilterAsyncTest.java | 12143 | /*
* Copyright 2016-2019 David Karnok
*
* 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 hu.akarnokd.rxjava2.operators;
import static org.junit.Assert.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import hu.akarnokd.rxjava2.test.*;
import io.reactivex.*;
import io.reactivex.disposables.Disposables;
import io.reactivex.functions.*;
import io.reactivex.observers.TestObserver;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
public class ObservableFilterAsyncTest {
@Test
public void normal() {
Observable.range(1, 10)
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return v % 2 == 0 ? Observable.just(true) : Observable.<Boolean>empty();
}
}))
.test()
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void normal2() {
Observable.range(1, 10)
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return v % 2 == 0 ? Observable.just(true) : Observable.just(false);
}
}))
.test()
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void normalMultiInner() {
Observable.range(1, 10)
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return v % 2 == 0 ? Observable.fromArray(true, true) : Observable.<Boolean>empty();
}
}))
.test()
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void normalAsync() {
Observable.range(1, 10)
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
Observable<Boolean> r = v % 2 == 0 ? Observable.just(true) : Observable.<Boolean>empty();
return r.subscribeOn(Schedulers.computation());
}
}))
.test()
.awaitDone(5, TimeUnit.SECONDS)
.assertResult(2, 4, 6, 8, 10);
}
@Test
public void mainError() {
Observable.<Integer>error(new TestException())
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return v % 2 == 0 ? Observable.just(true) : Observable.<Boolean>empty();
}
}))
.test()
.assertFailure(TestException.class);
}
@Test
public void mainErrorDisposesInner() {
PublishSubject<Integer> ps1 = PublishSubject.create();
final PublishSubject<Boolean> ps2 = PublishSubject.create();
TestObserver<Integer> to = ps1
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return ps2;
}
}))
.test();
assertFalse(ps2.hasObservers());
ps1.onNext(1);
assertTrue(ps2.hasObservers());
ps1.onError(new TestException());
assertFalse(ps2.hasObservers());
to.assertFailure(TestException.class);
}
@Test
public void innerError() {
Observable.range(1, 10)
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return v % 2 == 0
? Observable.<Boolean>error(new TestException())
: Observable.just(true);
}
}))
.test()
.assertFailure(TestException.class, 1);
}
@Test
public void innerErrorDisposesInner() {
PublishSubject<Integer> ps1 = PublishSubject.create();
final PublishSubject<Boolean> ps2 = PublishSubject.create();
TestObserver<Integer> to = ps1
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return ps2;
}
}))
.test();
assertFalse(ps2.hasObservers());
ps1.onNext(1);
assertTrue(ps2.hasObservers());
ps2.onError(new TestException());
assertFalse(ps1.hasObservers());
to.assertFailure(TestException.class);
}
@Test
public void dispose() {
PublishSubject<Integer> ps1 = PublishSubject.create();
final PublishSubject<Boolean> ps2 = PublishSubject.create();
TestObserver<Integer> to = ps1
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return ps2;
}
}))
.test();
ps1.onNext(1);
to.dispose();
assertFalse(ps1.hasObservers());
assertFalse(ps2.hasObservers());
to.assertEmpty();
}
@Test
public void isDisposed() {
PublishSubject<Integer> ps1 = PublishSubject.create();
final PublishSubject<Boolean> ps2 = PublishSubject.create();
TestHelper.checkDisposed(ps1
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return ps2;
}
})));
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Integer>, ObservableSource<Integer>>() {
@Override
public ObservableSource<Integer> apply(Observable<Integer> o)
throws Exception {
return o.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return Observable.just(true);
}
}));
}
});
}
@Test
public void mapperCrash() {
Observable.range(1, 10)
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
throw new TestException();
}
}))
.test()
.assertFailure(TestException.class);
}
@Test
public void innerIgnoresDispose() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
Observable.just(1)
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return new Observable<Boolean>() {
@Override
protected void subscribeActual(
Observer<? super Boolean> observer) {
observer.onSubscribe(Disposables.empty());
observer.onNext(true);
observer.onNext(false);
observer.onError(new TestException());
observer.onComplete();
}
};
}
}))
.test()
.assertResult(1);
TestHelper.assertUndeliverable(errors, 0, TestException.class);
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void mainErrorsAfterInnerErrors() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
new Observable<Integer>() {
@Override
protected void subscribeActual(
Observer<? super Integer> observer) {
observer.onSubscribe(Disposables.empty());
observer.onNext(1);
observer.onError(new TestException("outer"));
}
}
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
throw new TestException("inner");
}
}))
.test()
.assertFailureAndMessage(TestException.class, "inner");
TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer");
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void innerErrorsAfterMainErrors() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
final AtomicReference<Observer<? super Boolean>> refInner = new AtomicReference<Observer<? super Boolean>>();
new Observable<Integer>() {
@Override
protected void subscribeActual(
Observer<? super Integer> observer) {
observer.onSubscribe(Disposables.empty());
observer.onNext(1);
observer.onError(new TestException("outer"));
refInner.get().onError(new TestException("inner"));
}
}
.compose(ObservableTransformers.filterAsync(new Function<Integer, ObservableSource<Boolean>>() {
@Override
public ObservableSource<Boolean> apply(Integer v)
throws Exception {
return new Observable<Boolean>() {
@Override
protected void subscribeActual(
Observer<? super Boolean> observer) {
observer.onSubscribe(Disposables.empty());
refInner.set(observer);
}
};
}
}, 10))
.test()
.assertFailureAndMessage(TestException.class, "outer");
TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner");
} finally {
RxJavaPlugins.reset();
}
}
}
| apache-2.0 |
yvoswillens/flowable-engine | modules/flowable-engine/src/main/java/org/flowable/engine/impl/util/CommandContextUtil.java | 29147 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.engine.impl.util;
import java.util.HashMap;
import java.util.Map;
import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher;
import org.flowable.common.engine.impl.context.Context;
import org.flowable.common.engine.impl.db.DbSqlSession;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.common.engine.impl.interceptor.EngineConfigurationConstants;
import org.flowable.common.engine.impl.persistence.cache.EntityCache;
import org.flowable.content.api.ContentEngineConfigurationApi;
import org.flowable.content.api.ContentService;
import org.flowable.dmn.api.DmnEngineConfigurationApi;
import org.flowable.dmn.api.DmnManagementService;
import org.flowable.dmn.api.DmnRepositoryService;
import org.flowable.dmn.api.DmnRuleService;
import org.flowable.engine.FlowableEngineAgenda;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.history.HistoryManager;
import org.flowable.engine.impl.persistence.entity.ActivityInstanceEntityManager;
import org.flowable.engine.impl.persistence.entity.AttachmentEntityManager;
import org.flowable.engine.impl.persistence.entity.ByteArrayEntityManager;
import org.flowable.engine.impl.persistence.entity.CommentEntityManager;
import org.flowable.engine.impl.persistence.entity.DeploymentEntityManager;
import org.flowable.engine.impl.persistence.entity.EventLogEntryEntityManager;
import org.flowable.engine.impl.persistence.entity.EventSubscriptionEntityManager;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;
import org.flowable.engine.impl.persistence.entity.HistoricActivityInstanceEntityManager;
import org.flowable.engine.impl.persistence.entity.HistoricDetailEntityManager;
import org.flowable.engine.impl.persistence.entity.HistoricProcessInstanceEntityManager;
import org.flowable.engine.impl.persistence.entity.ModelEntityManager;
import org.flowable.engine.impl.persistence.entity.ProcessDefinitionEntityManager;
import org.flowable.engine.impl.persistence.entity.ProcessDefinitionInfoEntityManager;
import org.flowable.engine.impl.persistence.entity.PropertyEntityManager;
import org.flowable.engine.impl.persistence.entity.ResourceEntityManager;
import org.flowable.engine.impl.persistence.entity.TableDataManager;
import org.flowable.entitylink.api.EntityLinkService;
import org.flowable.entitylink.api.history.HistoricEntityLinkService;
import org.flowable.entitylink.service.EntityLinkServiceConfiguration;
import org.flowable.form.api.FormEngineConfigurationApi;
import org.flowable.form.api.FormManagementService;
import org.flowable.form.api.FormRepositoryService;
import org.flowable.form.api.FormService;
import org.flowable.identitylink.service.HistoricIdentityLinkService;
import org.flowable.identitylink.service.IdentityLinkService;
import org.flowable.identitylink.service.IdentityLinkServiceConfiguration;
import org.flowable.idm.api.IdmEngineConfigurationApi;
import org.flowable.idm.api.IdmIdentityService;
import org.flowable.job.service.HistoryJobService;
import org.flowable.job.service.JobService;
import org.flowable.job.service.JobServiceConfiguration;
import org.flowable.job.service.TimerJobService;
import org.flowable.job.service.impl.asyncexecutor.FailedJobCommandFactory;
import org.flowable.task.service.HistoricTaskService;
import org.flowable.task.service.InternalTaskAssignmentManager;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.TaskServiceConfiguration;
import org.flowable.variable.service.HistoricVariableService;
import org.flowable.variable.service.VariableService;
import org.flowable.variable.service.VariableServiceConfiguration;
public class CommandContextUtil {
public static final String ATTRIBUTE_INVOLVED_EXECUTIONS = "ctx.attribute.involvedExecutions";
public static ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return getProcessEngineConfiguration(getCommandContext());
}
public static ProcessEngineConfigurationImpl getProcessEngineConfiguration(CommandContext commandContext) {
if (commandContext != null) {
return (ProcessEngineConfigurationImpl) commandContext.getEngineConfigurations().get(EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
}
return null;
}
// VARIABLE SERVICE
public static VariableServiceConfiguration getVariableServiceConfiguration() {
return getVariableServiceConfiguration(getCommandContext());
}
public static VariableServiceConfiguration getVariableServiceConfiguration(CommandContext commandContext) {
return (VariableServiceConfiguration) getProcessEngineConfiguration(commandContext).getServiceConfigurations()
.get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG);
}
public static VariableService getVariableService() {
return getVariableService(getCommandContext());
}
public static VariableService getVariableService(CommandContext commandContext) {
VariableService variableService = null;
VariableServiceConfiguration variableServiceConfiguration = getVariableServiceConfiguration();
if (variableServiceConfiguration != null) {
variableService = variableServiceConfiguration.getVariableService();
}
return variableService;
}
public static HistoricVariableService getHistoricVariableService() {
HistoricVariableService historicVariableService = null;
VariableServiceConfiguration variableServiceConfiguration = getVariableServiceConfiguration();
if (variableServiceConfiguration != null) {
historicVariableService = variableServiceConfiguration.getHistoricVariableService();
}
return historicVariableService;
}
// IDENTITY LINK SERVICE
public static IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration() {
return getIdentityLinkServiceConfiguration(getCommandContext());
}
public static IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration(CommandContext commandContext) {
return (IdentityLinkServiceConfiguration) getProcessEngineConfiguration(commandContext).getServiceConfigurations()
.get(EngineConfigurationConstants.KEY_IDENTITY_LINK_SERVICE_CONFIG);
}
public static IdentityLinkService getIdentityLinkService() {
return getIdentityLinkService(getCommandContext());
}
public static IdentityLinkService getIdentityLinkService(CommandContext commandContext) {
IdentityLinkService identityLinkService = null;
IdentityLinkServiceConfiguration identityLinkServiceConfiguration = getIdentityLinkServiceConfiguration(commandContext);
if (identityLinkServiceConfiguration != null) {
identityLinkService = identityLinkServiceConfiguration.getIdentityLinkService();
}
return identityLinkService;
}
public static HistoricIdentityLinkService getHistoricIdentityLinkService() {
HistoricIdentityLinkService historicIdentityLinkService = null;
IdentityLinkServiceConfiguration identityLinkServiceConfiguration = getIdentityLinkServiceConfiguration();
if (identityLinkServiceConfiguration != null) {
historicIdentityLinkService = identityLinkServiceConfiguration.getHistoricIdentityLinkService();
}
return historicIdentityLinkService;
}
// ENTITY LINK SERVICE
public static EntityLinkServiceConfiguration getEntityLinkServiceConfiguration() {
return getEntityLinkServiceConfiguration(getCommandContext());
}
public static EntityLinkServiceConfiguration getEntityLinkServiceConfiguration(CommandContext commandContext) {
return (EntityLinkServiceConfiguration) getProcessEngineConfiguration(commandContext).getServiceConfigurations()
.get(EngineConfigurationConstants.KEY_ENTITY_LINK_SERVICE_CONFIG);
}
public static EntityLinkService getEntityLinkService() {
return getEntityLinkService(getCommandContext());
}
public static EntityLinkService getEntityLinkService(CommandContext commandContext) {
EntityLinkService entityLinkService = null;
EntityLinkServiceConfiguration entityLinkServiceConfiguration = getEntityLinkServiceConfiguration(commandContext);
if (entityLinkServiceConfiguration != null) {
entityLinkService = entityLinkServiceConfiguration.getEntityLinkService();
}
return entityLinkService;
}
public static HistoricEntityLinkService getHistoricEntityLinkService() {
HistoricEntityLinkService historicEntityLinkService = null;
EntityLinkServiceConfiguration entityLinkServiceConfiguration = getEntityLinkServiceConfiguration();
if (entityLinkServiceConfiguration != null) {
historicEntityLinkService = entityLinkServiceConfiguration.getHistoricEntityLinkService();
}
return historicEntityLinkService;
}
// TASK SERVICE
public static TaskServiceConfiguration getTaskServiceConfiguration() {
return getTaskServiceConfiguration(getCommandContext());
}
public static TaskServiceConfiguration getTaskServiceConfiguration(CommandContext commandContext) {
return (TaskServiceConfiguration) getProcessEngineConfiguration(commandContext).getServiceConfigurations()
.get(EngineConfigurationConstants.KEY_TASK_SERVICE_CONFIG);
}
public static TaskService getTaskService() {
return getTaskService(getCommandContext());
}
public static TaskService getTaskService(CommandContext commandContext) {
TaskService taskService = null;
TaskServiceConfiguration taskServiceConfiguration = getTaskServiceConfiguration(commandContext);
if (taskServiceConfiguration != null) {
taskService = taskServiceConfiguration.getTaskService();
}
return taskService;
}
public static HistoricTaskService getHistoricTaskService() {
return getHistoricTaskService(getCommandContext());
}
public static HistoricTaskService getHistoricTaskService(CommandContext commandContext) {
HistoricTaskService historicTaskService = null;
TaskServiceConfiguration taskServiceConfiguration = getTaskServiceConfiguration(commandContext);
if (taskServiceConfiguration != null) {
historicTaskService = taskServiceConfiguration.getHistoricTaskService();
}
return historicTaskService;
}
// JOB SERVICE
public static JobServiceConfiguration getJobServiceConfiguration() {
return getJobServiceConfiguration(getCommandContext());
}
public static JobServiceConfiguration getJobServiceConfiguration(CommandContext commandContext) {
return (JobServiceConfiguration) getProcessEngineConfiguration(commandContext).getServiceConfigurations()
.get(EngineConfigurationConstants.KEY_JOB_SERVICE_CONFIG);
}
public static JobService getJobService() {
return getJobService(getCommandContext());
}
public static JobService getJobService(CommandContext commandContext) {
JobService jobService = null;
JobServiceConfiguration jobServiceConfiguration = getJobServiceConfiguration(commandContext);
if (jobServiceConfiguration != null) {
jobService = jobServiceConfiguration.getJobService();
}
return jobService;
}
public static TimerJobService getTimerJobService() {
return getTimerJobService(getCommandContext());
}
public static TimerJobService getTimerJobService(CommandContext commandContext) {
TimerJobService timerJobService = null;
JobServiceConfiguration jobServiceConfiguration = getJobServiceConfiguration(commandContext);
if (jobServiceConfiguration != null) {
timerJobService = jobServiceConfiguration.getTimerJobService();
}
return timerJobService;
}
public static HistoryJobService getHistoryJobService() {
return getHistoryJobService(getCommandContext());
}
public static HistoryJobService getHistoryJobService(CommandContext commandContext) {
HistoryJobService historyJobService = null;
JobServiceConfiguration jobServiceConfiguration = getJobServiceConfiguration(commandContext);
if (jobServiceConfiguration != null) {
historyJobService = jobServiceConfiguration.getHistoryJobService();
}
return historyJobService;
}
// IDM ENGINE
public static IdmEngineConfigurationApi getIdmEngineConfiguration() {
return getIdmEngineConfiguration(getCommandContext());
}
public static IdmEngineConfigurationApi getIdmEngineConfiguration(CommandContext commandContext) {
return (IdmEngineConfigurationApi) commandContext.getEngineConfigurations().get(EngineConfigurationConstants.KEY_IDM_ENGINE_CONFIG);
}
public static IdmIdentityService getIdmIdentityService() {
IdmIdentityService idmIdentityService = null;
IdmEngineConfigurationApi idmEngineConfiguration = getIdmEngineConfiguration();
if (idmEngineConfiguration != null) {
idmIdentityService = idmEngineConfiguration.getIdmIdentityService();
}
return idmIdentityService;
}
// DMN ENGINE
public static DmnEngineConfigurationApi getDmnEngineConfiguration() {
return getDmnEngineConfiguration(getCommandContext());
}
public static DmnEngineConfigurationApi getDmnEngineConfiguration(CommandContext commandContext) {
return (DmnEngineConfigurationApi) commandContext.getEngineConfigurations().get(EngineConfigurationConstants.KEY_DMN_ENGINE_CONFIG);
}
public static DmnRepositoryService getDmnRepositoryService() {
DmnRepositoryService dmnRepositoryService = null;
DmnEngineConfigurationApi dmnEngineConfiguration = getDmnEngineConfiguration();
if (dmnEngineConfiguration != null) {
dmnRepositoryService = dmnEngineConfiguration.getDmnRepositoryService();
}
return dmnRepositoryService;
}
public static DmnRuleService getDmnRuleService() {
DmnRuleService dmnRuleService = null;
DmnEngineConfigurationApi dmnEngineConfiguration = getDmnEngineConfiguration();
if (dmnEngineConfiguration != null) {
dmnRuleService = dmnEngineConfiguration.getDmnRuleService();
}
return dmnRuleService;
}
public static DmnManagementService getDmnManagementService() {
DmnManagementService dmnManagementService = null;
DmnEngineConfigurationApi dmnEngineConfiguration = getDmnEngineConfiguration();
if (dmnEngineConfiguration != null) {
dmnManagementService = dmnEngineConfiguration.getDmnManagementService();
}
return dmnManagementService;
}
// FORM ENGINE
public static FormEngineConfigurationApi getFormEngineConfiguration() {
return getFormEngineConfiguration(getCommandContext());
}
public static FormEngineConfigurationApi getFormEngineConfiguration(CommandContext commandContext) {
return (FormEngineConfigurationApi) commandContext.getEngineConfigurations().get(EngineConfigurationConstants.KEY_FORM_ENGINE_CONFIG);
}
public static FormRepositoryService getFormRepositoryService() {
return getFormRepositoryService(getCommandContext());
}
public static FormRepositoryService getFormRepositoryService(CommandContext commandContext) {
FormRepositoryService formRepositoryService = null;
FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(commandContext);
if (formEngineConfiguration != null) {
formRepositoryService = formEngineConfiguration.getFormRepositoryService();
}
return formRepositoryService;
}
public static FormService getFormService() {
return getFormService(getCommandContext());
}
public static FormService getFormService(CommandContext commandContext) {
FormService formService = null;
FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(commandContext);
if (formEngineConfiguration != null) {
formService = formEngineConfiguration.getFormService();
}
return formService;
}
public static FormManagementService getFormManagementService() {
return getFormManagementService(getCommandContext());
}
public static FormManagementService getFormManagementService(CommandContext commandContext) {
FormManagementService formManagementService = null;
FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(commandContext);
if (formEngineConfiguration != null) {
formManagementService = formEngineConfiguration.getFormManagementService();
}
return formManagementService;
}
// CONTENT ENGINE
public static ContentEngineConfigurationApi getContentEngineConfiguration() {
return getContentEngineConfiguration(getCommandContext());
}
public static ContentEngineConfigurationApi getContentEngineConfiguration(CommandContext commandContext) {
return (ContentEngineConfigurationApi) commandContext.getEngineConfigurations().get(EngineConfigurationConstants.KEY_CONTENT_ENGINE_CONFIG);
}
public static ContentService getContentService() {
return getContentService(getCommandContext());
}
public static ContentService getContentService(CommandContext commandContext) {
ContentService contentService = null;
ContentEngineConfigurationApi contentEngineConfiguration = getContentEngineConfiguration(commandContext);
if (contentEngineConfiguration != null) {
contentService = contentEngineConfiguration.getContentService();
}
return contentService;
}
public static FlowableEngineAgenda getAgenda() {
return getAgenda(getCommandContext());
}
public static FlowableEngineAgenda getAgenda(CommandContext commandContext) {
return commandContext.getSession(FlowableEngineAgenda.class);
}
public static DbSqlSession getDbSqlSession() {
return getDbSqlSession(getCommandContext());
}
public static DbSqlSession getDbSqlSession(CommandContext commandContext) {
return commandContext.getSession(DbSqlSession.class);
}
public static EntityCache getEntityCache() {
return getEntityCache(getCommandContext());
}
public static EntityCache getEntityCache(CommandContext commandContext) {
return commandContext.getSession(EntityCache.class);
}
@SuppressWarnings("unchecked")
public static void addInvolvedExecution(CommandContext commandContext, ExecutionEntity executionEntity) {
if (executionEntity.getId() != null) {
Map<String, ExecutionEntity> involvedExecutions = null;
Object obj = commandContext.getAttribute(ATTRIBUTE_INVOLVED_EXECUTIONS);
if (obj != null) {
involvedExecutions = (Map<String, ExecutionEntity>) obj;
} else {
involvedExecutions = new HashMap<>();
commandContext.addAttribute(ATTRIBUTE_INVOLVED_EXECUTIONS, involvedExecutions);
}
involvedExecutions.put(executionEntity.getId(), executionEntity);
}
}
@SuppressWarnings("unchecked")
public static Map<String, ExecutionEntity> getInvolvedExecutions(CommandContext commandContext) {
Object obj = commandContext.getAttribute(ATTRIBUTE_INVOLVED_EXECUTIONS);
if (obj != null) {
return (Map<String, ExecutionEntity>) obj;
}
return null;
}
public static boolean hasInvolvedExecutions(CommandContext commandContext) {
return getInvolvedExecutions(commandContext) != null;
}
public static TableDataManager getTableDataManager() {
return getTableDataManager(getCommandContext());
}
public static TableDataManager getTableDataManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getTableDataManager();
}
public static ByteArrayEntityManager getByteArrayEntityManager() {
return getByteArrayEntityManager(getCommandContext());
}
public static ByteArrayEntityManager getByteArrayEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getByteArrayEntityManager();
}
public static ResourceEntityManager getResourceEntityManager() {
return getResourceEntityManager(getCommandContext());
}
public static ResourceEntityManager getResourceEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getResourceEntityManager();
}
public static DeploymentEntityManager getDeploymentEntityManager() {
return getDeploymentEntityManager(getCommandContext());
}
public static DeploymentEntityManager getDeploymentEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getDeploymentEntityManager();
}
public static PropertyEntityManager getPropertyEntityManager() {
return getPropertyEntityManager(getCommandContext());
}
public static PropertyEntityManager getPropertyEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getPropertyEntityManager();
}
public static ProcessDefinitionEntityManager getProcessDefinitionEntityManager() {
return getProcessDefinitionEntityManager(getCommandContext());
}
public static ProcessDefinitionEntityManager getProcessDefinitionEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getProcessDefinitionEntityManager();
}
public static ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager() {
return getProcessDefinitionInfoEntityManager(getCommandContext());
}
public static ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getProcessDefinitionInfoEntityManager();
}
public static ExecutionEntityManager getExecutionEntityManager() {
return getExecutionEntityManager(getCommandContext());
}
public static ExecutionEntityManager getExecutionEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getExecutionEntityManager();
}
public static EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return getEventSubscriptionEntityManager(getCommandContext());
}
public static EventSubscriptionEntityManager getEventSubscriptionEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getEventSubscriptionEntityManager();
}
public static CommentEntityManager getCommentEntityManager() {
return getCommentEntityManager(getCommandContext());
}
public static CommentEntityManager getCommentEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getCommentEntityManager();
}
public static ModelEntityManager getModelEntityManager() {
return getModelEntityManager(getCommandContext());
}
public static ModelEntityManager getModelEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getModelEntityManager();
}
public static HistoryManager getHistoryManager() {
return getHistoryManager(getCommandContext());
}
public static HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() {
return getHistoricProcessInstanceEntityManager(getCommandContext());
}
public static HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getHistoricProcessInstanceEntityManager();
}
public static ActivityInstanceEntityManager getActivityInstanceEntityManager() {
return getActivityInstanceEntityManager(getCommandContext());
}
public static ActivityInstanceEntityManager getActivityInstanceEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getActivityInstanceEntityManager();
}
public static HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getHistoricActivityInstanceEntityManager(getCommandContext());
}
public static HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getHistoricActivityInstanceEntityManager();
}
public static HistoryManager getHistoryManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getHistoryManager();
}
public static HistoricDetailEntityManager getHistoricDetailEntityManager() {
return getHistoricDetailEntityManager(getCommandContext());
}
public static HistoricDetailEntityManager getHistoricDetailEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getHistoricDetailEntityManager();
}
public static AttachmentEntityManager getAttachmentEntityManager() {
return getAttachmentEntityManager(getCommandContext());
}
public static AttachmentEntityManager getAttachmentEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getAttachmentEntityManager();
}
public static EventLogEntryEntityManager getEventLogEntryEntityManager() {
return getEventLogEntryEntityManager(getCommandContext());
}
public static EventLogEntryEntityManager getEventLogEntryEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getEventLogEntryEntityManager();
}
public static FlowableEventDispatcher getEventDispatcher() {
return getEventDispatcher(getCommandContext());
}
public static FlowableEventDispatcher getEventDispatcher(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getEventDispatcher();
}
public static FailedJobCommandFactory getFailedJobCommandFactory() {
return getFailedJobCommandFactory(getCommandContext());
}
public static FailedJobCommandFactory getFailedJobCommandFactory(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getFailedJobCommandFactory();
}
public static ProcessInstanceHelper getProcessInstanceHelper() {
return getProcessInstanceHelper(getCommandContext());
}
public static ProcessInstanceHelper getProcessInstanceHelper(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getProcessInstanceHelper();
}
public static CommandContext getCommandContext() {
return Context.getCommandContext();
}
public static InternalTaskAssignmentManager getInternalTaskAssignmentManager(CommandContext commandContext) {
return getTaskServiceConfiguration(commandContext).getInternalTaskAssignmentManager();
}
public static InternalTaskAssignmentManager getInternalTaskAssignmentManager() {
return getInternalTaskAssignmentManager(getCommandContext());
}
}
| apache-2.0 |
fhussonnois/kafkastreams-cep | streams/src/main/java/com/github/fhuss/kafka/streams/cep/state/internal/builder/AggregatesStoreBuilder.java | 2467 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.fhuss.kafka.streams.cep.state.internal.builder;
import com.github.fhuss.kafka.streams.cep.core.state.AggregatesStore;
import com.github.fhuss.kafka.streams.cep.state.AggregatesStateStore;
import com.github.fhuss.kafka.streams.cep.state.internal.AggregatesStoreImpl;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
/**
* Default class to build {@link AggregatesStore} instance.
*
* @param <K> the type of keys
* @param <V> the type of values
*/
public class AggregatesStoreBuilder<K, V> extends AbstractStoreBuilder<K, V, AggregatesStateStore<K>> {
private final KeyValueBytesStoreSupplier storeSupplier;
public AggregatesStoreBuilder(final KeyValueBytesStoreSupplier storeSupplier) {
super(storeSupplier.name(), null, null);
this.storeSupplier = storeSupplier;
}
/**
* {@inheritDoc}
*/
@Override
public AggregatesStateStore<K> build() {
final StoreBuilder<KeyValueStore<Bytes, byte[]>> builder = Stores.keyValueStoreBuilder(
storeSupplier,
Serdes.Bytes(),
Serdes.ByteArray());
if (enableLogging) {
builder.withLoggingEnabled(logConfig());
} else {
builder.withLoggingDisabled();
}
if (enableCaching) {
builder.withCachingEnabled();
}
return new AggregatesStoreImpl<>(builder.build());
}
}
| apache-2.0 |
andriydrozhko/reminder | src/main/java/com/reminder/enums/UserRole.java | 70 | package com.reminder.enums;
public enum UserRole {
USER, ADMIN
}
| apache-2.0 |
nkurihar/pulsar | pulsar-client-api/src/main/java/org/apache/pulsar/client/api/MessageRoutingMode.java | 2045 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.api;
/**
* Default routing mode for messages to partition.
*
* This logic is applied when the application is not setting a key {@link MessageBuilder#setKey(String)} on a particular
* message.
*/
public enum MessageRoutingMode {
/**
* If no key is provided, The partitioned producer will randomly pick one single partition and publish all the messages into that partition.
* If a key is provided on the message, the partitioned producer will hash the key and assign message to a particular partition.
*/
SinglePartition,
/**
* If no key is provided, the producer will publish messages across all partitions in round-robin fashion to achieve maximum throughput.
* Please note that round-robin is not done per individual message but rather it's set to the same boundary of batching delay, to ensure batching is effective.
*
* While if a key is specified on the message, the partitioned producer will hash the key and assign message to a particular partition.
*/
RoundRobinPartition,
/**
* Use custom message router implementation that will be called to determine the partition for a particular message.
*/
CustomPartition
}
| apache-2.0 |
jhwhetstone/cdsWebserver | networkServer/src/test/java/org/pesc/DocumentTests.java | 6907 | /*
* Copyright (c) 2017. California Community Colleges Technology Center
*
* 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.pesc;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.pesc.cds.domain.Transaction;
import org.pesc.cds.service.FileProcessorService;
import org.pesc.cds.service.SerializationService;
import org.pesc.sdk.message.collegetranscript.v1_6.CollegeTranscript;
import org.pesc.sdk.message.functionalacknowledgement.v1_2.Acknowledgment;
import org.pesc.sdk.message.transcriptrequest.v1_4.TranscriptRequest;
import org.pesc.sdk.message.transcriptresponse.v1_4.TranscriptResponse;
import org.pesc.sdk.sector.academicrecord.v1_9.HoldReasonType;
import org.pesc.sdk.sector.academicrecord.v1_9.ResponseHoldType;
import org.pesc.sdk.sector.academicrecord.v1_9.ResponseStatusType;
import org.pesc.sdk.util.ValidationUtils;
import org.pesc.sdk.util.XmlFileType;
import org.pesc.sdk.util.XmlSchemaVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.xml.sax.SAXException;
import javax.naming.OperationNotSupportedException;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Calendar;
import static junit.framework.TestCase.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = NetworkServerApplication.class, webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext
@ActiveProfiles("test")
public class DocumentTests {
public static Logger logger = LoggerFactory.getLogger(DocumentTests.class);
@Autowired
FileProcessorService fileProcessorService;
@Autowired
private SerializationService serializationService;
@Test
public void testFunctionalAckCreation() throws JAXBException, SAXException, OperationNotSupportedException {
Transaction transaction = new Transaction();
transaction.setSenderId(4);
transaction.setRecipientId(5);
Acknowledgment ack = fileProcessorService.createFunctionalAcknowledgement(transaction, "ack_1");
Marshaller marshaller = serializationService.createFunctionalAckMarshaller();
marshaller.setSchema(ValidationUtils.getSchema(XmlFileType.FUNCTIONAL_ACKNOWLEDGEMENT, XmlSchemaVersion.V1_2_0));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
marshaller.marshal(ack, byteArrayOutputStream);
ValidationUtils.validateDocument(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()),
XmlFileType.FUNCTIONAL_ACKNOWLEDGEMENT,
XmlSchemaVersion.V1_2_0);
}
@Test
public void testTranscriptResponseCreation() throws JAXBException, SAXException, OperationNotSupportedException {
Unmarshaller u = serializationService.createTranscriptRequestUnmarshaller(true, false);
TranscriptRequest transcriptRequest = null;
try {
transcriptRequest = (TranscriptRequest) u.unmarshal(getClass().getClassLoader().getResource("xmlTranscript_request.xml"));
} catch (Exception e) {
logger.error("Error Unmarshalling TranscriptRequest", e);
throw e;
}
createAndValidateTranscriptResponse(transcriptRequest);
}
private void createAndValidateTranscriptResponse(TranscriptRequest transcriptRequest) throws JAXBException, SAXException, OperationNotSupportedException {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 3);
ResponseHoldType hold = fileProcessorService.createResponseHold(HoldReasonType.FINANCIAL, cal.getTime());
TranscriptResponse response = fileProcessorService.buildBaseTranscriptResponse(transcriptRequest.getTransmissionData().getDestination(),
transcriptRequest.getTransmissionData().getSource(),
"1",
"1-request-tracking-id",
"docid",
ResponseStatusType.HOLD,
Arrays.asList(new ResponseHoldType[]{hold}),
transcriptRequest.getRequests().get(0).getRequestedStudent()
);
Marshaller marshaller = serializationService.createTranscriptResponseMarshaller();
marshaller.setSchema(ValidationUtils.getSchema(XmlFileType.TRANSCRIPT_RESPONSE, XmlSchemaVersion.V1_4_0));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
marshaller.marshal(response, byteArrayOutputStream);
ValidationUtils.validateDocument(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), XmlFileType.TRANSCRIPT_RESPONSE, XmlSchemaVersion.V1_4_0);
}
@Test
public void testJSONSerializationOfJAXBPESCCollegeTranscript() throws JAXBException, SAXException, OperationNotSupportedException {
Unmarshaller unmarshaller = serializationService.createTranscriptUnmarshaller(false, false);
Object object = unmarshaller.unmarshal(getClass().getClassLoader().getResourceAsStream("college-transcript.xml"));
Marshaller marshaller = serializationService.createTranscriptMarshaller(true);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
marshaller.marshal(object, outputStream);
System.out.print(outputStream.toString());
InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
unmarshaller = serializationService.createTranscriptUnmarshaller(false, true);
object = unmarshaller.unmarshal(inputStream);
Assert.assertTrue("Failed to unmarshall JSON transcript from PESC College Transcript object.", object instanceof CollegeTranscript);
CollegeTranscript collegeTranscript = (CollegeTranscript)object;
Assert.assertTrue("Student's first name is incorrect.", collegeTranscript.getStudent().getPerson().getName().getFirstName().equals("John"));
}
}
| apache-2.0 |
elasticsoftwarefoundation/elasticactors | main/core/src/main/java/org/elasticsoftware/elasticactors/util/concurrent/ThreadBoundExecutor.java | 1122 | /*
* Copyright 2013 - 2022 The Original Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.elasticsoftware.elasticactors.util.concurrent;
/**
* ThreadBoundExecutor
*
* <p>
* A thread bound executor guarantees that a runnable executed on the executor that has the same key
* will always be executed by the same thread.
*
* @param <T> The type of the key
* @author Joost van de Wijgerd
*/
public interface ThreadBoundExecutor<T extends ThreadBoundEvent<?>> {
void execute(T runnable);
void shutdown();
int getThreadCount();
void init();
}
| apache-2.0 |
joobn72/qi4j-sdk | libraries/alarm/src/main/java/org/qi4j/library/alarm/StandardAlarmModelService.java | 11398 | /*
* Copyright 1996-2011 Niclas Hedhman.
*
* 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.qi4j.library.alarm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import org.qi4j.api.entity.Identity;
import org.qi4j.api.injection.scope.Structure;
import org.qi4j.api.mixin.Mixins;
import org.qi4j.api.service.ServiceComposite;
import org.qi4j.api.value.ValueBuilder;
import org.qi4j.api.value.ValueBuilderFactory;
/**
* The Standard AlarmPoint Model is centered around the Normal, Activated, Acknowledged
* and Deactivated states, and the triggers "activate", "deactivate",
* and "acknowledge".
* <p>
* The following matrix details the resulting grid.
* </p>
* <table summary="Transitions">
* <tr><th>Initial State</th><th>Trigger</th><th>Resulting State</th><th>Event Generated</th></tr>
* <tr><td>Normal</td><td>activate</td><td>Activated</td><td>activation</td></tr>
* <tr><td>Normal</td><td>deactivate</td><td>Normal</td><td>-</td></tr>
* <tr><td>Normal</td><td>acknowledge</td><td>Normal</td><td>-</td></tr>
* <tr><td>Activated</td><td>activate</td><td>Activated</td><td>-</td></tr>
* <tr><td>Activated</td><td>deactivate</td><td>Deactivated</td><td>deactivation</td></tr>
* <tr><td>Activated</td><td>acknowledge</td><td>Acknowledged</td><td>acknowledge</td></tr>
* <tr><td>Deactivated</td><td>activate</td><td>Activated</td><td>activation</td></tr>
* <tr><td>Deactivated</td><td>deactivate</td><td>Deativated</td><td>-</td></tr>
* <tr><td>Deactivated</td><td>acknowledge</td><td>Normal</td><td>acknowledge</td></tr>
* <tr><td>Acknowledged</td><td>activate</td><td>Acknowledged</td><td>-</td></tr>
* <tr><td>Acknowledged</td><td>deactivate</td><td>Normal</td><td>deactivation</td></tr>
* <tr><td>Acknowledged</td><td>acknowledge</td><td>Acknowledged</td><td>-</td></tr>
* </table>
*/
@Mixins( StandardAlarmModelService.StandardAlarmModelMixin.class )
public interface StandardAlarmModelService extends AlarmModel, ServiceComposite
{
class StandardAlarmModelMixin
implements AlarmModel
{
private static final List<String> TRIGGER_LIST;
private static final List<String> STATUS_LIST;
static
{
List<String> list1 = new ArrayList<String>();
list1.add( AlarmPoint.STATUS_NORMAL );
list1.add( AlarmPoint.STATUS_ACTIVATED );
list1.add( AlarmPoint.STATUS_DEACTIVATED );
list1.add( AlarmPoint.STATUS_ACKNOWLEDGED );
STATUS_LIST = Collections.unmodifiableList( list1 );
List<String> list2 = new ArrayList<String>();
list2.add( AlarmPoint.TRIGGER_ACTIVATE );
list2.add( AlarmPoint.TRIGGER_DEACTIVATE );
list2.add( AlarmPoint.TRIGGER_ACKNOWLEDGE );
TRIGGER_LIST = Collections.unmodifiableList( list2 );
}
@Structure
private ValueBuilderFactory vbf;
static ResourceBundle getResourceBundle( Locale locale )
{
if( locale == null )
{
locale = Locale.getDefault();
}
ClassLoader cl = StandardAlarmModelMixin.class.getClassLoader();
return ResourceBundle.getBundle( MODEL_BUNDLE_NAME, locale, cl );
}
/**
* Returns the Name of the AlarmModel.
* This normally returns the human readable technical name of
* the AlarmModel.
*/
@Override
public String modelName()
{
return "org.qi4j.library.alarm.model.standard";
}
/**
* Returns a Description of the AlarmModel in the default Locale.
* This normally returns a full Description of the AlarmModel in the
* default Locale.
*
* @return the description of the ModelProvider.
*/
@Override
public String modelDescription()
{
return modelDescription( null );
}
/**
* Returns a Description of the AlarmModel.
* This normally returns a full Description of the AlarmModel in the
* Locale. If Locale is <code><b>null</b></code>, then the
* default Locale is used.
*/
@Override
public String modelDescription( Locale locale )
{
ResourceBundle rb = getResourceBundle( locale );
return rb.getString( "MODEL_DESCRIPTION_STANDARD" );
}
/**
* Execute the required changes upon an AlarmTrigger.
* The AlarmSystem calls this method, for the AlarmStatus
* in the the AlarmPoint to be updated, as well as an AlarmEvent
* to be created.
*
* @param alarm the AlarmPoint object to be updated.
* @param trigger the AlarmTrigger that was used.
*/
@Override
public AlarmEvent evaluate( AlarmPoint alarm, String trigger )
{
if( trigger.equals( AlarmPoint.TRIGGER_ACTIVATE ) )
{
return activation( alarm );
}
else if( trigger.equals( AlarmPoint.TRIGGER_DEACTIVATE ) )
{
return deactivation( alarm );
}
else if( trigger.equals( AlarmPoint.TRIGGER_ACKNOWLEDGE ) )
{
return acknowledge( alarm );
}
else
{
throw new IllegalArgumentException( "'" + trigger + "' is not supported by this AlarmModel." );
}
}
/**
* Returns all the supported AlarmPoint triggers.
*/
@Override
public List<String> alarmTriggers()
{
return TRIGGER_LIST;
}
@Override
public List<String> statusList()
{
return STATUS_LIST;
}
@Override
public String computeTrigger( AlarmStatus status, boolean condition )
{
if( condition )
{
if( ( status.name( null ).equals( AlarmPoint.STATUS_DEACTIVATED ) ) ||
( status.name( null ).equals( AlarmPoint.STATUS_NORMAL ) ) )
{
return AlarmPoint.TRIGGER_ACTIVATE;
}
}
else
{
if( ( status.name( null ).equals( AlarmPoint.STATUS_ACTIVATED ) ) ||
( status.name( null ).equals( AlarmPoint.STATUS_ACKNOWLEDGED ) ) )
{
return AlarmPoint.TRIGGER_DEACTIVATE;
}
}
return null;
}
@Override
public boolean computeCondition( AlarmStatus status )
{
return ( status.name( null ).equals( AlarmPoint.STATUS_ACTIVATED ) ) ||
( status.name( null ).equals( AlarmPoint.STATUS_ACKNOWLEDGED ) );
}
/**
* StateMachine change for activate trigger.
*
* @param alarm the alarm that is being triggered.
*
* @return The event to be fired on activation.
*/
private AlarmEvent activation( AlarmPoint alarm )
{
AlarmStatus oldStatus = alarm.currentStatus();
if( ( oldStatus.name( null ).equals( AlarmPoint.STATUS_NORMAL ) ) ||
( oldStatus.name( null ).equals( AlarmPoint.STATUS_DEACTIVATED ) ) )
{
AlarmStatus newStatus = createStatus( AlarmPoint.STATUS_ACTIVATED );
return createEvent( ( (Identity) alarm ), oldStatus, newStatus, AlarmPoint.EVENT_ACTIVATION );
}
return null;
}
/**
* StateMachine change for activate trigger.
*
* @param alarm the alarm that is being triggered.
*
* @return The event to be fired on deactivation.
*/
private AlarmEvent deactivation( AlarmPoint alarm )
{
AlarmStatus oldStatus = alarm.currentStatus();
if( oldStatus.name( null ).equals( AlarmPoint.STATUS_ACKNOWLEDGED ) )
{
AlarmStatus newStatus = createStatus( AlarmPoint.STATUS_NORMAL );
return createEvent( ( (Identity) alarm ), oldStatus, newStatus, AlarmPoint.EVENT_DEACTIVATION );
}
else if( oldStatus.name( null ).equals( AlarmPoint.STATUS_ACTIVATED ) )
{
AlarmStatus newStatus = createStatus( AlarmPoint.STATUS_DEACTIVATED );
return createEvent( ( (Identity) alarm ), oldStatus, newStatus, AlarmPoint.EVENT_DEACTIVATION );
}
return null;
}
/**
* StateMachine change for activate trigger.
*
* @param alarm the alarm that is being triggered.
*
* @return The event to be fired on acknowledge.
*/
private AlarmEvent acknowledge( AlarmPoint alarm )
{
AlarmStatus oldStatus = alarm.currentStatus();
if( oldStatus.name( null ).equals( AlarmPoint.STATUS_DEACTIVATED ) )
{
AlarmStatus newStatus = createStatus( AlarmPoint.STATUS_NORMAL );
return createEvent( ( (Identity) alarm ), oldStatus, newStatus, AlarmPoint.EVENT_ACKNOWLEDGEMENT );
}
else if( oldStatus.name( null ).equals( AlarmPoint.STATUS_ACTIVATED ) )
{
AlarmStatus newStatus = createStatus( AlarmPoint.STATUS_ACKNOWLEDGED );
return createEvent( ( (Identity) alarm ), oldStatus, newStatus, AlarmPoint.EVENT_ACKNOWLEDGEMENT );
}
return null;
}
private AlarmStatus createStatus( String status )
{
ValueBuilder<AlarmStatus> builder = vbf.newValueBuilder( AlarmStatus.class );
AlarmStatus.State prototype = builder.prototypeFor( AlarmStatus.State.class );
prototype.name().set( status );
prototype.creationDate().set( new Date() );
return builder.newInstance();
}
private AlarmEvent createEvent( Identity alarmId,
AlarmStatus oldStatus,
AlarmStatus newStatus,
String eventSystemName
)
{
ValueBuilder<AlarmEvent> builder = vbf.newValueBuilder( AlarmEvent.class );
AlarmEvent prototype = builder.prototype();
prototype.alarmIdentity().set( alarmId.identity().get() );
prototype.eventTime().set( new Date() );
prototype.newStatus().set( newStatus );
prototype.oldStatus().set( oldStatus );
prototype.systemName().set( eventSystemName );
return builder.newInstance();
}
}
}
| apache-2.0 |
bhargavr/HomeAutomationServer | src/main/java/com/sjsu/cmpe273Server/dao/SecurityAlarmDao.java | 455 | package com.sjsu.cmpe273Server.dao;
import com.sjsu.cmpe273Server.model.SecurityAlarm;
import java.util.List;
import java.util.Optional;
public interface SecurityAlarmDao{
public List<SecurityAlarm> getAll();
public Optional<SecurityAlarm> read(String serialNumber);
public Optional<SecurityAlarm> create(SecurityAlarm securityAlarm);
public Optional<SecurityAlarm> update(SecurityAlarm securityAlarm);
public boolean delete(String serialNumber);
} | apache-2.0 |
devil110/coolweather | src/com/coolweather/app/activity/WeatherActivity.java | 5287 | package com.coolweather.app.activity;
import com.coolweather.app.R;
import com.coolweather.app.service.AutoUpdateService;
import com.coolweather.app.util.HttpCallBackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WeatherActivity extends Activity implements OnClickListener{
private TextView cityNameText;
private LinearLayout weatherInfoLayout;
private TextView publishText;
private TextView weatherDespText;
private TextView temp1Text;//ÆøÎÂ1
private TextView temp2Text;//ÆøÎÂ2
private TextView currentDateText;
private Button switchCity;
private Button refreshWeather;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_layout);
cityNameText = (TextView) findViewById(R.id.city_name);
weatherInfoLayout = (LinearLayout) findViewById(R.id.weather_info_layout);
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)){
Log.e("WeatherActivitys", "main1");
//ÓÐÏØ¼¶´úºÅʱ¾ÍÈ¥²éѯÌìÆø
publishText.setText("ÕýÔÚͬ²½ÖÐ...");
weatherInfoLayout.setVisibility(View.INVISIBLE);
cityNameText.setVisibility(View.INVISIBLE);
queryWeatherCode(countyCode);
}else{
Log.e("WeatherActivitys", "main2");
// ûÓÐÏØ¼¶´úºÅʱ¾ÍÖ±½ÓÏÔʾ±¾µØÌìÆø
showWeather();
}
switchCity.setOnClickListener(this);
refreshWeather.setOnClickListener(this);
}
private void queryWeatherCode(String countyCode) {
Log.e("WeatherActivitys", "queryWeatherCode");
String address = "http://www.weather.com.cn/data/list3/city"+countyCode+".xml";
Log.i("code",countyCode);
queryFromServer(address, "countyCode");
}
private void queryWeatherInfo(String weatherCode){
Log.e("WeatherActivitys", "queryWeatherInfo");
String address = "http://www.weather.com.cn/data/cityinfo/" +weatherCode + ".html";
queryFromServer(address, "weatherCode");
}
private void queryFromServer(final String address, final String type) {
Log.e("WeatherActivitys", "queryFromServer");
HttpUtil.sendHttpRequest(address, new HttpCallBackListener() {
@Override
public void onFinish(final String response) {
if("countyCode".equals(type)){
if(!TextUtils.isEmpty(response)){
Log.e("WeatherActivitys", "queryFromServer_countyCode");
String[] array = response.split("\\|");
if(array != null && array.length == 2){
String weatherCode = array[1];
queryWeatherInfo(weatherCode);
}
}
}else if("weatherCode".equals(type)){
Log.e("WeatherActivitys", "queryFromServer_weatherCode");
Utility.handleWeatherResponse(WeatherActivity.this, response);
runOnUiThread(new Runnable() {
public void run() {
showWeather();
}
});
}
}
@Override
public void onError(Exception e) {
Log.d("tag", "", e);
runOnUiThread(new Runnable() {
public void run() {
publishText.setText("ͬ²½Ê§°Ü");
}
});
}
});
}
//´ÓSharedPreferencesÎļþÖжÁÈ¡´æ´¢µÄÌìÆøÐÅÏ¢£¬²¢ÏÔʾµ½½çÃæÉÏ¡£
private void showWeather(){
Log.e("WeatherActivitys", "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);
}
@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;
}
}
}
| apache-2.0 |
conterra/babelfish-overpass | src/main/java/de/conterra/babelfish/overpass/config/CompressionMethodAdapter.java | 596 | package de.conterra.babelfish.overpass.config;
import org.openstreetmap.osmosis.xml.common.CompressionMethod;
/**
* defines an JAXB adapter of {@link CompressionMethod}s
*
* @author ChrissW-R1
* @version 0.2.0
* @since 0.2.0
*/
public class CompressionMethodAdapter {
/**
* converts a {@link CompressionMethod} to a {@link String}
*
* @param impl the {@link CompressionMethod} to convert
* @return the converted {@link CompressionMethod} as {@link String}
*
* @since 0.2.0
*/
public static String printEnumToString(CompressionMethod impl) {
return impl.toString();
}
}
| apache-2.0 |
keith-turner/fluo-recipes | modules/core/src/test/java/org/apache/fluo/recipes/core/export/it/ExportTestBase.java | 8970 | /*
* 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.fluo.recipes.core.export.it;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import com.google.common.collect.Iterators;
import org.apache.commons.io.FileUtils;
import org.apache.fluo.api.client.FluoClient;
import org.apache.fluo.api.client.FluoFactory;
import org.apache.fluo.api.client.LoaderExecutor;
import org.apache.fluo.api.client.Snapshot;
import org.apache.fluo.api.client.scanner.CellScanner;
import org.apache.fluo.api.client.scanner.ColumnScanner;
import org.apache.fluo.api.client.scanner.RowScanner;
import org.apache.fluo.api.config.FluoConfiguration;
import org.apache.fluo.api.data.Column;
import org.apache.fluo.api.data.ColumnValue;
import org.apache.fluo.api.data.Span;
import org.apache.fluo.api.mini.MiniFluo;
import org.apache.fluo.api.observer.ObserverProvider;
import org.apache.fluo.recipes.core.export.ExportQueue;
import org.apache.fluo.recipes.core.export.SequencedExport;
import org.apache.fluo.recipes.core.export.function.Exporter;
import org.apache.fluo.recipes.core.serialization.SimpleSerializer;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import static org.apache.fluo.api.observer.Observer.NotificationType.STRONG;
public class ExportTestBase {
private static Map<String, Map<String, RefInfo>> globalExports = new HashMap<>();
private static int exportCalls = 0;
protected static Set<String> getExportedReferees(String node) {
synchronized (globalExports) {
Set<String> ret = new HashSet<>();
Map<String, RefInfo> referees = globalExports.get(node);
if (referees == null) {
return ret;
}
referees.forEach((k, v) -> {
if (!v.deleted)
ret.add(k);
});
return ret;
}
}
protected static Map<String, Set<String>> getExportedReferees() {
synchronized (globalExports) {
Map<String, Set<String>> ret = new HashMap<>();
for (String k : globalExports.keySet()) {
Set<String> referees = getExportedReferees(k);
if (referees.size() > 0) {
ret.put(k, referees);
}
}
return ret;
}
}
protected static int getNumExportCalls() {
synchronized (globalExports) {
return exportCalls;
}
}
public static class RefExporter implements Exporter<String, RefUpdates> {
public static final String QUEUE_ID = "req";
private void updateExports(String key, long seq, String addedRef, boolean deleted) {
Map<String, RefInfo> referees = globalExports.computeIfAbsent(addedRef, k -> new HashMap<>());
referees.compute(key, (k, v) -> (v == null || v.seq < seq) ? new RefInfo(seq, deleted) : v);
}
@Override
public void export(Iterator<SequencedExport<String, RefUpdates>> exportIterator) {
ArrayList<SequencedExport<String, RefUpdates>> exportList = new ArrayList<>();
Iterators.addAll(exportList, exportIterator);
synchronized (globalExports) {
exportCalls++;
for (SequencedExport<String, RefUpdates> se : exportList) {
for (String addedRef : se.getValue().getAddedRefs()) {
updateExports(se.getKey(), se.getSequence(), addedRef, false);
}
for (String deletedRef : se.getValue().getDeletedRefs()) {
updateExports(se.getKey(), se.getSequence(), deletedRef, true);
}
}
}
}
}
protected MiniFluo miniFluo;
protected int getNumBuckets() {
return 13;
}
protected Integer getBufferSize() {
return null;
}
public static class ExportTestObserverProvider implements ObserverProvider {
@Override
public void provide(Registry or, Context ctx) {
ExportQueue<String, RefUpdates> refExportQueue =
ExportQueue.getInstance(RefExporter.QUEUE_ID, ctx.getAppConfiguration());
or.forColumn(new Column("content", "new"), STRONG).useObserver(
new DocumentObserver(refExportQueue));
refExportQueue.registerObserver(or, new RefExporter());
}
}
@Before
public void setUpFluo() throws Exception {
FileUtils.deleteQuietly(new File("target/mini"));
FluoConfiguration props = new FluoConfiguration();
props.setApplicationName("eqt");
props.setWorkerThreads(20);
props.setMiniDataDir("target/mini");
props.setObserverProvider(ExportTestObserverProvider.class);
SimpleSerializer.setSerializer(props, GsonSerializer.class);
if (getBufferSize() == null) {
ExportQueue.configure(RefExporter.QUEUE_ID).keyType(String.class).valueType(RefUpdates.class)
.buckets(getNumBuckets()).save(props);
} else {
ExportQueue.configure(RefExporter.QUEUE_ID).keyType(String.class).valueType(RefUpdates.class)
.buckets(getNumBuckets()).bufferSize(getBufferSize()).save(props);
}
miniFluo = FluoFactory.newMiniFluo(props);
globalExports.clear();
exportCalls = 0;
}
@After
public void tearDownFluo() throws Exception {
if (miniFluo != null) {
miniFluo.close();
}
}
protected static Set<String> ns(String... sa) {
return new HashSet<>(Arrays.asList(sa));
}
protected static String nk(int i) {
return String.format("%06d", i);
}
protected static Set<String> ns(int... ia) {
HashSet<String> ret = new HashSet<>();
for (int i : ia) {
ret.add(nk(i));
}
return ret;
}
public void assertEquals(Map<String, Set<String>> expected, Map<String, Set<String>> actual,
FluoClient fc) {
if (!expected.equals(actual)) {
System.out.println("*** diff ***");
diff(expected, actual);
System.out.println("*** fluo dump ***");
dump(fc);
System.out.println("*** map dump ***");
Assert.fail();
}
}
protected void loadRandom(FluoClient fc, int num, int maxDocId) {
try (LoaderExecutor loader = fc.newLoaderExecutor()) {
Random rand = new Random();
for (int i = 0; i < num; i++) {
String docid = String.format("%05d", rand.nextInt(maxDocId));
String[] refs = new String[rand.nextInt(20) + 1];
for (int j = 0; j < refs.length; j++) {
refs[j] = String.format("%05d", rand.nextInt(maxDocId));
}
loader.execute(new DocumentLoader(docid, refs));
}
}
}
protected void diff(Map<String, Set<String>> fr, Map<String, Set<String>> er) {
HashSet<String> allKeys = new HashSet<>(fr.keySet());
allKeys.addAll(er.keySet());
for (String k : allKeys) {
Set<String> s1 = fr.getOrDefault(k, Collections.emptySet());
Set<String> s2 = er.getOrDefault(k, Collections.emptySet());
HashSet<String> sub1 = new HashSet<>(s1);
sub1.removeAll(s2);
HashSet<String> sub2 = new HashSet<>(s2);
sub2.removeAll(s1);
if (sub1.size() > 0 || sub2.size() > 0) {
System.out.println(k + " " + sub1 + " " + sub2);
}
}
}
protected Map<String, Set<String>> getFluoReferees(FluoClient fc) {
Map<String, Set<String>> fluoReferees = new HashMap<>();
try (Snapshot snap = fc.newSnapshot()) {
Column currCol = new Column("content", "current");
RowScanner rowScanner = snap.scanner().over(Span.prefix("d:")).fetch(currCol).byRow().build();
for (ColumnScanner columnScanner : rowScanner) {
String docid = columnScanner.getsRow().substring(2);
for (ColumnValue columnValue : columnScanner) {
String[] refs = columnValue.getsValue().split(" ");
for (String ref : refs) {
if (ref.isEmpty())
continue;
fluoReferees.computeIfAbsent(ref, k -> new HashSet<>()).add(docid);
}
}
}
}
return fluoReferees;
}
public static void dump(FluoClient fc) {
try (Snapshot snap = fc.newSnapshot()) {
CellScanner scanner = snap.scanner().build();
scanner.forEach(rcv -> System.out.println("row:[" + rcv.getRow() + "] col:["
+ rcv.getColumn() + "] val:[" + rcv.getValue() + "]"));
}
}
}
| apache-2.0 |
csmith932/uas-schedule-generator | swac-datalayer/src/main/java/gov/faa/ang/swac/datalayer/storage/fileio/OutputRecord.java | 299 | package gov.faa.ang.swac.datalayer.storage.fileio;
/**
* Implementation of this Interface indicates that these records are written to 'output' folder. It can be used to
* avoid duplication when the same data is written to different folders (report etc ) *
*/
public interface OutputRecord {
}
| apache-2.0 |
lucafavatella/intellij-community | platform/platform-impl/src/com/intellij/ui/popup/BalloonPopupBuilderImpl.java | 7838 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.popup;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupAdapter;
import com.intellij.openapi.ui.popup.LightweightWindowEvent;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.BalloonImpl;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class BalloonPopupBuilderImpl implements BalloonBuilder {
@Nullable private final Map<Disposable, List<Balloon>> myStorage;
@Nullable private Disposable myAnchor;
private final JComponent myContent;
private Color myBorder = new JBColor(JBColor.GRAY, Gray._200);
@Nullable private Insets myBorderInsets = null;
private Color myFill = MessageType.INFO.getPopupBackground();
private boolean myHideOnMouseOutside = true;
private boolean myHideOnKeyOutside = true;
private long myFadeoutTime = -1;
private boolean myShowCallout = true;
private boolean myCloseButtonEnabled = false;
private boolean myHideOnFrameResize = true;
private boolean myHideOnLinkClick = false;
private ActionListener myClickHandler;
private boolean myCloseOnClick;
private int myAnimationCycle = 500;
private int myCalloutShift;
private int myPositionChangeXShift;
private int myPositionChangeYShift;
private boolean myHideOnAction = true;
private boolean myDialogMode;
private String myTitle;
private Insets myContentInsets = new Insets(2, 2, 2, 2);
private boolean myShadow = false;
private boolean mySmallVariant = false;
private Balloon.Layer myLayer;
private boolean myBlockClicks = false;
private boolean myRequestFocus = false;
public BalloonPopupBuilderImpl(@Nullable Map<Disposable, List<Balloon>> storage, @NotNull final JComponent content) {
myStorage = storage;
myContent = content;
}
@NotNull
@Override
public BalloonBuilder setHideOnAction(boolean hideOnAction) {
myHideOnAction = hideOnAction;
return this;
}
@NotNull
@Override
public BalloonBuilder setDialogMode(boolean dialogMode) {
myDialogMode = dialogMode;
return this;
}
@NotNull
@Override
public BalloonBuilder setBorderColor(@NotNull final Color color) {
myBorder = color;
return this;
}
@NotNull
@Override
public BalloonBuilder setBorderInsets(@Nullable Insets insets) {
myBorderInsets = insets;
return this;
}
@NotNull
@Override
public BalloonBuilder setFillColor(@NotNull final Color color) {
myFill = color;
return this;
}
@NotNull
@Override
public BalloonBuilder setHideOnClickOutside(final boolean hide) {
myHideOnMouseOutside = hide;
return this;
}
@NotNull
@Override
public BalloonBuilder setHideOnKeyOutside(final boolean hide) {
myHideOnKeyOutside = hide;
return this;
}
@NotNull
@Override
public BalloonBuilder setShowCallout(final boolean show) {
myShowCallout = show;
return this;
}
@NotNull
@Override
public BalloonBuilder setFadeoutTime(long fadeoutTime) {
myFadeoutTime = fadeoutTime;
return this;
}
@NotNull
@Override
public BalloonBuilder setBlockClicksThroughBalloon(boolean block) {
myBlockClicks = block;
return this;
}
@NotNull
@Override
public BalloonBuilder setRequestFocus(boolean requestFocus) {
myRequestFocus = requestFocus;
return this;
}
@NotNull
@Override
public BalloonBuilder setAnimationCycle(int time) {
myAnimationCycle = time;
return this;
}
@NotNull
@Override
public BalloonBuilder setHideOnFrameResize(boolean hide) {
myHideOnFrameResize = hide;
return this;
}
@NotNull
@Override
public BalloonBuilder setHideOnLinkClick(boolean hide) {
myHideOnLinkClick = hide;
return this;
}
@NotNull
@Override
public BalloonBuilder setPositionChangeXShift(int positionChangeXShift) {
myPositionChangeXShift = positionChangeXShift;
return this;
}
@NotNull
@Override
public BalloonBuilder setPositionChangeYShift(int positionChangeYShift) {
myPositionChangeYShift = positionChangeYShift;
return this;
}
@NotNull
@Override
public BalloonBuilder setCloseButtonEnabled(boolean enabled) {
myCloseButtonEnabled = enabled;
return this;
}
@NotNull
@Override
public BalloonBuilder setClickHandler(ActionListener listener, boolean closeOnClick) {
myClickHandler = listener;
myCloseOnClick = closeOnClick;
return this;
}
@NotNull
@Override
public BalloonBuilder setCalloutShift(int length) {
myCalloutShift = length;
return this;
}
@NotNull
@Override
public BalloonBuilder setTitle(@Nullable String title) {
myTitle = title;
return this;
}
@NotNull
@Override
public BalloonBuilder setContentInsets(Insets insets) {
myContentInsets = insets;
return this;
}
@NotNull
@Override
public BalloonBuilder setShadow(boolean shadow) {
myShadow = shadow;
return this;
}
@NotNull
@Override
public BalloonBuilder setSmallVariant(boolean smallVariant) {
mySmallVariant = smallVariant;
return this;
}
@NotNull
@Override
public BalloonBuilder setLayer(Balloon.Layer layer) {
myLayer = layer;
return this;
}
@NotNull
@Override
public BalloonBuilder setDisposable(@NotNull Disposable anchor) {
myAnchor = anchor;
return this;
}
@NotNull
@Override
public Balloon createBalloon() {
final BalloonImpl result = new BalloonImpl(
myContent, myBorder, myBorderInsets, myFill, myHideOnMouseOutside, myHideOnKeyOutside, myHideOnAction, myShowCallout, myCloseButtonEnabled,
myFadeoutTime, myHideOnFrameResize, myHideOnLinkClick, myClickHandler, myCloseOnClick, myAnimationCycle, myCalloutShift,
myPositionChangeXShift, myPositionChangeYShift, myDialogMode, myTitle, myContentInsets, myShadow, mySmallVariant, myBlockClicks,
myLayer, myRequestFocus);
if (myStorage != null && myAnchor != null) {
List<Balloon> balloons = myStorage.get(myAnchor);
if (balloons == null) {
myStorage.put(myAnchor, balloons = new ArrayList<Balloon>());
Disposer.register(myAnchor, new Disposable() {
@Override
public void dispose() {
List<Balloon> toDispose = myStorage.remove(myAnchor);
if (toDispose != null) {
for (Balloon balloon : toDispose) {
if (!balloon.isDisposed()) {
Disposer.dispose(balloon);
}
}
}
}
});
}
balloons.add(result);
result.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
if (!result.isDisposed()) {
Disposer.dispose(result);
}
}
});
}
return result;
}
}
| apache-2.0 |
FZZFVII/pipe | android/Pipe/factory/src/main/java/com/xym/factory/model/card/ApplyCard.java | 1475 | package com.xym.factory.model.card;
import java.util.Date;
/**
* 申请请求的Card, 用于推送一个申请请求
*
*/
public class ApplyCard {
// 申请Id
private String id;
// 附件
private String attach;
// 描述
private String desc;
// 目标的类型
private int type;
// 目标(群/人...的ID)
private String targetId;
// 申请人的Id
private String applicantId;
// 创建时间
private Date createAt;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAttach() {
return attach;
}
public void setAttach(String attach) {
this.attach = attach;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getTargetId() {
return targetId;
}
public void setTargetId(String targetId) {
this.targetId = targetId;
}
public String getApplicantId() {
return applicantId;
}
public void setApplicantId(String applicantId) {
this.applicantId = applicantId;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
}
| apache-2.0 |
stori-es/stori_es | dashboard/src/test/java/org/consumersunion/stories/common/shared/dto/ErrorApiResponseSerializationTest.java | 1288 | package org.consumersunion.stories.common.shared.dto;
import java.io.IOException;
import org.consumersunion.stories.server.api.rest.mapper.ObjectMapperConfigurator;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.restassured.path.json.JsonPath;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class ErrorApiResponseSerializationTest {
private final ObjectMapper objectMapper = new ObjectMapperConfigurator().configure(new ObjectMapper());
@Test
public void serialize() throws JsonProcessingException {
// When
String json = objectMapper.writeValueAsString(new ErrorApiResponse("some message"));
// Then
Metadata metadata = JsonPath.from(json).getObject("meta", Metadata.class);
assertNotNull(metadata);
}
@Test
public void deserialize() throws IOException {
// Given
String json = "{\"meta\":{}}";
// When
ErrorApiResponse storiesApiResponse = objectMapper.readValue(json, ErrorApiResponse.class);
// Then
assertNull(storiesApiResponse.getData());
assertNotNull(storiesApiResponse.getMetadata());
}
}
| apache-2.0 |
rasmuslund/spring-tutorial | Ex_SimpleBootApp/src/test/java/dk/ralu/springtutorial/jpa/PersonRepositoryTest.java | 586 | package dk.ralu.springtutorial.jpa;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonRepositoryTest {
@Autowired
private PersonRepository personRepository;
@Test
public void findFullNameById() {
Assert.assertEquals("Rod Johnson", personRepository.findFullNameById(1L));
}
} | apache-2.0 |
GwtDomino/domino | ssl-server-configurator/src/main/java/org/dominokit/domino/http/server/config/PemCertificateConfigurator.java | 2591 | package org.dominokit.domino.http.server.config;
import com.google.auto.service.AutoService;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.net.JksOptions;
import io.vertx.core.net.PemKeyCertOptions;
import org.dominokit.domino.api.server.config.HttpServerConfigurator;
import org.dominokit.domino.api.server.config.ServerConfiguration;
import org.dominokit.domino.api.server.entrypoint.VertxContext;
import static java.lang.Boolean.TRUE;
import static org.dominokit.domino.http.server.config.ConfigKies.*;
@AutoService(HttpServerConfigurator.class)
public class PemCertificateConfigurator implements HttpServerConfigurator {
private static final String CERTIFICAT_PATH = "app.ssl.certificate.path";
@Override
public void configureHttpServer(VertxContext context, HttpServerOptions options) {
applyConfigurations(context.config(), options);
}
private void applyConfigurations(ServerConfiguration configuration, HttpServerOptions options) {
validateConfiguration(configuration);
if (sslEnabled(configuration)) {
enableSsl(configuration, options);
}
}
private void enableSsl(ServerConfiguration config, HttpServerOptions options) {
options.setSsl(TRUE);
options.setHost("localhost");
options.setPemKeyCertOptions(new PemKeyCertOptions()
.setCertPath(getPath(config))
.setKeyPath(getPath(config)))
.setPort(getPort(config));
}
private String getPath(ServerConfiguration configuration) {
return configuration.getString(CERTIFICAT_PATH);
}
private int getPort(ServerConfiguration configuration) {
return configuration.getInteger(HTTPS_PORT, DEFAULT_HTTPS_PORT);
}
private void validateConfiguration(ServerConfiguration configuration) {
if (sslEnabled(configuration))
validateSslPathAndPassword(configuration);
}
private Boolean sslEnabled(ServerConfiguration configuration) {
return configuration.getBoolean(SSL_CONFIGURATION_KEY, false);
}
private void validateSslPathAndPassword(ServerConfiguration configuration) {
if (missingCertificatePath(configuration))
throw new PemCertificateConfigurator.MissingCertificatePathInConfigurationException();
}
private boolean missingCertificatePath(ServerConfiguration configuration) {
return configuration.getString(CERTIFICAT_PATH, DEFAULT_EMPTY).isEmpty();
}
class MissingCertificatePathInConfigurationException extends RuntimeException {
}
}
| apache-2.0 |
trienvu/-Algorithm | Algorithm/src/vn/trienvd/c1/SearchingProblem.java | 363 | package vn.trienvd.c1;
public class SearchingProblem {
public static int searchV(int v,int [] A){
int n = A.length;
for(int i = 0; i < n; i++){
if(v == A[i])
{ return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] A = new int[] { 31, 41, 59, 26, 41, 58};
int ret = searchV(539,A);
System.out.println(ret);
}
}
| apache-2.0 |
spinnaker/halyard | halyard-deploy/src/main/java/com/netflix/spinnaker/halyard/deploy/spinnaker/v1/service/distributed/kubernetes/v2/KubernetesV2EchoService.java | 1976 | /*
* Copyright 2018 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v2;
import com.netflix.spinnaker.halyard.config.model.v1.node.DeploymentConfiguration;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.EchoService;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.ServiceSettings;
import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.DistributedService.DeployPriority;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Delegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Data
@Component
@EqualsAndHashCode(callSuper = true)
public class KubernetesV2EchoService extends EchoService
implements KubernetesV2Service<EchoService.Echo> {
final DeployPriority deployPriority = new DeployPriority(0);
@Delegate @Autowired KubernetesV2ServiceDelegate serviceDelegate;
@Override
public boolean isEnabled(DeploymentConfiguration deploymentConfiguration) {
return !deploymentConfiguration
.getDeploymentEnvironment()
.getHaServices()
.getEcho()
.isEnabled();
}
@Override
public ServiceSettings defaultServiceSettings(DeploymentConfiguration deploymentConfiguration) {
return new Settings(getActiveSpringProfiles(deploymentConfiguration));
}
}
| apache-2.0 |
zhousong3333/ChannelSDK | ewan/src/androidTest/java/com/skysoul/MR/ewan/ApplicationTest.java | 350 | package com.skysoul.MR.ewan;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | apache-2.0 |
usc/demo | src/main/java/org/usc/demo/observer/Publisher.java | 104 | package org.usc.demo.observer;
/**
*
* @author ShunLi
*/
public interface Publisher {
}
| apache-2.0 |
googleapis/java-pubsublite | google-cloud-pubsublite/src/main/java/com/google/cloud/pubsublite/internal/wire/Subscriber.java | 1142 | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsublite.internal.wire;
import com.google.api.core.ApiService;
import com.google.cloud.pubsublite.internal.CheckedApiException;
import com.google.cloud.pubsublite.proto.FlowControlRequest;
/**
* A generic PubSub Lite subscriber. Errors are handled out of band. Messages are sent out of band.
* Thread safe.
*/
public interface Subscriber extends ApiService {
// Allow the provided amount of messages and bytes to be sent by the server.
void allowFlow(FlowControlRequest request) throws CheckedApiException;
}
| apache-2.0 |
milandukovski/web-programming-starter | src/main/java/mk/ukim/finki/wp/web/rest/db/SpecifiedPersonResource.java | 932 | package mk.ukim.finki.wp.web.rest.db;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import mk.ukim.finki.wp.model.db.SpecifiedPerson;
import mk.ukim.finki.wp.service.db.SpecifiedPersonService;
import mk.ukim.finki.wp.specifications.BaseSpecification;
import mk.ukim.finki.wp.specifications.SpecifiedPersonSpecifications;
import mk.ukim.finki.wp.web.CrudResource;
@RestController
@RequestMapping("/data/rest/SpecifiedPerson")
public class SpecifiedPersonResource extends CrudResource<SpecifiedPerson, SpecifiedPersonService> {
@Autowired
private SpecifiedPersonService service;
@Override
public SpecifiedPersonService getService() {
return service;
}
@Override
public BaseSpecification<SpecifiedPerson> getSpecification() {
return new SpecifiedPersonSpecifications();
}
}
| apache-2.0 |
ontop/ontop | mapping/sql/owlapi/src/main/java/it/unibz/inf/ontop/exception/MappingBootstrappingException.java | 244 | package it.unibz.inf.ontop.exception;
/**
* Problem occurred while boostrapping the mapping
*/
public class MappingBootstrappingException extends Exception {
public MappingBootstrappingException(Exception e) {
super(e);
}
}
| apache-2.0 |
aguasiot/resource-server | src/main/java/cl/rgaticav94/shelke/resource/cloudinary/ImageController.java | 2765 | package cl.rgaticav94.shelke.resource.cloudinary;
import com.cloudinary.Cloudinary;
import com.cloudinary.utils.ObjectUtils;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.cloudinary.json.JSONArray;
import org.cloudinary.json.JSONObject;
import org.springframework.beans.factory.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@CrossOrigin
@RestController
@RequestMapping(value="/cloud")
public class ImageController
{
@Autowired
@Qualifier("com.cloudinary.cloud_name")
String mCloudName;
@Autowired
@Qualifier("com.cloudinary.api_key")
String mApiKey;
@Autowired
@Qualifier("com.cloudinary.api_secret")
String mApiSecret;
@GetMapping(value="/image")
public ResponseEntity< List<String> > get(
@RequestParam(value="name", required=false) String aName)
{
Cloudinary c=new Cloudinary("cloudinary://"+mApiKey+":"+mApiSecret+"@"+mCloudName);
List<String> retval=new ArrayList<String>();
try
{
Map response=c.api().resource("", ObjectUtils.asMap("type", "upload"));
JSONObject json=new JSONObject(response);
JSONArray ja=json.getJSONArray("resources");
for(int i=0; i<ja.length(); i++)
{
JSONObject j=ja.getJSONObject(i);
retval.add(j.getString("url"));
}
return new ResponseEntity< List<String> >(retval, HttpStatus.OK);
}
catch (Exception e)
{
return new ResponseEntity< List<String> >(HttpStatus.BAD_REQUEST);
}
}
@PostMapping(value="/image")
public ResponseEntity< String > post(
@RequestParam(value="upload", required=true) MultipartFile aFile)
{
Cloudinary c=new Cloudinary("cloudinary://"+mApiKey+":"+mApiSecret+"@"+mCloudName);
try
{
File f=Files.createTempFile("temp", aFile.getOriginalFilename()).toFile();
aFile.transferTo(f);
Map response=c.uploader().upload(f, ObjectUtils.emptyMap());
JSONObject json=new JSONObject(response);
String url=json.getString("url");
System.out.println(url);
return new ResponseEntity<String>("{\"status\":\"OK\", \"url\":\""+url+"\"}", HttpStatus.OK);
}
catch(Exception e)
{
return new ResponseEntity< String >("", HttpStatus.BAD_REQUEST);
}
}
};
| apache-2.0 |
VanRoy/spring-data-jest | spring-data-jest/src/main/java/com/github/vanroy/springdata/jest/mapper/JestSearchResultMapper.java | 657 | package com.github.vanroy.springdata.jest.mapper;
import com.github.vanroy.springdata.jest.aggregation.AggregatedPage;
import io.searchbox.core.SearchResult;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.springframework.data.domain.Pageable;
import java.util.List;
/**
* Jest specific search result mapper.
*
* @author Julien Roy
*/
public interface JestSearchResultMapper {
<T> AggregatedPage<T> mapResults(SearchResult response, Class<T> clazz, Pageable pageable);
<T> AggregatedPage<T> mapResults(SearchResult response, Class<T> clazz, List<AbstractAggregationBuilder> aggregations, Pageable pageable);
}
| apache-2.0 |
hmmlopez/citrus | modules/citrus-java-dsl/src/main/java/com/consol/citrus/dsl/builder/HttpServerActionBuilder.java | 5707 | /*
* Copyright 2006-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.dsl.builder;
import com.consol.citrus.TestAction;
import com.consol.citrus.dsl.actions.DelegatingTestAction;
import com.consol.citrus.endpoint.Endpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
/**
* Action executes http server operations such as receiving requests and sending response messages.
*
* @author Christoph Deppisch
* @since 2.4
*/
public class HttpServerActionBuilder extends AbstractTestActionBuilder<DelegatingTestAction<TestAction>> {
/** Spring application context */
private ApplicationContext applicationContext;
/** Target http client instance */
private final Endpoint httpServer;
/**
* Default constructor.
*/
public HttpServerActionBuilder(DelegatingTestAction<TestAction> action, Endpoint httpServer) {
super(action);
this.httpServer = httpServer;
}
/**
* Generic response builder for expecting response messages on client.
* @return
*/
public HttpServerResponseActionBuilder respond() {
HttpServerResponseActionBuilder httpServerResponseActionBuilder = new HttpServerResponseActionBuilder(action, httpServer)
.withApplicationContext(applicationContext);
return httpServerResponseActionBuilder;
}
/**
* Generic response builder for expecting response messages on client with response status code.
* @return
*/
public HttpServerResponseActionBuilder respond(HttpStatus status) {
HttpServerResponseActionBuilder httpServerResponseActionBuilder = new HttpServerResponseActionBuilder(action, httpServer)
.withApplicationContext(applicationContext)
.status(status);
return httpServerResponseActionBuilder;
}
/**
* Sends Http GET request as client to server.
*/
public HttpServerRequestActionBuilder get() {
return request(HttpMethod.GET, null);
}
/**
* Sends Http GET request as client to server.
*/
public HttpServerRequestActionBuilder get(String path) {
return request(HttpMethod.GET, path);
}
/**
* Sends Http POST request as client to server.
*/
public HttpServerRequestActionBuilder post() {
return request(HttpMethod.POST, null);
}
/**
* Sends Http POST request as client to server.
*/
public HttpServerRequestActionBuilder post(String path) {
return request(HttpMethod.POST, path);
}
/**
* Sends Http PUT request as client to server.
*/
public HttpServerRequestActionBuilder put() {
return request(HttpMethod.PUT, null);
}
/**
* Sends Http PUT request as client to server.
*/
public HttpServerRequestActionBuilder put(String path) {
return request(HttpMethod.PUT, path);
}
/**
* Sends Http DELETE request as client to server.
*/
public HttpServerRequestActionBuilder delete() {
return request(HttpMethod.DELETE, null);
}
/**
* Sends Http DELETE request as client to server.
*/
public HttpServerRequestActionBuilder delete(String path) {
return request(HttpMethod.DELETE, path);
}
/**
* Sends Http HEAD request as client to server.
*/
public HttpServerRequestActionBuilder head() {
return request(HttpMethod.HEAD, null);
}
/**
* Sends Http HEAD request as client to server.
*/
public HttpServerRequestActionBuilder head(String path) {
return request(HttpMethod.HEAD, path);
}
/**
* Sends Http OPTIONS request as client to server.
*/
public HttpServerRequestActionBuilder options() {
return request(HttpMethod.OPTIONS, null);
}
/**
* Sends Http OPTIONS request as client to server.
*/
public HttpServerRequestActionBuilder options(String path) {
return request(HttpMethod.OPTIONS, path);
}
/**
* Sends Http TRACE request as client to server.
*/
public HttpServerRequestActionBuilder trace() {
return request(HttpMethod.TRACE, null);
}
/**
* Sends Http TRACE request as client to server.
*/
public HttpServerRequestActionBuilder trace(String path) {
return request(HttpMethod.TRACE, path);
}
/**
* Sends Http PATCH request as client to server.
*/
public HttpServerRequestActionBuilder patch() {
return request(HttpMethod.PATCH, null);
}
/**
* Sends Http PATCH request as client to server.
*/
public HttpServerRequestActionBuilder patch(String path) {
return request(HttpMethod.PATCH, path);
}
/**
* Generic request builder with request method and path.
* @param method
* @param path
* @return
*/
private HttpServerRequestActionBuilder request(HttpMethod method, String path) {
HttpServerRequestActionBuilder httpServerRequestActionBuilder = new HttpServerRequestActionBuilder(action, httpServer)
.withApplicationContext(applicationContext)
.method(method);
if (StringUtils.hasText(path)) {
httpServerRequestActionBuilder.path(path);
}
return httpServerRequestActionBuilder;
}
/**
* Sets the Spring bean application context.
* @param applicationContext
*/
public HttpServerActionBuilder withApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
return this;
}
}
| apache-2.0 |
xfmysql/xfwdata | xfdatacenter/src/main/src/com/findide/utils/FileUtils.java | 1799 | package com.findide.utils;
import java.io.File;
import java.io.*;
import java.util.Properties;
public class FileUtils {
public static Properties getProperties(InputStream in) {
Properties prop = null;
try {
prop = new Properties();
//prop.load(in);//直接这么写,如果properties文件中有汉子,则汉字会乱码。因为未设置编码格式。
prop.load(new InputStreamReader(in, "utf-8"));
//path = prop.getProperty("path");
} catch (FileNotFoundException e) {
System.out.println("properties文件路径书写有误,请检查!");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return prop;
}
public static String readTxtFile(String filePath){
StringBuffer sb = new StringBuffer();
try {
String encoding="UTF-8";
File file=new File(filePath);
//if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
sb.append(lineTxt);
}
read.close();
//}else{
// System.out.println("找不到指定的文件");
//}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
finally{
return sb.toString();
}
}
}
| apache-2.0 |
floodlight/loxigen-artifacts | openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver15/OFBsnTlvNoArpResponseVer15.java | 5373 | // Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFBsnTlvNoArpResponseVer15 implements OFBsnTlvNoArpResponse {
private static final Logger logger = LoggerFactory.getLogger(OFBsnTlvNoArpResponseVer15.class);
// version: 1.5
final static byte WIRE_VERSION = 6;
final static int LENGTH = 4;
// OF message fields
//
// Immutable default instance
final static OFBsnTlvNoArpResponseVer15 DEFAULT = new OFBsnTlvNoArpResponseVer15(
);
final static OFBsnTlvNoArpResponseVer15 INSTANCE = new OFBsnTlvNoArpResponseVer15();
// private empty constructor - use shared instance!
private OFBsnTlvNoArpResponseVer15() {
}
// Accessors for OF message fields
@Override
public int getType() {
return 0x93;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
// no data members - do not support builder
public OFBsnTlvNoArpResponse.Builder createBuilder() {
throw new UnsupportedOperationException("OFBsnTlvNoArpResponseVer15 has no mutable properties -- builder unneeded");
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFBsnTlvNoArpResponse> {
@Override
public OFBsnTlvNoArpResponse readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property type == 0x93
short type = bb.readShort();
if(type != (short) 0x93)
throw new OFParseError("Wrong type: Expected=0x93(0x93), got="+type);
int length = U16.f(bb.readShort());
if(length != 4)
throw new OFParseError("Wrong length: Expected=4(4), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
if(logger.isTraceEnabled())
logger.trace("readFrom - returning shared instance={}", INSTANCE);
return INSTANCE;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFBsnTlvNoArpResponseVer15Funnel FUNNEL = new OFBsnTlvNoArpResponseVer15Funnel();
static class OFBsnTlvNoArpResponseVer15Funnel implements Funnel<OFBsnTlvNoArpResponseVer15> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFBsnTlvNoArpResponseVer15 message, PrimitiveSink sink) {
// fixed value property type = 0x93
sink.putShort((short) 0x93);
// fixed value property length = 4
sink.putShort((short) 0x4);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFBsnTlvNoArpResponseVer15> {
@Override
public void write(ByteBuf bb, OFBsnTlvNoArpResponseVer15 message) {
// fixed value property type = 0x93
bb.writeShort((short) 0x93);
// fixed value property length = 4
bb.writeShort((short) 0x4);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFBsnTlvNoArpResponseVer15(");
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
return true;
}
@Override
public int hashCode() {
int result = 1;
return result;
}
}
| apache-2.0 |
camunda/camunda-consulting | snippets/external-task-connector/src/main/java/com/camunda/demo/externaltask/ExternalTaskConnector.java | 2949 | package com.camunda.demo.externaltask;
import java.util.HashMap;
import java.util.Map;
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.client.topic.TopicSubscriptionBuilder;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
public class ExternalTaskConnector {
public static void main(String[] args) {
// bootstrap the client
ExternalTaskClient client = ExternalTaskClient.create()
.baseUrl("http://localhost:8080/engine-rest")
.lockDuration(60000)
.asyncResponseTimeout(100000)
.maxTasks(1)
.build();
// subscribe to the topic
TopicSubscriptionBuilder subscribtionBuilder = client.subscribe("REST_CONNECTOR");
subscribtionBuilder
.handler((externalTask, externalTaskService) -> {
System.out.println("Trying to Work on task " + externalTask.getActivityId());
HttpResponse<String> response = null;
Map<String, Object> vars = new HashMap<String, Object>();
String url = externalTask.getVariable("url");
String method = externalTask.getVariable("method");
//Map<String, String> headers = externalTask.getVariable("headers");
String headerKey = externalTask.getVariable("headerKey");
String headerValue = externalTask.getVariable("headerValue");
String payload = externalTask.getVariable("payload");
try {
if(method == null) {
externalTaskService.handleFailure(externalTask, "The method for the rest call is null", "You need to create a method variable whith either GET or POST as a value", 0, 0);
}else if (method.equals("GET")) {
response =
Unirest.get(url)
.header(headerKey, headerValue)
.asString();
}else if (method.equals("POST")) {
response = Unirest.post(url)
.header(headerKey, headerValue)
.body(payload)
.asString();
}else {
externalTaskService.handleFailure(externalTask, "The method is incorrect or not yet implemented", "You can either implement the method or maybe the type you supplied is not correct.", 0, 0);
}
}catch (UnirestException e) {
externalTaskService.handleFailure(externalTask, e.getMessage(), e.getCause().getMessage(), 0, 0);
e.printStackTrace();
}catch (Exception e) {
externalTaskService.handleFailure(externalTask, e.getMessage(), e.getCause().getMessage() , 0, 0);
e.printStackTrace();
}
vars.put("response_"+externalTask.getActivityId(), response.getBody());
vars.put("response_status_"+externalTask.getActivityId(), response.getStatus());
externalTaskService.complete(externalTask, vars);
}).open();
}
}
| apache-2.0 |
GoogleCloudPlatform/google-cloud-eclipse | plugins/com.google.cloud.tools.eclipse.util/src/com/google/cloud/tools/eclipse/util/JavaPackageValidator.java | 2368 | /*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.tools.eclipse.util;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
public class JavaPackageValidator {
private static final String PLUGIN_ID = "com.google.cloud.tools.eclipse.util"; //$NON-NLS-1$
/**
* Check if a string is a legal Java package name.
*/
public static IStatus validate(String packageName) {
if (packageName == null) {
return new Status(IStatus.ERROR, PLUGIN_ID, 45, "null package name", null);
} else if (packageName.isEmpty()) { // default package is allowed
return Status.OK_STATUS;
} else if (packageName.endsWith(".")) { //$NON-NLS-1$
// todo or allow this and strip the period
return new Status(IStatus.ERROR, PLUGIN_ID, 46,
Messages.getString("package.ends.with.period", packageName), null); //$NON-NLS-1$
} else if (containsWhitespace(packageName)) {
// very weird condition because validatePackageName allows internal white space
return new Status(IStatus.ERROR, PLUGIN_ID, 46,
Messages.getString("package.contains.whitespace", packageName), null); //$NON-NLS-1$
} else {
return JavaConventions.validatePackageName(
packageName, JavaCore.VERSION_1_4, JavaCore.VERSION_1_4);
}
}
/**
* Checks whether this string contains any C0 controls (characters with code
* point <= 0x20). This is the definition of white space used by String.trim()
* which is what we're prechecking here.
*/
private static boolean containsWhitespace(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) <= 0x20) {
return true;
}
}
return false;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/HPOResourceConfig.java | 7973 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.personalize.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes the resource configuration for hyperparameter optimization (HPO).
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/HPOResourceConfig" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HPOResourceConfig implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The maximum number of training jobs when you create a solution version. The maximum value for
* <code>maxNumberOfTrainingJobs</code> is <code>40</code>.
* </p>
*/
private String maxNumberOfTrainingJobs;
/**
* <p>
* The maximum number of parallel training jobs when you create a solution version. The maximum value for
* <code>maxParallelTrainingJobs</code> is <code>10</code>.
* </p>
*/
private String maxParallelTrainingJobs;
/**
* <p>
* The maximum number of training jobs when you create a solution version. The maximum value for
* <code>maxNumberOfTrainingJobs</code> is <code>40</code>.
* </p>
*
* @param maxNumberOfTrainingJobs
* The maximum number of training jobs when you create a solution version. The maximum value for
* <code>maxNumberOfTrainingJobs</code> is <code>40</code>.
*/
public void setMaxNumberOfTrainingJobs(String maxNumberOfTrainingJobs) {
this.maxNumberOfTrainingJobs = maxNumberOfTrainingJobs;
}
/**
* <p>
* The maximum number of training jobs when you create a solution version. The maximum value for
* <code>maxNumberOfTrainingJobs</code> is <code>40</code>.
* </p>
*
* @return The maximum number of training jobs when you create a solution version. The maximum value for
* <code>maxNumberOfTrainingJobs</code> is <code>40</code>.
*/
public String getMaxNumberOfTrainingJobs() {
return this.maxNumberOfTrainingJobs;
}
/**
* <p>
* The maximum number of training jobs when you create a solution version. The maximum value for
* <code>maxNumberOfTrainingJobs</code> is <code>40</code>.
* </p>
*
* @param maxNumberOfTrainingJobs
* The maximum number of training jobs when you create a solution version. The maximum value for
* <code>maxNumberOfTrainingJobs</code> is <code>40</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HPOResourceConfig withMaxNumberOfTrainingJobs(String maxNumberOfTrainingJobs) {
setMaxNumberOfTrainingJobs(maxNumberOfTrainingJobs);
return this;
}
/**
* <p>
* The maximum number of parallel training jobs when you create a solution version. The maximum value for
* <code>maxParallelTrainingJobs</code> is <code>10</code>.
* </p>
*
* @param maxParallelTrainingJobs
* The maximum number of parallel training jobs when you create a solution version. The maximum value for
* <code>maxParallelTrainingJobs</code> is <code>10</code>.
*/
public void setMaxParallelTrainingJobs(String maxParallelTrainingJobs) {
this.maxParallelTrainingJobs = maxParallelTrainingJobs;
}
/**
* <p>
* The maximum number of parallel training jobs when you create a solution version. The maximum value for
* <code>maxParallelTrainingJobs</code> is <code>10</code>.
* </p>
*
* @return The maximum number of parallel training jobs when you create a solution version. The maximum value for
* <code>maxParallelTrainingJobs</code> is <code>10</code>.
*/
public String getMaxParallelTrainingJobs() {
return this.maxParallelTrainingJobs;
}
/**
* <p>
* The maximum number of parallel training jobs when you create a solution version. The maximum value for
* <code>maxParallelTrainingJobs</code> is <code>10</code>.
* </p>
*
* @param maxParallelTrainingJobs
* The maximum number of parallel training jobs when you create a solution version. The maximum value for
* <code>maxParallelTrainingJobs</code> is <code>10</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HPOResourceConfig withMaxParallelTrainingJobs(String maxParallelTrainingJobs) {
setMaxParallelTrainingJobs(maxParallelTrainingJobs);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getMaxNumberOfTrainingJobs() != null)
sb.append("MaxNumberOfTrainingJobs: ").append(getMaxNumberOfTrainingJobs()).append(",");
if (getMaxParallelTrainingJobs() != null)
sb.append("MaxParallelTrainingJobs: ").append(getMaxParallelTrainingJobs());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof HPOResourceConfig == false)
return false;
HPOResourceConfig other = (HPOResourceConfig) obj;
if (other.getMaxNumberOfTrainingJobs() == null ^ this.getMaxNumberOfTrainingJobs() == null)
return false;
if (other.getMaxNumberOfTrainingJobs() != null && other.getMaxNumberOfTrainingJobs().equals(this.getMaxNumberOfTrainingJobs()) == false)
return false;
if (other.getMaxParallelTrainingJobs() == null ^ this.getMaxParallelTrainingJobs() == null)
return false;
if (other.getMaxParallelTrainingJobs() != null && other.getMaxParallelTrainingJobs().equals(this.getMaxParallelTrainingJobs()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getMaxNumberOfTrainingJobs() == null) ? 0 : getMaxNumberOfTrainingJobs().hashCode());
hashCode = prime * hashCode + ((getMaxParallelTrainingJobs() == null) ? 0 : getMaxParallelTrainingJobs().hashCode());
return hashCode;
}
@Override
public HPOResourceConfig clone() {
try {
return (HPOResourceConfig) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.personalize.model.transform.HPOResourceConfigMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
nus-ncl/services-in-one | service-mail/src/main/java/sg/ncl/service/mail/domain/MailService.java | 404 | package sg.ncl.service.mail.domain;
/**
* Created by dcszwang on 8/10/2016.
*/
public interface MailService {
void send(String from, String recipients, String subject, String content, boolean html, String cc, String bcc);
void send(String from, String[] recipients, String subject, String content, boolean html, String[] cc, String[] bcc);
void send(Email email);
void retry();
}
| apache-2.0 |
KRMAssociatesInc/eHMP | ehmp/product/production/hmp-main/src/main/java/gov/va/cpe/vpr/sync/msg/SecondarySiteSyncMessageHandler.java | 14597 | package gov.va.cpe.vpr.sync.msg;
import static gov.va.cpe.vpr.sync.vista.SynchronizationRpcConstants.VPR_STREAM_API_RPC_URI;
import static gov.va.hmp.vista.util.RpcUriUtils.VISTA_RPC_BROKER_SCHEME;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableMap;
import gov.va.cpe.idn.PatientIds;
import gov.va.cpe.vpr.IBroadcastService;
import gov.va.cpe.vpr.PatientDemographics;
import gov.va.cpe.vpr.PatientService;
import gov.va.cpe.vpr.dao.IVprSyncStatusDao;
import gov.va.cpe.vpr.pom.IPatientDAO;
import gov.va.cpe.vpr.pom.POMUtils;
import gov.va.cpe.vpr.sync.ISyncService;
import gov.va.cpe.vpr.sync.SyncStatus;
import gov.va.cpe.vpr.sync.expirationrulesengine.IExpirationRulesEngine;
import gov.va.cpe.vpr.sync.vista.VistaDataChunk;
import gov.va.hmp.healthtime.PointInTime;
import gov.va.hmp.util.LoggingUtil;
import gov.va.hmp.util.NullChecker;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.listener.SessionAwareMessageListener;
import org.springframework.jms.support.converter.SimpleMessageConverter;
public abstract class SecondarySiteSyncMessageHandler implements SessionAwareMessageListener {
private static final String CRLF = System.getProperty("line.separator");
protected abstract String getSiteId();
protected abstract String getTimerName();
protected abstract Logger getLogger();
protected abstract void setLogger(Logger theLogger);
protected abstract String getUid(PatientIds patientIds);
protected abstract String getPid(PatientIds patientIds);
protected MetricRegistry metrics;
protected IBroadcastService bcSvc;
protected SimpleMessageConverter messageConverter;
protected ISyncService syncService;
protected IVprSyncStatusDao syncStatusDao;
protected PatientService patientService;
protected IExpirationRulesEngine expirationRulesEngine;
protected int retryCount = 0;
@Autowired
public void setMetricRegistry(MetricRegistry metrics) {
this.metrics = metrics;
}
@Autowired
public void setBroadcastService(IBroadcastService bcSvc) {
this.bcSvc = bcSvc;
}
@Autowired
public void setMessageConverter(SimpleMessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
@Autowired
public void setSyncService(ISyncService syncService) {
this.syncService = syncService;
}
@Autowired
public void setSyncStatusDao(IVprSyncStatusDao syncStatusDao) {
this.syncStatusDao = syncStatusDao;
}
@Autowired
public void setPatientService(PatientService patientService) {
this.patientService = patientService;
}
@Autowired
public void setExpirationRulesEngine(IExpirationRulesEngine expirationRulesEngine) {
this.expirationRulesEngine = expirationRulesEngine;
}
private IPatientDAO patientDao;
@Autowired
public void setPatientDao(IPatientDAO patientDao) {
this.patientDao = patientDao;
}
protected abstract List<VistaDataChunk> fetchData(PatientIds patientIds, PatientDemographics pt) throws Exception;
@Override
public void onMessage(Message message, Session session) throws JMSException {
getLogger().debug("SecondarySiteSyncMessageHandler.onMessage(). Entering method...");
Timer.Context timerContext = metrics.timer(MetricRegistry.name(getTimerName())).time();
Map msg = (Map) messageConverter.fromMessage(message);
Map patientIdMap = (Map) msg.get("patientIds");
PatientIds patientIds = PatientIds.fromMap(patientIdMap);
Object objRetryCount = msg.get("retrycount");
if (objRetryCount != null) {
retryCount = (int) objRetryCount;
}
getLogger().debug("SecondarySiteSyncMessageHandler.onMessage(). calling fetchData()...");
Map<String, Map<String, Integer>> domainTotals = new HashMap<>();
List<VistaDataChunk> vistaDataChunks = null;
getLogger().debug("retryCount:" + retryCount);
int iterationCount = 0;
String syncError = "";
PatientDemographics pt = null;
while (true) {
try {
getLogger().debug("onMessage: Retrieving patient demographics for pid: " + getPid(patientIds));
getLogger().debug("onMessage: patientDao is = " + ((patientDao == null) ? "null" : "NOT null"));
pt = patientDao.findByPid(getPid(patientIds));
getLogger().debug("onMessage: Found patient demographics. pt: " + ((pt == null) ? "null" : pt.toJSON()));
vistaDataChunks = fetchData(patientIds, pt);
break;
} catch (Exception e) {
getLogger().error("Error while fetching data from site '" + getSiteId() + "'. Error: " + e.getMessage(), e);
++iterationCount;
if (iterationCount < retryCount + 1) {
getLogger().info("Retrying to fetch data.");
} else {
getLogger().error("'" + getSiteId() + "' site data could not be fetched even after " + retryCount + " retries.");
syncError = "Site could not be synced because of '" + e.getMessage().replace("java.lang.RuntimeException: ", "") + "'";
break;
}
}
}
// Calculate domain totals to place in the sync status
//----------------------------------------------------
if (vistaDataChunks != null) {
getLogger().debug("SecondarySiteSyncMessageHandler.onMessage(). Received " + vistaDataChunks.size() + " chunks.");
for (VistaDataChunk vistaDataChunk : vistaDataChunks ) {
Map<String, Integer> currentCounts = domainTotals.get(vistaDataChunk.getDomain());
if (currentCounts == null) {
currentCounts = ImmutableMap.<String, Integer>builder()
.put("total", 1)
.put("count", 1)
.build();
domainTotals.put(vistaDataChunk.getDomain(), currentCounts);
} else {
currentCounts = ImmutableMap.<String, Integer>builder()
.put("total", currentCounts.get("total") + 1)
.put("count", currentCounts.get("count") + 1)
.build();
domainTotals.put(vistaDataChunk.getDomain(), currentCounts);
}
}
} else {
getLogger().debug("SecondarySiteSyncMessageHandler.onMessage(). No data was received...");
}
// Create the sync status
//------------------------
SyncStatus syncStatus = syncStatusDao.findOneByPid(getPid(patientIds));
getLogger().debug(LoggingUtil.outputSyncStatus("onMessage: Retrieved sync status from JDS - pid: " + getPid(patientIds), syncStatus));
if (syncStatus != null) {
SyncStatus.VistaAccountSyncStatus vistaAccountSyncStatusForSystemId;
try {
vistaAccountSyncStatusForSystemId = syncStatus.getVistaAccountSyncStatusForSystemId(getSiteId());
} catch (NullPointerException npe) {
getLogger().error("onMessage: Exception occured. This should never happen. Failed to find site: " + getSiteId() + " in SyncStatus: " + syncStatus.getUid(), npe);
throw new IllegalStateException("No site found in " + syncStatus.getUid() + " for Site ID " + getSiteId());
}
if (vistaAccountSyncStatusForSystemId == null) {
getLogger().error("onMessage: This should never happen. Failed to find site: " + getSiteId() + " in SyncStatus: " + syncStatus.getUid());
vistaAccountSyncStatusForSystemId = syncStatus.addSite(patientIds.getUid(), patientIds.getEdipi(), getSiteId());
}
// Add domains totals and counts
vistaAccountSyncStatusForSystemId.setDomainExpectedTotals(domainTotals);
vistaAccountSyncStatusForSystemId.setSyncReceivedAllChunks(true);
// Record the last sync time
vistaAccountSyncStatusForSystemId.setLastSyncTime(PointInTime.now());
// Clear expiration
vistaAccountSyncStatusForSystemId.setExpiresOn(null);
// Set expiration
// TODO: Should this stay here? Or should it only be in VistaVprDataExtractEventStreamDAO.subscribePatientSecondarySites(...)?
expirationRulesEngine.evaluate(syncStatus);
//Set Sync Error message if any
vistaAccountSyncStatusForSystemId.setErrorMessage(syncError);
// If we are in an error condition, then set sync complete to true. Nothing more to do on this.
//------------------------------------------------------------------------------------------------
if (NullChecker.isNotNullish(syncError)) {
vistaAccountSyncStatusForSystemId.setSyncComplete(true);
}
HashSet<String> overwriteErrorMessageForSites = new HashSet<>();
overwriteErrorMessageForSites.add(getSiteId());
getLogger().debug(LoggingUtil.outputSyncStatus("onMessage: Before storing sync status - primary site pid: " + patientIds.getPid() + "; Secondary Site pid: " + getPid(patientIds), syncStatus));
syncStatus = syncStatusDao.saveMergeSyncStatus(syncStatus, overwriteErrorMessageForSites);
getLogger().debug(LoggingUtil.outputSyncStatus("onMessage: After storing sync status - primary site pid: " + patientIds.getPid() + "; Secondary Site pid: " + getPid(patientIds), syncStatus));
getLogger().debug("onMessage: After storing sync status - primary site pid: " + patientIds.getPid() + "; Secondary Site pid: " + getPid(patientIds) + "- Full Message: " + syncStatus.toJSON());
broadcastSyncStatus(syncStatus);
// Note that this chunk must be added last and only if we are not in an error condition.
// So that it is the last message processed and stored in the JDS.
//-----------------------------------------------------------------------------------------------------------
if (NullChecker.isNullish(syncError)) {
syncStatus.setSyncComplete(getSiteId(), true);
JsonNode dataNode = POMUtils.parseJSONtoNode(syncStatus.toJSON());
getLogger().debug("onMessage: Completed receiving data from secondary site. Creating VistaDataChunk for SyncStatus. pid:" + getPid(patientIds) +
"; + vistaId + " + "; syncStatus: " + CRLF + syncStatus.toJSON());
String url = VISTA_RPC_BROKER_SCHEME + "://" + this.getSiteId() + VPR_STREAM_API_RPC_URI;
int idx = 1;
int tot = 1;
VistaDataChunk chunk = VistaDataChunk.createVistaDataChunk(this.getSiteId(), url, dataNode, "syncStatus", idx, tot, pt,
VistaDataChunk.getProcessorParams(this.getSiteId(), getPid(patientIds), false), false);
if (vistaDataChunks != null) {
vistaDataChunks.add(chunk);
}
}
} else {
getLogger().error("Null value found for sync status for pid " + getPid(patientIds));
throw new RuntimeException("Error: A SyncStatus record should always exist at this point, but for some reason it did not. " +
"Aborting processing of the secondary site data for Site: " + this.getSiteId() + "; pid: " + getPid(patientIds) +
"; icn: " + patientIds.getIcn() + "; edipi: " + patientIds.getEdipi());
}
try {
if (vistaDataChunks != null) {
for (VistaDataChunk vistaDataChunk : vistaDataChunks ) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("onMessage: Sending chunk to queue with pid: " + vistaDataChunk.getPatientId() + "; " + vistaDataChunk.objectContentsOutput("vistaDataChunk"));
}
syncService.sendImportVistaDataExtractItemMsg(vistaDataChunk);
}
} else {
getLogger().debug("SecondarySiteSyncMessageHandler.onMessage(). No data was received...");
}
} catch (Exception e) {
HashSet<String> overwriteErrorMessageForSites = new HashSet<>();
overwriteErrorMessageForSites.add(getSiteId());
SyncStatus.VistaAccountSyncStatus vistaAccountSyncStatusForSystemId;
vistaAccountSyncStatusForSystemId = syncStatus.getVistaAccountSyncStatusForSystemId(getSiteId());
vistaAccountSyncStatusForSystemId.setErrorMessage(syncError);
vistaAccountSyncStatusForSystemId.setSyncComplete(true);
getLogger().debug(LoggingUtil.outputSyncStatus("onMessage: Before storing sync status - primary site pid: " + patientIds.getPid() + "; Secondary Site pid: " + getPid(patientIds), syncStatus));
syncStatus = syncStatusDao.saveMergeSyncStatus(syncStatus, overwriteErrorMessageForSites);
getLogger().debug(LoggingUtil.outputSyncStatus("onMessage: After storing sync status - primary site pid: " + patientIds.getPid() + "; Secondary Site pid: " + getPid(patientIds), syncStatus));
getLogger().error("SecondarySiteSyncMessageHandler.onMessage(). An exception was thrown. Message: " + e.getMessage(), e);
}
timerContext.stop();
}
private void broadcastSyncStatus(SyncStatus stat) {
Map<String, Object> message = new HashMap<String, Object>();
message.put("eventName", "syncStatusChange");
message.put("syncStatus", stat.getData());
bcSvc.broadcastMessage(message);
}
}
| apache-2.0 |
gentics/mesh | tests/tests-core/src/main/java/com/gentics/mesh/core/node/NodeConflictEndpointTest.java | 18357 | package com.gentics.mesh.core.node;
import static com.gentics.mesh.MeshVersion.CURRENT_API_BASE_PATH;
import static com.gentics.mesh.assertj.MeshAssertions.assertThat;
import static com.gentics.mesh.test.ClientHelper.call;
import static com.gentics.mesh.test.TestDataProvider.PROJECT_NAME;
import static com.gentics.mesh.test.TestSize.FULL;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.CONFLICT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
import com.gentics.mesh.FieldUtil;
import com.gentics.mesh.core.data.HibNodeFieldContainer;
import com.gentics.mesh.core.data.dao.ContentDao;
import com.gentics.mesh.core.data.i18n.I18NUtil;
import com.gentics.mesh.core.data.node.HibNode;
import com.gentics.mesh.core.data.node.field.list.HibStringFieldList;
import com.gentics.mesh.core.data.node.field.nesting.HibMicronodeField;
import com.gentics.mesh.core.db.Tx;
import com.gentics.mesh.core.rest.node.NodeResponse;
import com.gentics.mesh.core.rest.node.NodeUpdateRequest;
import com.gentics.mesh.core.rest.schema.ListFieldSchema;
import com.gentics.mesh.core.rest.schema.MicronodeFieldSchema;
import com.gentics.mesh.core.rest.schema.SchemaVersionModel;
import com.gentics.mesh.core.rest.schema.impl.ListFieldSchemaImpl;
import com.gentics.mesh.core.rest.schema.impl.MicronodeFieldSchemaImpl;
import com.gentics.mesh.parameter.impl.NodeParametersImpl;
import com.gentics.mesh.rest.client.MeshRestClientMessageException;
import com.gentics.mesh.test.MeshTestSetting;
import com.gentics.mesh.test.context.AbstractMeshTest;
import com.gentics.mesh.util.Tuple;
@MeshTestSetting(testSize = FULL, startServer = true)
public class NodeConflictEndpointTest extends AbstractMeshTest {
private HibNode getTestNode() {
return content("concorde");
}
private NodeUpdateRequest prepareNameFieldUpdateRequest(String nameFieldValue, String baseVersion) {
NodeUpdateRequest request = new NodeUpdateRequest();
request.setLanguage("en");
// Only update the name field
request.getFields().put("teaser", FieldUtil.createStringField(nameFieldValue));
request.setVersion(baseVersion);
return request;
}
@Test
public void testNoConflictUpdate() {
try (Tx trx = tx()) {
HibNode node = getTestNode();
NodeUpdateRequest request = prepareNameFieldUpdateRequest("1234", "1.0");
NodeParametersImpl parameters = new NodeParametersImpl();
parameters.setLanguages("en", "de");
// Invoke an initial update on the node
NodeResponse restNode = call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request, parameters));
assertThat(restNode).hasVersion("1.1");
// Update the node again but don't change any data. Base the update on 1.0 thus a conflict check must be performed. No conflict should occur. Since
// no fields have been altered no version should be created.
restNode = call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request, parameters));
assertThat(restNode).hasVersion("1.1");
// Update the node again but change some fields. A new version should be created (1.2)
request.getFields().put("content", FieldUtil.createHtmlField("someValue"));
restNode = call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request, parameters));
assertThat(restNode).hasVersion("1.2");
}
}
@Test
public void testConflictDetection() {
try (Tx trx = tx()) {
// Invoke an initial update on the node - Update Version 1.0 teaser -> 1.1
HibNode node = getTestNode();
NodeUpdateRequest request1 = prepareNameFieldUpdateRequest("1234", "1.0");
NodeParametersImpl parameters = new NodeParametersImpl();
parameters.setLanguages("en", "de");
NodeResponse restNode = call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request1, parameters));
assertThat(restNode).hasVersion("1.1");
// Invoke another update which just changes the title field - Update Title 1.1 -> 1.2
NodeUpdateRequest request2 = prepareNameFieldUpdateRequest("1234", "1.1");
request2.getFields().put("title", FieldUtil.createStringField("updatedTitle"));
restNode = call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request2, parameters));
assertThat(restNode).hasVersion("1.2");
// Update the node and change the name field. Base the update on 1.0 thus a conflict check must be performed. A conflict should be detected.
NodeUpdateRequest request3 = prepareNameFieldUpdateRequest("1234", "1.0");
request3.getFields().put("teaser", FieldUtil.createStringField("updatedField"));
Throwable error = null;
try {
client().updateNode(PROJECT_NAME, node.getUuid(), request3, parameters).blockingGet();
fail("The node update should fail with a conflict error");
} catch (RuntimeException e) {
error = e.getCause();
}
assertThat(error).isNotNull().isInstanceOf(MeshRestClientMessageException.class);
MeshRestClientMessageException conflictException = ((MeshRestClientMessageException) error);
assertThat((List) conflictException.getResponseMessage().getProperty("conflicts")).hasSize(1).containsExactly("teaser");
assertThat(conflictException.getStatusCode()).isEqualTo(CONFLICT.code());
assertThat(conflictException.getMessage()).isEqualTo("Error:409 in POST " + CURRENT_API_BASE_PATH + "/dummy/nodes/" + node.getUuid()
+ "?lang=en,de : Conflict Info: " + I18NUtil.get(Locale.ENGLISH, "node_error_conflict_detected"));
assertThat(conflictException.getResponseMessage().getProperty("oldVersion")).isEqualTo("1.0");
assertThat(conflictException.getResponseMessage().getProperty("newVersion")).isEqualTo("1.2");
}
}
/**
* Update a node and verify that only modified fields are bound to the new node version. Other fields should be referenced from the previous node version.
*/
@Test
public void testDeduplicationDuringUpdate() {
disableAutoPurge();
try (Tx tx = tx()) {
ContentDao contentDao = tx.contentDao();
updateSchema();
HibNodeFieldContainer origContainer = contentDao.getLatestDraftFieldContainer(getTestNode(), english());
assertEquals("Concorde_english_name", origContainer.getString("teaser").getString());
assertEquals("Concorde english title", origContainer.getString("title").getString());
tx.success();
}
// First request - Update 1.0 and add basic fields and complex fields -> 1.1
initialRequest();
// Second request - Modify referenced elements (stringList, micronode) (1.1 -> 1.2)
NodeUpdateRequest request = modifingRequest();
// Third request - Update the node again and don't change anything (1.2 -> 1.2)
repeatRequest(request);
// Fourth request - Remove referenced elements (stringList, micronode)
deletingRequest();
}
private void initialRequest() {
HibNode node = getTestNode();
String nodeUuid = tx(() -> node.getUuid());
HibNodeFieldContainer oldContainer = tx(() -> boot().contentDao().findVersion(node, "en", project().getLatestBranch().getUuid(), "1.0"));
NodeUpdateRequest request = prepareNameFieldUpdateRequest("1234", "1.0");
// Add micronode / string list
request.getFields().put("stringList", FieldUtil.createStringListField("a", "b", "c"));
request.getFields().put("micronode", FieldUtil.createMicronodeField("vcard", Tuple.tuple("firstName", FieldUtil.createStringField(
"test-firstname")), Tuple.tuple("lastName", FieldUtil.createStringField("test-lastname"))));
NodeParametersImpl parameters = new NodeParametersImpl();
parameters.setLanguages("en", "de");
NodeResponse restNode = call(() -> client().updateNode(PROJECT_NAME, nodeUuid, request, parameters));
assertThat(restNode).hasVersion("1.1");
try (Tx tx = tx()) {
ContentDao contentDao = tx.contentDao();
assertNotNull("The old version should have a new version 1.1", contentDao.getNextVersions(oldContainer).iterator().next());
HibNodeFieldContainer newContainer = contentDao.findVersion(node, "en", project().getLatestBranch().getUuid(), "1.1");
assertEquals("The name field value of the old container version should not have been changed.", "Concorde_english_name", oldContainer
.getString("teaser").getString());
assertEquals("The name field value of the new container version should contain the expected value.", "1234", newContainer.getString(
"teaser").getString());
assertNotNull("The new container should also contain the title since basic field types are not deduplicated", newContainer.getString(
"title"));
assertNotNull("The container for version 0.1 should contain the title value.", oldContainer.getString("title"));
}
}
private NodeUpdateRequest modifingRequest() {
try (Tx trx = tx()) {
HibNode node = getTestNode();
NodeParametersImpl parameters = new NodeParametersImpl();
parameters.setLanguages("en", "de");
NodeUpdateRequest request = prepareNameFieldUpdateRequest("1234", "1.1");
// Add micronode / string list - This time only change the order
request.getFields().put("stringList", FieldUtil.createStringListField("b", "c", "d"));
request.getFields().put("micronode", FieldUtil.createMicronodeField("vcard", Tuple.tuple("firstName", FieldUtil.createStringField(
"test-updated-firstname")), Tuple.tuple("lastName", FieldUtil.createStringField("test-updated-lastname"))));
NodeResponse restNode = call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request, parameters));
assertThat(restNode).hasVersion("1.2");
HibNodeFieldContainer createdVersion = trx.contentDao().findVersion(node, Arrays.asList("en"), project().getLatestBranch().getUuid(),
"1.2");
assertNotNull("The graph field container for version 1.2 could not be found.", createdVersion);
return request;
}
}
/**
* Assert that deduplication occurred correctly. The complex fields have not changed and should thus be referenced from the previous graph field container
* version.
*
* @param request
*/
private void repeatRequest(NodeUpdateRequest request) {
try (Tx trx = tx()) {
HibNode node = getTestNode();
NodeParametersImpl parameters = new NodeParametersImpl();
parameters.setLanguages("en", "de");
// Add another field to the request in order to invoke an update. Otherwise no update would occure and no 1.3 would be created.
request.getFields().put("content", FieldUtil.createHtmlField("changed"));
NodeResponse restNode = call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request, parameters));
assertThat(restNode).hasVersion("1.3");
}
try (Tx trx = tx()) {
HibNode node = getTestNode();
HibNodeFieldContainer createdVersion = trx.contentDao().findVersion(node, Arrays.asList("en"), project().getLatestBranch().getUuid(),
"1.3");
assertNotNull("The graph field container for version 1.3 could not be found.", createdVersion);
HibNodeFieldContainer previousVersion = createdVersion.getPreviousVersion();
assertNotNull("The graph field container for version 1.2 could not be found.", previousVersion);
assertEquals("The previous version of 1.3 should be 1.2", "1.2", previousVersion.getVersion().toString());
HibMicronodeField previousMicronode = previousVersion.getMicronode("micronode");
HibMicronodeField nextMicronode = createdVersion.getMicronode("micronode");
assertNotNull("Could not find the field within the previous version.", previousMicronode);
assertNotNull("Could not find the expected field in the created version.", nextMicronode);
assertEquals("Both fields should have the same uuid since both are referenced by the both versions.", nextMicronode.getMicronode()
.getUuid(), previousMicronode.getMicronode().getUuid());
HibStringFieldList previousStringList = previousVersion.getStringList("stringList");
HibStringFieldList nextStringList = createdVersion.getStringList("stringList");
assertNotNull("Could not find the field within the previous version.", previousStringList);
assertNotNull("Could not find the expected field in the created version.", nextStringList);
assertEquals("Both fields should have the same uuid since both are referenced by the both versions.", nextStringList.getUuid(),
previousStringList.getUuid());
}
}
private void deletingRequest() {
try (Tx trx = tx()) {
HibNode node = getTestNode();
NodeParametersImpl parameters = new NodeParametersImpl();
parameters.setLanguages("en", "de");
NodeUpdateRequest request4 = prepareNameFieldUpdateRequest("1234", "1.2");
request4.getFields().put("micronode", null);
request4.getFields().put("stringList", null);
NodeResponse restNode4 = call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request4, parameters));
assertThat(restNode4).hasVersion("1.4");
}
try (Tx trx = tx()) {
HibNode node = getTestNode();
HibNodeFieldContainer createdVersion = trx.contentDao().findVersion(node, "en", project().getLatestBranch().getUuid(), "1.4");
assertNotNull("The graph field container for version 0.5 could not be found.", createdVersion);
assertNull("The micronode should not exist in this version since we explicitly removed it.", createdVersion.getMicronode("micronode"));
assertNull("The string list should not exist in this version since we explicitly removed it via a null update request.", createdVersion
.getStringList("stringList"));
}
}
private void updateSchema() {
HibNode node = getTestNode();
ListFieldSchema stringListFieldSchema = new ListFieldSchemaImpl();
stringListFieldSchema.setName("stringList");
stringListFieldSchema.setListType("string");
MicronodeFieldSchema micronodeFieldSchema = new MicronodeFieldSchemaImpl();
micronodeFieldSchema.setName("micronode");
micronodeFieldSchema.setAllowedMicroSchemas("vcard");
// Add the field schemas to the schema
SchemaVersionModel schema = node.getSchemaContainer().getLatestVersion().getSchema();
schema.addField(stringListFieldSchema);
schema.addField(micronodeFieldSchema);
node.getSchemaContainer().getLatestVersion().setSchema(schema);
mesh().serverSchemaStorage().addSchema(schema);
}
/**
* Test whether a conflict with a micronode update is correctly detected and shown.
*/
@Test
public void testConflictInMicronode() {
disableAutoPurge();
try (Tx tx = tx()) {
ContentDao contentDao = tx.contentDao();
updateSchema();
HibNodeFieldContainer origContainer = contentDao.getLatestDraftFieldContainer(getTestNode(), english());
assertEquals("Concorde_english_name", origContainer.getString("teaser").getString());
assertEquals("Concorde english title", origContainer.getString("title").getString());
tx.success();
}
// First request - Update 1.0 and add basic fields and complex fields
initialRequest();
// Modify 1.1 and update micronode
HibNode node = getTestNode();
try (Tx tx = tx()) {
NodeParametersImpl parameters = new NodeParametersImpl();
parameters.setLanguages("en", "de");
NodeUpdateRequest request = prepareNameFieldUpdateRequest("1234", "1.1");
// Add micronode / string list - This time only change the order
request.getFields().put("stringList", FieldUtil.createStringListField("b", "c", "d"));
request.getFields().put("micronode", FieldUtil.createMicronodeField("vcard", Tuple.tuple("firstName", FieldUtil.createStringField(
"test-updated-firstname")), Tuple.tuple("lastName", FieldUtil.createStringField("test-updated-lastname"))));
NodeResponse restNode = call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request, parameters));
assertThat(restNode).hasVersion("1.2");
HibNodeFieldContainer createdVersion = tx.contentDao().findVersion(node, Arrays.asList("en"), project().getLatestBranch().getUuid(),
"1.2");
assertNotNull("The graph field container for version 0.3 could not be found.", createdVersion);
}
// Another update request based on 1.1 which also updates the micronode - A conflict should be detected
try (Tx tx = tx()) {
NodeParametersImpl parameters = new NodeParametersImpl();
parameters.setLanguages("en", "de");
NodeUpdateRequest request = prepareNameFieldUpdateRequest("1234", "1.1");
// Add micronode / string list - This time only change the order
request.getFields().put("stringList", FieldUtil.createStringListField("b", "c", "d"));
request.getFields().put("micronode", FieldUtil.createMicronodeField("vcard", Tuple.tuple("firstName", FieldUtil.createStringField(
"test-updated-firstname")), Tuple.tuple("lastName", FieldUtil.createStringField("test-updated-lastname-also-modified"))));
Throwable error = null;
try {
client().updateNode(PROJECT_NAME, node.getUuid(), request, parameters).blockingGet();
fail("The node update should fail with a conflict error");
} catch (RuntimeException e) {
error = e.getCause();
}
assertThat(error).isNotNull().isInstanceOf(MeshRestClientMessageException.class);
MeshRestClientMessageException conflictException = ((MeshRestClientMessageException) error);
assertThat(((List) conflictException.getResponseMessage().getProperty("conflicts"))).hasSize(2).containsExactly("micronode.firstName",
"micronode.lastName");
assertThat(conflictException.getStatusCode()).isEqualTo(CONFLICT.code());
assertThat(conflictException.getMessage()).isEqualTo("Error:409 in POST " + CURRENT_API_BASE_PATH + "/dummy/nodes/" + node.getUuid()
+ "?lang=en,de : Conflict Info: " + I18NUtil.get(Locale.ENGLISH, "node_error_conflict_detected"));
assertThat(conflictException.getResponseMessage().getProperty("oldVersion")).isEqualTo("1.1");
assertThat(conflictException.getResponseMessage().getProperty("newVersion")).isEqualTo("1.2");
}
}
@Test
public void testBogusVersionNumber() {
try (Tx trx = tx()) {
HibNode node = getTestNode();
NodeUpdateRequest request = prepareNameFieldUpdateRequest("1234", "42.1");
NodeParametersImpl parameters = new NodeParametersImpl();
parameters.setLanguages("en", "de");
call(() -> client().updateNode(PROJECT_NAME, node.getUuid(), request, parameters), BAD_REQUEST, "node_error_draft_not_found", "42.1",
"en");
}
}
}
| apache-2.0 |
jodzga/metrowka | src/main/java/com/linkedin/metrowka/Metrowka.java | 2513 | package com.linkedin.metrowka;
import java.util.Date;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Metrowka {
private static final Logger _logger = LoggerFactory.getLogger(Metrowka.class);
private static final ThreadFactory _threadFactory = new ThreadFactory() {
private final AtomicInteger _poolNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "reaper-" + _poolNumber.getAndIncrement());
}
};
private final AtomicBoolean _started = new AtomicBoolean(false);
private final AtomicBoolean stopped = new AtomicBoolean(false);
private final long _harvestPeriodMs;
private final ScheduledExecutorService _scheduler =
Executors.newSingleThreadScheduledExecutor(_threadFactory);
private final ConcurrentHashMap<Harvestable, Harvester> _harvesters = new ConcurrentHashMap<>();
public Metrowka(long harvestPeriodMs) {
_harvestPeriodMs = harvestPeriodMs;
}
public Harvester register(Harvestable harvestable, Harvester harvester) {
return _harvesters.put(harvestable, harvester);
}
public void start() {
if (_started.compareAndSet(false, true)) {
long currentMs = System.currentTimeMillis();
long msUntilNextPeriod = _harvestPeriodMs - currentMs % _harvestPeriodMs;
_logger.info("scheduled reaper to start at " + new Date(currentMs + msUntilNextPeriod));
_scheduler.scheduleAtFixedRate(this::harvest, msUntilNextPeriod, _harvestPeriodMs, TimeUnit.MILLISECONDS);
} else {
_logger.warn("reaper already started");
}
}
public void stop() {
if (!_started.get()) {
_logger.warn("asked to stop reaper that has not been started");
} else {
if (stopped.compareAndSet(false, true)) {
_scheduler.shutdownNow();
} else {
_logger.warn("reaper already stopped");
}
}
}
private void harvest() {
for (Entry<Harvestable, Harvester> entry: _harvesters.entrySet()) {
try {
entry.getKey().harvest(entry.getValue());
} catch (Exception e) {
_logger.error("failed to harvest histogram", e);
}
}
}
}
| apache-2.0 |
jfdenise/aesh | aesh/src/test/java/org/aesh/command/AeshCommandResultHandlerTest.java | 4985 | /*
* JBoss, Home of Professional Open Source
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.aesh.command;
import org.aesh.command.activator.CommandActivator;
import org.aesh.command.activator.OptionActivator;
import org.aesh.command.completer.CompleterInvocation;
import org.aesh.command.converter.ConverterInvocation;
import org.aesh.command.option.Arguments;
import org.aesh.command.option.Option;
import org.aesh.command.registry.CommandRegistryException;
import org.aesh.command.result.ResultHandler;
import org.aesh.command.invocation.CommandInvocation;
import org.aesh.command.impl.registry.AeshCommandRegistryBuilder;
import org.aesh.command.registry.CommandRegistry;
import org.aesh.command.settings.Settings;
import org.aesh.command.settings.SettingsBuilder;
import org.aesh.command.validator.ValidatorInvocation;
import org.aesh.readline.ReadlineConsole;
import org.aesh.tty.TestConnection;
import org.aesh.utils.Config;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a>
*/
public class AeshCommandResultHandlerTest {
@Test
public void testResultHandler() throws IOException, InterruptedException, CommandRegistryException {
TestConnection connection = new TestConnection();
CommandRegistry registry = AeshCommandRegistryBuilder.builder()
.command(FooCommand.class)
.create();
Settings<CommandInvocation, ConverterInvocation, CompleterInvocation, ValidatorInvocation,
OptionActivator, CommandActivator> settings =
SettingsBuilder.builder()
.commandRegistry(registry)
.connection(connection)
.logging(true)
.build();
ReadlineConsole console = new ReadlineConsole(settings);
console.start();
connection.read("foo --foo 1 --name aesh"+ Config.getLineSeparator());
//outputStream.flush();
Thread.sleep(80);
connection.read("foo --foo 1"+ Config.getLineSeparator());
//outputStream.flush();
Thread.sleep(80);
connection.read("foo --fo 1 --name aesh"+ Config.getLineSeparator());
//outputStream.flush();
Thread.sleep(80);
connection.read("foo --foo 1 --exception" + Config.getLineSeparator());
//outputStream.flush();
Thread.sleep(80);
}
@CommandDefinition(name = "foo", description = "", resultHandler = FooResultHandler.class)
public static class FooCommand implements Command {
@Option(required = true)
private String foo;
@Option
private String name;
@Option(hasValue = false)
private boolean exception;
@Arguments
private List<String> arguments;
@Override
public CommandResult execute(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
if (name == null) {
if (exception) {
throw new CommandException("Exception occured, please fix options");
} else {
return CommandResult.FAILURE;
}
} else
return CommandResult.SUCCESS;
}
public String getName() {
return name;
}
}
public static class FooResultHandler implements ResultHandler {
private transient int resultCounter = 0;
@Override
public void onSuccess() {
assertEquals(0, resultCounter);
resultCounter++;
}
@Override
public void onFailure(CommandResult result) {
assertEquals(1, resultCounter);
resultCounter++;
}
@Override
public void onValidationFailure(CommandResult result, Exception exception) {
assertEquals(2, resultCounter);
resultCounter++;
}
@Override
public void onExecutionFailure(CommandResult result, CommandException exception) {
assertEquals(3, resultCounter);
}
}
}
| apache-2.0 |
rostam/gradoop | gradoop-data-integration/src/main/java/org/gradoop/dataintegration/transformation/impl/functions/package-info.java | 780 | /*
* Copyright © 2014 - 2019 Leipzig University (Database Research Group)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This package contains functions used for graph transformations.
*/
package org.gradoop.dataintegration.transformation.impl.functions;
| apache-2.0 |
infinitiessoft/keystone4j | keystone4j-client/src/main/java/com/infinities/keystone4j/middleware/model/AccessInfo.java | 4148 | /*******************************************************************************
* Copyright 2015 InfinitiesSoft Solutions 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.infinities.keystone4j.middleware.model;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.common.base.Strings;
import com.infinities.keystone4j.middleware.model.v3.AccessInfoV3;
import com.infinities.keystone4j.middleware.model.v3.wrapper.TokenV3Wrapper;
import com.infinities.keystone4j.middleware.model.wrapper.AccessWrapper;
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class AccessInfo {
public final static int STALE_TOKEN_DURATION = 30;
protected ServiceCatalog serviceCatalog;
// protected AccessInfo() {
// this.serviceCatalog = ServiceCatalog.build(this, null,
// this.getRegionName());
// }
public abstract String getRegionName();
public boolean willExpireSoon(int staleDuration) {
if (staleDuration == 0) {
staleDuration = STALE_TOKEN_DURATION;
}
Calendar soon = Calendar.getInstance();
soon.add(Calendar.SECOND, staleDuration);
return soon.after(this.getExpires());
}
public abstract boolean hasServiceCatalog();
public abstract String getAuthToken();
public abstract Calendar getExpires();
public abstract Calendar getIssued();
public abstract String getUsername();
public abstract String getUserId();
public abstract String getUserDomainId();
public abstract String getUserDomainName();
public abstract List<String> getRoleIds();
public abstract List<String> getRoleNames();
public abstract String getDomainName();
public abstract String getDomainId();
public abstract String getProjectName();
public String getTenantName() {
return getProjectName();
}
public abstract boolean isScoped();
public abstract boolean isProjectScoped();
public abstract boolean isDomainScoped();
public abstract String getTrustId();
public abstract boolean isTrustScoped();
public abstract String getTrusteeUserId();
public abstract String getTrustorUserId();
public abstract String getProjectId();
public String getTenantId() {
return getProjectId();
}
public abstract String getProjectDomainId();
public abstract String getProjectDomainName();
public abstract List<URL> getAuthUrl() throws MalformedURLException;
public abstract String getVersion();
public abstract String getOauthAccessTokenId();
public abstract String getOauthConsumerId();
public static AccessInfo build(Response response, TokenWrapper body, String regionName) {
if (body != null) {
if (AccessInfoV3.isValid(body)) {
String tokenid = null;
if (response != null) {
tokenid = response.getHeaderString("X-Subject-Token");
}
com.infinities.keystone4j.middleware.model.v3.Token token = ((TokenV3Wrapper) body).getToken();
if (!Strings.isNullOrEmpty(regionName)) {
token.setRegionName(regionName);
}
return new AccessInfoV3(tokenid, token);
} else if (AccessInfoV2.isValid(body)) {
if (!Strings.isNullOrEmpty(regionName)) {
((AccessWrapper) body).getAccess().setRegionName(regionName);
}
return new AccessInfoV2(((AccessWrapper) body).getAccess());
} else {
throw new RuntimeException("Unrecognized auth response");
}
} else {
return new AccessInfoV2(null);
}
}
public ServiceCatalog getServiceCatalog() {
return serviceCatalog;
}
}
| apache-2.0 |
optivo-org/junit-benchmarks | src/main/java/com/carrotsearch/junitbenchmarks/h2/LabelType.java | 155 | package com.carrotsearch.junitbenchmarks.h2;
/**
* X-axis label type.
*/
public enum LabelType
{
RUN_ID,
CUSTOM_KEY,
TIMESTAMP
}
| apache-2.0 |
Schinzel/basic-utils | src/main/java/io/schinzel/basicutils/thrower/Thrower.java | 7905 | package io.schinzel.basicutils.thrower;
import io.schinzel.basicutils.Checker;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* The purpose of this class is to offer less verbose exception throwing in
* general and variable checking in particular.
*
* @author schinzel
*/
@SuppressWarnings({"WeakerAccess", "UnusedReturnValue"})
public class Thrower {
Thrower() {
}
/**
* @return An ThrowerInstance for chaining of Thrower methods.
*/
public static ThrowerInstance createInstance() {
return new ThrowerInstance();
}
/**
* @param string The string to validate
* @param variableName The name of the argument to validate
* @param regex The regex to match
* @return The argument string
*/
public static String throwIfNotMatchesRegex(String string, String variableName, Pattern regex) {
ThrowerMessage.create(!regex.matcher(string).matches())
.message("Argument '" + variableName + "' with value '" + string + "' does not match regex '" + regex.pattern() + "'");
return string;
}
/**
* Throws runtime exception if the argument value with the argument name is null.
*
* @param value The value to check
* @param variableName The name of the value to check
* @return The argument value checked
*/
public static Object throwIfVarNull(Object value, String variableName) {
ThrowerMessage.create(value == null).message(getErrorMessage(variableName, "null"));
return value;
}
/**
* Throws runtime exception if the argument value with the argument name is null or an empty string.
*
* @param value The value to check
* @param variableName The name of the value to check
* @return The argument value checked
*/
public static String throwIfVarEmpty(String value, String variableName) {
ThrowerMessage.create(Checker.isEmpty(value)).message(getErrorMessage(variableName, "empty"));
return value;
}
/**
* Throws runtime exception if the argument list with the argument name is null ot an empty list.
*
* @param <T> The type of the list
* @param value The value to check
* @param variableName The name of the value to check
* @return The argument value checked
*/
public static <T> List<T> throwIfVarEmpty(List<T> value, String variableName) {
ThrowerMessage.create(Checker.isEmpty(value)).message(getErrorMessage(variableName, "empty"));
return value;
}
/**
* Throws runtime exception if the argument value with the argument name is null or an empty map.
*
* @param <K> The type of the keys in the map
* @param <V> The type of the values in the map
* @param value The value to check
* @param variableName The name of the value to check
* @return The argument value checked
*/
public static <K, V> Map<K, V> throwIfVarEmpty(Map<K, V> value, String variableName) {
ThrowerMessage.create(Checker.isEmpty(value)).message(getErrorMessage(variableName, "empty"));
return value;
}
/**
* Throws a runtime exception if argument value is less than argument min.
*
* @param valueToCheck The value to check.
* @param variableName The name of the variable that holds the value to
* check. Used to create more useful exception message.
* @param min The min value the argument value should not be less than.
* @return The argument value checked
*/
public static int throwIfVarTooSmall(int valueToCheck, String variableName, int min) {
Thrower.throwIfTrue(valueToCheck < min)
.message("The value %1$d in variable '%2$s' is too small. Min value is %3$d.", valueToCheck, variableName, min);
return valueToCheck;
}
/**
* Throws a runtime exception if argument value is less than argument min.
*
* @param valueToCheck The value to check.
* @param variableName The name of the variable that holds the value to
* check. Used to create more useful exception message.
* @param max The max value the argument value should not be larger than.
* @return The argument value checked
*/
public static int throwIfVarTooLarge(int valueToCheck, String variableName, int max) {
Thrower.throwIfTrue(valueToCheck > max)
.message("The value %1$d in variable '%2$s' is too large. Max value is %3$d.", valueToCheck, variableName, max);
return valueToCheck;
}
/**
* Throws runtime exception if argument value is less than argument min or
* larger than argument max.
*
* @param valueToCheck The value to check
* @param variableName The name of the variable that holds the value to
* check. Used to create more useful exception message.
* @param min The minimum allowed value that the argument value can have
* @param max The maximum allowed value that the argument value can have
* @return The argument value checked
*/
public static int throwIfVarOutsideRange(int valueToCheck, String variableName, int min, int max) {
Thrower.throwIfTrue((max < min), "Error using method. Max cannot be smaller than min.");
Thrower.throwIfVarEmpty(variableName, "variable");
Thrower.throwIfVarTooSmall(valueToCheck, variableName, min);
Thrower.throwIfVarTooLarge(valueToCheck, variableName, max);
return valueToCheck;
}
/**
* Throw runtime exception if argument expression is false.
*
* @param expression The expression to check
* @param message The exception message
*/
public static void throwIfFalse(boolean expression, String message) {
Thrower.throwIfFalse(expression).message(message);
}
/**
* Throw if argument expression is false.
*
* @param expression The expression to check
* @return Thrower message for chaining the exception message.
*/
public static ThrowerMessage throwIfFalse(boolean expression) {
return ThrowerMessage.create(!expression);
}
/**
* Throw if argument expression is true.
*
* @param expression The boolean expression to evaluate.
* @param message The exception message
*/
public static void throwIfTrue(boolean expression, String message) {
throwIfFalse(!expression, message);
}
/**
* Throw if argument expression is true.
*
* @param expression The expression to check
* @return Thrower message for chaining the exception message.
*/
public static ThrowerMessage throwIfTrue(boolean expression) {
return ThrowerMessage.create(expression);
}
/**
* Throw if argument expression is true.
*
* @param object The object to check for null
* @return Thrower message for chaining the exception message.
*/
public static ThrowerMessage throwIfNull(Object object) {
return ThrowerMessage.create(object == null);
}
/**
* Throw if argument object is null.
*
* @param object The object to check for null
* @param message The exception message
*/
public static void throwIfNull(Object object, String message) {
Thrower.throwIfNull(object).message(message);
}
/**
* @param variableName Name of variable to include in returned message
* @param state The state of the argument variable. E.g. "null" or "empty"
* @return Error message prefix
*/
static String getErrorMessage(String variableName, String state) {
return "Argument '" + variableName + "' cannot be " + state;
}
}
| apache-2.0 |
IHTSDO/snow-owl | dependencies/org.eclipse.net4j/src/org/eclipse/net4j/acceptor/IAcceptor.java | 2480 | /*
* Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.net4j.acceptor;
import org.eclipse.net4j.ILocationAware.Location;
import org.eclipse.net4j.connector.IConnector;
import org.eclipse.net4j.util.collection.Closeable;
import org.eclipse.net4j.util.container.IContainer;
import org.eclipse.spi.net4j.Acceptor;
/**
* Accepts incoming connection requests from {@link Location#CLIENT client} {@link IConnector connectors} and creates
* the appropriate {@link Location#SERVER server} connectors.
* <p>
* Since the process of accepting connection requests is heavily dependent on the implementation of the respective
* connectors the only public API is introspection and notification.
* <p>
* This interface is <b>not</b> intended to be implemented by clients. Service providers <b>must</b> extend the abstract
* {@link Acceptor} class.
* <p>
* <dt><b>Class Diagram:</b></dt>
* <dd><img src="doc-files/IAcceptor-1.gif" title="Diagram Acceptors" border="0" usemap="#IAcceptor-1.gif"/></dd>
* <p>
* <MAP NAME="IAcceptor-1.gif"> <AREA SHAPE="RECT" COORDS="10,8,99,58" HREF="IAcceptor.html"> <AREA SHAPE="RECT"
* COORDS="289,8,378,58" HREF="../connector/IConnector.html"> </MAP>
* <p>
* <dt><b>Sequence Diagram:</b></dt>
* <dd><img src="doc-files/IAcceptor-2.gif" title="Connection Process" border="0" usemap="#IAcceptor-2.gif"/></dd>
* <p>
* <MAP NAME="IAcceptor-2.gif"> <AREA SHAPE="RECT" COORDS="146,136,265,165" HREF="IConnector.html"> <AREA SHAPE="RECT"
* COORDS="485,75,564,105" HREF="IAcceptor.html"> <AREA SHAPE="RECT" COORDS="296,325,414,355" HREF="IConnector.html">
* <AREA SHAPE="RECT" COORDS="64,426,444,506" HREF="ConnectorState.html#CONNECTING"> <AREA SHAPE="RECT"
* COORDS="64,516,444,596" HREF="ConnectorState.html#NEGOTIATING"> </MAP>
*
* @author Eike Stepper
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IAcceptor extends IContainer<IConnector>, Closeable
{
/**
* Returns an array of the connectors that have been accepted by this acceptor and not been closed since.
*/
public IConnector[] getAcceptedConnectors();
}
| apache-2.0 |
maheshika/charon | modules/charon-core/src/main/java/org/wso2/charon/core/extensions/TenantDTO.java | 1261 | /*
* Copyright (c) 2005-2010, 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.charon.core.extensions;
/**
* To represent a tenant created in SCIM service provider side.
*/
public interface TenantDTO {
public String getTenantAdminUserName();
public void setTenantAdminUserName(String tenantAdminUserName);
public String getTenantAdminPassword();
public void setTenantAdminPassword(String tenantAdminPassword);
public String getTenantDomain();
public void setTenantDomain(String tenantDomain);
public String getAuthenticationMechanism();
public void setAuthenticationMechanism(String authenticationMechanism);
}
| apache-2.0 |
parasoft-pl/jpf-core | main/src/main/java/gov/nasa/jpf/util/SparseIntVector.java | 10267 | /*
* Copyright (C) 2014, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The Java Pathfinder core (jpf-core) platform is 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 gov.nasa.jpf.util;
import java.util.Arrays;
import static java.lang.Integer.MIN_VALUE;
/**
* This has approximately the interface of IntVector but uses a hash table
* instead of an array. Also, does not require allocation with each add.
* Configurable default value.
*/
public class SparseIntVector implements Cloneable {
private static final boolean DEBUG = false;
static final double MAX_LOAD_WIPE = 0.6;
static final double MAX_LOAD_REHASH = 0.4;
static final int DEFAULT_POW = 10;
static final int DEFAULT_VAL = 0;
/**
* a simplistic snapshot implementation that stores set indices/values in order to save space
*/
public static class Snapshot {
private final int length;
private final int pow, mask, nextWipe, nextRehash;
private final int[] positions;
private final int[] indices;
private final int[] values;
Snapshot (SparseIntVector v){
int len = v.idxTable.length;
length = len;
pow = v.pow;
mask = v.mask;
nextWipe = v.nextWipe;
nextRehash = v.nextRehash;
int size = v.count;
positions = new int[size];
indices = new int[size];
values = new int[size];
int[] idxTable = v.idxTable;
int[] valTable = v.valTable;
int j=0;
for (int i=0; i<len; i++) {
if (idxTable[i] != MIN_VALUE) {
positions[j] = i;
indices[j] = idxTable[i];
values[j] = valTable[i];
j++;
}
}
}
void restore (SparseIntVector v) {
int size = indices.length;
v.count = size;
v.pow = pow;
v.mask = mask;
v.nextWipe = nextWipe;
v.nextRehash = nextRehash;
int len = length;
int[] idxTable = new int[len];
int[] valTable = new int[len];
Arrays.fill(idxTable, MIN_VALUE);
for (int i=0; i<size; i++) {
int j = positions[i];
idxTable[j] = indices[i];
valTable[j] = values[i];
}
v.idxTable = idxTable;
v.valTable = valTable;
}
}
int[] idxTable; // MIN_VALUE => unoccupied
int[] valTable; // can be bound to null
int count;
int pow;
int mask;
int nextWipe;
int nextRehash;
int defaultValue;
/**
* Creates a SimplePool that holds about 716 elements before first
* rehash.
*/
public SparseIntVector() {
this(DEFAULT_POW,DEFAULT_VAL);
}
/**
* Creates a SimplePool that holds about 0.7 * 2**pow elements before
* first rehash.
*/
public SparseIntVector(int pow, int defValue) {
this.pow = pow;
newTable();
count = 0;
mask = valTable.length - 1;
nextWipe = (int)(MAX_LOAD_WIPE * mask);
nextRehash = (int)(MAX_LOAD_REHASH * mask);
defaultValue = defValue;
}
// INTERNAL //
@SuppressWarnings("unchecked")
protected void newTable() {
valTable = new int[1 << pow];
idxTable = new int[1 << pow];
if (defaultValue != 0) {
Arrays.fill(valTable, defaultValue);
}
Arrays.fill(idxTable, MIN_VALUE);
}
protected int mix(int x) {
int y = 0x9e3779b9;
x ^= 0x510fb60d;
y += (x >> 8) + (x << 3);
x ^= (y >> 5) + (y << 2);
return y - x;
}
// ********************* Public API ******************** //
public Snapshot getSnapshot() {
return new Snapshot(this);
}
public void restore (Snapshot snap) {
snap.restore(this);
}
@Override
public SparseIntVector clone() {
try {
SparseIntVector o = (SparseIntVector) super.clone();
o.idxTable = idxTable.clone();
o.valTable = valTable.clone();
return o;
} catch (CloneNotSupportedException cnsx) {
// can't happen
return null;
}
}
public int size() {
return count;
}
public void clear() {
Arrays.fill(valTable, defaultValue);
Arrays.fill(idxTable, MIN_VALUE);
count = 0;
}
public void clear(int idx) {
int code = mix(idx);
int pos = code & mask;
int delta = (code >> (pow - 1)) | 1; // must be odd!
int oidx = pos;
for(;;) {
int tidx = idxTable[pos];
if (tidx == MIN_VALUE) {
return; // nothing to clear
}
if (tidx == idx) {
count--;
idxTable[pos] = MIN_VALUE;
valTable[pos] = defaultValue;
return;
}
pos = (pos + delta) & mask;
assert (pos != oidx); // should never wrap around
}
}
@SuppressWarnings("unchecked")
public int get(int idx) {
int code = mix(idx);
int pos = code & mask;
int delta = (code >> (pow - 1)) | 1; // must be odd!
int oidx = pos;
for(;;) {
int tidx = idxTable[pos];
if (tidx == MIN_VALUE) {
return defaultValue;
}
if (tidx == idx) {
return valTable[pos];
}
pos = (pos + delta) & mask;
assert (pos != oidx); // should never wrap around
}
}
// for debug only
int count() {
int count = 0;
for (int i = 0; i < idxTable.length; i++) {
if (idxTable[i] != MIN_VALUE /*&& valTable[i] != defaultValue*/) {
count++;
}
}
return count;
}
public void set(int idx, int val) {
int code = mix(idx);
int pos = code & mask;
int delta = (code >> (pow - 1)) | 1; // must be odd!
int oidx = pos;
for(;;) {
int tidx = idxTable[pos];
if (tidx == MIN_VALUE) {
break;
}
if (tidx == idx) {
valTable[pos] = val; // update
return; // and we're done
}
pos = (pos + delta) & mask;
assert (pos != oidx); // should never wrap around
}
// idx not in table; add it
if ((count+1) >= nextWipe) { // too full
if (count >= nextRehash) {
pow++;
}
/**
// determine if size needs to be increased or just wipe null blocks
int oldCount = count;
count = 0;
for (int i = 0; i < idxTable.length; i++) {
//if (idxTable[i] != MIN_VALUE && valTable[i] != defaultValue) {
if (idxTable[i] != MIN_VALUE) {
count++;
}
}
if (count >= nextRehash) {
pow++; // needs to be increased in size
if (DEBUG) {
System.out.println("Rehash to capacity: 2**" + pow);
}
} else {
if (DEBUG) {
System.out.println("Rehash reclaiming this many nulls: " + (oldCount - count));
}
}
**/
int[] oldValTable = valTable;
int[] oldIdxTable = idxTable;
newTable();
mask = idxTable.length - 1;
nextWipe = (int)(MAX_LOAD_WIPE * mask);
nextRehash = (int)(MAX_LOAD_REHASH * mask);
int oldLen = oldIdxTable.length;
for (int i = 0; i < oldLen; i++) {
int tidx = oldIdxTable[i];
if (tidx == MIN_VALUE) continue;
int o = oldValTable[i];
//if (o == defaultValue) continue;
// otherwise:
code = mix(tidx);
pos = code & mask;
delta = (code >> (pow - 1)) | 1; // must be odd!
while (idxTable[pos] != MIN_VALUE) { // we know enough slots exist
pos = (pos + delta) & mask;
}
idxTable[pos] = tidx;
valTable[pos] = o;
}
// done with rehash; now get idx to empty slot
code = mix(idx);
pos = code & mask;
delta = (code >> (pow - 1)) | 1; // must be odd!
while (idxTable[pos] != MIN_VALUE) { // we know enough slots exist
pos = (pos + delta) & mask;
}
} else {
// pos already pointing to empty slot
}
count++;
idxTable[pos] = idx;
valTable[pos] = val;
}
public void setRange (int fromIndex, int toIndex, int val) {
for (int i=fromIndex; i<toIndex; i++) {
set(i, val);
}
}
// ************************** Test main ************************ //
public static void main(String[] args) {
SparseIntVector vect = new SparseIntVector(3, MIN_VALUE);
// add some
for (int i = -4200; i < 4200; i += 10) {
vect.set(i, i);
}
// check for added & non-added
for (int i = -4200; i < 4200; i += 10) {
int v = vect.get(i);
if (v != i) {
throw new IllegalStateException();
}
}
for (int i = -4205; i < 4200; i += 10) {
int v = vect.get(i);
if (v != MIN_VALUE) {
throw new IllegalStateException();
}
}
// add some more
for (int i = -4201; i < 4200; i += 10) {
vect.set(i, i);
}
// check all added
for (int i = -4200; i < 4200; i += 10) {
int v = vect.get(i);
if (v != i) {
throw new IllegalStateException();
}
}
for (int i = -4201; i < 4200; i += 10) {
int v = vect.get(i);
if (v != i) {
throw new IllegalStateException();
}
}
// "remove" some
for (int i = -4200; i < 4200; i += 10) {
vect.set(i,MIN_VALUE);
}
// check for added & non-added
for (int i = -4201; i < 4200; i += 10) {
int v = vect.get(i);
if (v != i) {
throw new IllegalStateException();
}
}
for (int i = -4200; i < 4200; i += 10) {
int v = vect.get(i);
if (v != MIN_VALUE) {
throw new IllegalStateException();
}
}
// add even more
for (int i = -4203; i < 4200; i += 10) {
vect.set(i, i);
}
for (int i = -4204; i < 4200; i += 10) {
vect.set(i, i);
}
}
}
| apache-2.0 |
budioktaviyan/appium-sample | test/src/io/appium/java_client/pagefactory/ElementInterceptor.java | 784 | package io.appium.java_client.pagefactory;
import io.appium.java_client.MobileElement;
import java.lang.reflect.Method;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.pagefactory.ElementLocator;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* Intercepts requests to {@link MobileElement}
*
*/
class ElementInterceptor implements MethodInterceptor {
private final ElementLocator locator;
ElementInterceptor(ElementLocator locator) {
this.locator = locator;
}
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
WebElement realElement = locator.findElement();
return method.invoke(realElement, args);
}
}
| apache-2.0 |
YoungPeanut/YoungSamples | app/src/main/java/info/ipeanut/youngsamples/third/ownview/basepage/BasePageActivity.java | 1403 | package info.ipeanut.youngsamples.third.ownview.basepage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import info.ipeanut.youngsamples.R;
public class BasePageActivity extends AppCompatActivity {
List<BasePage> pages = new ArrayList<>();
NewsPage newsPage;
MinePage minePage;
FrameLayout container;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_page);
container = (FrameLayout) findViewById(R.id.container);
pages.clear();
}
public void onMe(View view){
Toast.makeText(BasePageActivity.this, "me", Toast.LENGTH_SHORT).show();
if (minePage == null){
minePage = new MinePage(this);
pages.add(minePage);
}
container.removeAllViews();
container.addView(minePage.getView());
}
public void onNews(View view){
Toast.makeText(BasePageActivity.this, "news", Toast.LENGTH_SHORT).show();
if (newsPage == null){
newsPage = new NewsPage(this);
pages.add(newsPage);
}
container.removeAllViews();
container.addView(newsPage.getView());
}
}
| apache-2.0 |
ppavlidis/Gemma | gemma-core/src/test/java/ubic/gemma/core/job/TaskUtilsTest.java | 1354 | /*
* The Gemma project
*
* Copyright (c) 2010 University of British Columbia
*
* 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 ubic.gemma.core.job;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import java.util.Collection;
import java.util.HashSet;
import static org.junit.Assert.assertTrue;
/**
* @author paul
*
*/
public class TaskUtilsTest {
/**
* Test method for {@link ubic.gemma.core.job.TaskUtils#generateTaskId()}.
*/
@Test
public final void testGenerateTaskId() {
Collection<String> seen = new HashSet<>();
for ( int i = 0; i < 1000; i++ ) {
String id = TaskUtils.generateTaskId();
assertTrue( StringUtils.isNotBlank( id ) );
assertTrue( !seen.contains( id ) );
seen.add( id );
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-cloudhsmv2/src/main/java/com/amazonaws/services/cloudhsmv2/model/UntagResourceRequest.java | 7486 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cloudhsmv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudhsmv2-2017-04-28/UntagResource" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UntagResourceRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The cluster identifier (ID) for the cluster whose tags you are removing. To find the cluster ID, use
* <a>DescribeClusters</a>.
* </p>
*/
private String resourceId;
/**
* <p>
* A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag values.
* </p>
*/
private java.util.List<String> tagKeyList;
/**
* <p>
* The cluster identifier (ID) for the cluster whose tags you are removing. To find the cluster ID, use
* <a>DescribeClusters</a>.
* </p>
*
* @param resourceId
* The cluster identifier (ID) for the cluster whose tags you are removing. To find the cluster ID, use
* <a>DescribeClusters</a>.
*/
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
/**
* <p>
* The cluster identifier (ID) for the cluster whose tags you are removing. To find the cluster ID, use
* <a>DescribeClusters</a>.
* </p>
*
* @return The cluster identifier (ID) for the cluster whose tags you are removing. To find the cluster ID, use
* <a>DescribeClusters</a>.
*/
public String getResourceId() {
return this.resourceId;
}
/**
* <p>
* The cluster identifier (ID) for the cluster whose tags you are removing. To find the cluster ID, use
* <a>DescribeClusters</a>.
* </p>
*
* @param resourceId
* The cluster identifier (ID) for the cluster whose tags you are removing. To find the cluster ID, use
* <a>DescribeClusters</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UntagResourceRequest withResourceId(String resourceId) {
setResourceId(resourceId);
return this;
}
/**
* <p>
* A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag values.
* </p>
*
* @return A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag
* values.
*/
public java.util.List<String> getTagKeyList() {
return tagKeyList;
}
/**
* <p>
* A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag values.
* </p>
*
* @param tagKeyList
* A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag
* values.
*/
public void setTagKeyList(java.util.Collection<String> tagKeyList) {
if (tagKeyList == null) {
this.tagKeyList = null;
return;
}
this.tagKeyList = new java.util.ArrayList<String>(tagKeyList);
}
/**
* <p>
* A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag values.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTagKeyList(java.util.Collection)} or {@link #withTagKeyList(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param tagKeyList
* A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag
* values.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UntagResourceRequest withTagKeyList(String... tagKeyList) {
if (this.tagKeyList == null) {
setTagKeyList(new java.util.ArrayList<String>(tagKeyList.length));
}
for (String ele : tagKeyList) {
this.tagKeyList.add(ele);
}
return this;
}
/**
* <p>
* A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag values.
* </p>
*
* @param tagKeyList
* A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag
* values.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UntagResourceRequest withTagKeyList(java.util.Collection<String> tagKeyList) {
setTagKeyList(tagKeyList);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getResourceId() != null)
sb.append("ResourceId: ").append(getResourceId()).append(",");
if (getTagKeyList() != null)
sb.append("TagKeyList: ").append(getTagKeyList());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UntagResourceRequest == false)
return false;
UntagResourceRequest other = (UntagResourceRequest) obj;
if (other.getResourceId() == null ^ this.getResourceId() == null)
return false;
if (other.getResourceId() != null && other.getResourceId().equals(this.getResourceId()) == false)
return false;
if (other.getTagKeyList() == null ^ this.getTagKeyList() == null)
return false;
if (other.getTagKeyList() != null && other.getTagKeyList().equals(this.getTagKeyList()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getResourceId() == null) ? 0 : getResourceId().hashCode());
hashCode = prime * hashCode + ((getTagKeyList() == null) ? 0 : getTagKeyList().hashCode());
return hashCode;
}
@Override
public UntagResourceRequest clone() {
return (UntagResourceRequest) super.clone();
}
}
| apache-2.0 |
ArloL/liquibase | liquibase-core/src/main/java/liquibase/datatype/DatabaseDataType.java | 1531 | package liquibase.datatype;
import liquibase.util.StringUtils;
public class DatabaseDataType {
private String type;
public DatabaseDataType(String type) {
this.type = type;
}
public void addAdditionalInformation(String additionalInformation) {
if (additionalInformation != null) {
this.type += " "+additionalInformation;
}
}
public DatabaseDataType(String name, Object... parameters) {
this.type = name;
String[] stringParams = new String[parameters.length];
if (parameters.length > 0) {
for (int i=0; i<parameters.length; i++){
if (parameters[i] == null) {
stringParams[i] = "NULL";
} else {
stringParams[i] = parameters[i].toString();
}
}
type += "("+ StringUtils.join(stringParams, ", ")+")";
}
}
/**
* Mainly for postgres, check if the column is a serial data type.
* @return Whether the type is serial
*/
public boolean isSerialDataType() {
return type.equalsIgnoreCase("serial") || type.equalsIgnoreCase("bigserial");
}
public String toSql() {
return toString();
}
@Override
public String toString() {
return type;
}
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
}
| apache-2.0 |
infinum/Android-prince-of-versions | prince-of-versions/src/main/java/co/infinum/princeofversions/Version.java | 966 | package co.infinum.princeofversions;
/**
* Provides information about specific version.
*/
public final class Version {
protected com.github.zafarkhaja.semver.Version version;
public Version(com.github.zafarkhaja.semver.Version version) {
this.version = version;
}
public boolean isGreaterThan(Version version) {
return this.version.greaterThan(version.version);
}
public boolean isGreaterThanOrEqualsTo(Version version) {
return this.version.greaterThanOrEqualTo(version.version);
}
public boolean isEqualsTo(Version version) {
return this.version.equals(version.version);
}
public boolean isLessThan(Version version) {
return this.version.lessThan(version.version);
}
public boolean isLessThanOrEqualsTo(Version version) {
return this.version.lessThanOrEqualTo(version.version);
}
public String value() {
return version.toString();
}
}
| apache-2.0 |
DashShen/codecraft | java/io/src/test/java/im/dashen/codecraft/java/io/FileToolTest.java | 458 | package im.dashen.codecraft.java.io;
import org.junit.Test;
import java.io.File;
import java.util.List;
import static org.junit.Assert.*;
public class FileToolTest {
@Test
public void testListLocalFiles() throws Exception {
List<File> files = FileTool.listFiles(".");
files.forEach(System.out::println);
}
@Test
public void testRecurseDirs() throws Exception {
System.out.println(FileTool.walk("."));
}
} | apache-2.0 |
joskarthic/chatsecure | src/info/guardianproject/otr/app/im/app/MessageView.java | 29337 | /*
* Copyright (C) 2008 Esmertec AG. Copyright (C) 2008 The Android Open Source
* Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package info.guardianproject.otr.app.im.app;
import info.guardianproject.emoji.EmojiManager;
import info.guardianproject.otr.app.im.R;
import info.guardianproject.otr.app.im.engine.Presence;
import info.guardianproject.otr.app.im.plugin.xmpp.XmppAddress;
import info.guardianproject.otr.app.im.provider.Imps;
import info.guardianproject.otr.app.im.ui.ImageViewActivity;
import info.guardianproject.otr.app.im.ui.LetterAvatar;
import info.guardianproject.otr.app.im.ui.RoundedAvatarDrawable;
import info.guardianproject.util.AudioPlayer;
import info.guardianproject.util.LinkifyHelper;
import info.guardianproject.util.LogCleaner;
import java.io.File;
import java.io.IOException;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.Browser;
import android.provider.MediaStore;
import android.support.v4.util.LruCache;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MessageView extends FrameLayout {
private static int sCacheSize = 512; // 1MiB
private static LruCache<String,Bitmap> mBitmapCache = new LruCache<String,Bitmap>(sCacheSize);
public enum DeliveryState {
NEUTRAL, DELIVERED, UNDELIVERED
}
public enum EncryptionState {
NONE, ENCRYPTED, ENCRYPTED_AND_VERIFIED
}
private CharSequence lastMessage = null;
private Context context;
private boolean linkify = false;
public MessageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
private ViewHolder mHolder = null;
private final static DateFormat MESSAGE_DATETIME_FORMAT = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
private final static DateFormat MESSAGE_TIME_FORMAT = SimpleDateFormat.getTimeInstance(DateFormat.SHORT);
private static final SimpleDateFormat FMT_SAME_DAY = new SimpleDateFormat("yyyyMMdd");
private final static Date DATE_NOW = new Date();
private final static char DELIVERED_SUCCESS = '\u2714';
private final static char DELIVERED_FAIL = '\u2718';
private final static String LOCK_CHAR = "Secure";
class ViewHolder
{
TextView mTextViewForMessages = (TextView) findViewById(R.id.message);
TextView mTextViewForTimestamp = (TextView) findViewById(R.id.messagets);
ImageView mAvatar = (ImageView) findViewById(R.id.avatar);
// View mStatusBlock = findViewById(R.id.status_block);
ImageView mMediaThumbnail = (ImageView) findViewById(R.id.media_thumbnail);
View mContainer = findViewById(R.id.message_container);
// save the media uri while the MediaScanner is creating the thumbnail
// if the holder was reused, the pair is broken
Uri mMediaUri = null;
ViewHolder() {
// disable built-in autoLink so we can add custom ones
mTextViewForMessages.setAutoLinkMask(0);
}
public void setOnClickListenerMediaThumbnail( final String mimeType, final Uri mediaUri ) {
mMediaThumbnail.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
onClickMediaIcon( mimeType, mediaUri );
}
});
mMediaThumbnail.setOnLongClickListener( new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
onLongClickMediaIcon( mimeType, mediaUri );
return false;
}
});
}
public void resetOnClickListenerMediaThumbnail() {
mMediaThumbnail.setOnClickListener( null );
}
long mTimeDiff = -1;
}
/**
* This trickery is needed in order to have clickable links that open things
* in a new {@code Task} rather than in ChatSecure's {@code Task.} Thanks to @commonsware
* https://stackoverflow.com/a/11417498
*
*/
class NewTaskUrlSpan extends ClickableSpan {
private String urlString;
NewTaskUrlSpan(String urlString) {
this.urlString = urlString;
}
@Override
public void onClick(View widget) {
Uri uri = Uri.parse(urlString);
Context context = widget.getContext();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
class URLSpanConverter implements LinkifyHelper.SpanConverter<URLSpan, ClickableSpan> {
@Override
public NewTaskUrlSpan convert(URLSpan span) {
return (new NewTaskUrlSpan(span.getURL()));
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mHolder = (ViewHolder)getTag();
if (mHolder == null)
{
mHolder = new ViewHolder();
setTag(mHolder);
}
}
public void setLinkify(boolean linkify) {
this.linkify = linkify;
}
public void setMessageBackground (Drawable d) {
mHolder.mContainer.setBackgroundDrawable(d);
}
public URLSpan[] getMessageLinks() {
return mHolder.mTextViewForMessages.getUrls();
}
public String getLastMessage () {
return lastMessage.toString();
}
public void bindIncomingMessage(int id, int messageType, String address, String nickname, final String mimeType, final String body, Date date, Markup smileyRes,
boolean scrolling, EncryptionState encryption, boolean showContact, int presenceStatus) {
mHolder = (ViewHolder)getTag();
mHolder.mTextViewForMessages.setVisibility(View.VISIBLE);
if (nickname == null)
nickname = address;
if (showContact && nickname != null)
{
lastMessage = nickname + ": " + formatMessage(body);
showAvatar(address,nickname,true,presenceStatus);
}
else
{
lastMessage = formatMessage(body);
showAvatar(address,nickname,true,presenceStatus);
mHolder.resetOnClickListenerMediaThumbnail();
if( mimeType != null ) {
mHolder.mTextViewForMessages.setVisibility(View.GONE);
mHolder.mMediaThumbnail.setVisibility(View.VISIBLE);
Uri mediaUri = Uri.parse( body ) ;
lastMessage = "";
showMediaThumbnail(mimeType, mediaUri, id, mHolder);
} else {
mHolder.mMediaThumbnail.setVisibility(View.GONE);
if (showContact)
{
String[] nickParts = nickname.split("/");
lastMessage = nickParts[nickParts.length-1] + ": " + formatMessage(body);
}
else
{
lastMessage = formatMessage(body);
}
}
}
if (lastMessage.length() > 0)
{
try {
SpannableString spannablecontent=new SpannableString(lastMessage);
EmojiManager.getInstance(getContext()).addEmoji(getContext(), spannablecontent);
mHolder.mTextViewForMessages.setText(spannablecontent);
} catch (IOException e) {
LogCleaner.error(ImApp.LOG_TAG, "error processing message", e);
}
}
else
{
mHolder.mTextViewForMessages.setText(lastMessage);
}
if (date != null)
{
CharSequence tsText = null;
if (isSameDay(date,DATE_NOW))
tsText = formatTimeStamp(date,messageType,MESSAGE_TIME_FORMAT, null, encryption);
else
tsText = formatTimeStamp(date,messageType,MESSAGE_DATETIME_FORMAT, null, encryption);
mHolder.mTextViewForTimestamp.setText(tsText);
mHolder.mTextViewForTimestamp.setVisibility(View.VISIBLE);
}
else
{
mHolder.mTextViewForTimestamp.setText("");
//mHolder.mTextViewForTimestamp.setVisibility(View.GONE);
}
if (linkify)
LinkifyHelper.addLinks(mHolder.mTextViewForMessages, new URLSpanConverter());
LinkifyHelper.addTorSafeLinks(mHolder.mTextViewForMessages);
}
private void showMediaThumbnail (String mimeType, Uri mediaUri, int id, ViewHolder holder)
{
/* Guess the MIME type in case we received a file that we can display or play*/
if (TextUtils.isEmpty(mimeType) || mimeType.startsWith("application")) {
String guessed = URLConnection.guessContentTypeFromName(mediaUri.toString());
if (!TextUtils.isEmpty(guessed)) {
if (TextUtils.equals(guessed, "video/3gpp"))
mimeType = "audio/3gpp";
else
mimeType = guessed;
}
}
holder.setOnClickListenerMediaThumbnail(mimeType, mediaUri);
holder.mMediaThumbnail.setVisibility(View.VISIBLE);
holder.mTextViewForMessages.setText(lastMessage);
holder.mTextViewForMessages.setVisibility(View.GONE);
if( mimeType.startsWith("image/") ) {
setImageThumbnail( getContext().getContentResolver(), id, holder, mediaUri );
holder.mMediaThumbnail.setBackgroundColor(Color.TRANSPARENT);
// holder.mMediaThumbnail.setBackgroundColor(Color.WHITE);
}
else if (mimeType.startsWith("audio"))
{
holder.mMediaThumbnail.setImageResource(R.drawable.media_audio_play);
holder.mMediaThumbnail.setBackgroundColor(Color.TRANSPARENT);
}
else
{
holder.mMediaThumbnail.setImageResource(R.drawable.ic_file); // generic file icon
}
holder.mContainer.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
private boolean isSameDay (Date date1, Date date2)
{
return FMT_SAME_DAY.format(date1).equals(FMT_SAME_DAY.format(date2));
}
protected String convertMediaUriToPath(Uri uri) {
String path = null;
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(uri, proj, null, null, null);
if (cursor != null && (!cursor.isClosed()))
{
if (cursor.isBeforeFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index);
}
cursor.close();
}
return path;
}
private MediaPlayer mMediaPlayer = null;
/**
* @param mimeType
* @param body
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void onClickMediaIcon(String mimeType, Uri mediaUri) {
if (ChatFileStore.isVfsUri(mediaUri)) {
if (mimeType.startsWith("image")) {
Intent intent = new Intent(context, ImageViewActivity.class);
intent.putExtra( ImageViewActivity.FILENAME, mediaUri.getPath());
context.startActivity(intent);
return;
}
if (mimeType.startsWith("audio")) {
new AudioPlayer(getContext(), mediaUri.getPath(), mimeType).play();
return;
}
return;
}
else
{
String body = convertMediaUriToPath(mediaUri);
if (body == null)
body = new File(mediaUri.getPath()).getAbsolutePath();
if (mimeType.startsWith("audio") || (body.endsWith("3gp")||body.endsWith("3gpp")||body.endsWith("amr")))
{
if (mMediaPlayer != null)
mMediaPlayer.release();
try
{
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(body);
mMediaPlayer.prepare();
mMediaPlayer.start();
return;
} catch (IOException e) {
Log.e(ImApp.LOG_TAG,"error playing audio: " + body,e);
}
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 11)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//set a general mime type not specific
intent.setDataAndType(Uri.parse( body ), mimeType);
Context context = getContext().getApplicationContext();
if (isIntentAvailable(context,intent))
{
context.startActivity(intent);
}
else
{
Toast.makeText(getContext(), R.string.there_is_no_viewer_available_for_this_file_format, Toast.LENGTH_LONG).show();
}
}
}
protected void onLongClickMediaIcon(final String mimeType, final Uri mediaUri) {
final java.io.File exportPath = ChatFileStore.exportPath(mimeType, mediaUri);
new AlertDialog.Builder(context)
.setTitle(context.getString(R.string.export_media))
.setMessage(context.getString(R.string.export_media_file_to, exportPath.getAbsolutePath()))
.setPositiveButton(R.string.export, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
try {
ChatFileStore.exportContent(mimeType, mediaUri, exportPath);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(exportPath));
shareIntent.setType(mimeType);
context.startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.export_media)));
} catch (IOException e) {
Toast.makeText(getContext(), "Export Failed " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return;
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
return;
}
})
.create().show();
}
public static boolean isIntentAvailable(Context context, Intent intent) {
final PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
/**
* @param contentResolver
* @param id
* @param aHolder
* @param mediaUri
*/
private void setImageThumbnail(final ContentResolver contentResolver, final int id, final ViewHolder aHolder, final Uri mediaUri) {
// pair this holder to the uri. if the holder is recycled, the pairing is broken
aHolder.mMediaUri = mediaUri;
// if a content uri - already scanned
setThumbnail(contentResolver, aHolder, mediaUri);
}
/**
* @param contentResolver
* @param aHolder
* @param uri
*/
private void setThumbnail(final ContentResolver contentResolver, final ViewHolder aHolder, final Uri uri) {
new AsyncTask<String, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(String... params) {
Bitmap result = mBitmapCache.get(uri.toString());
if (result == null)
return getThumbnail( contentResolver, uri );
else
return result;
}
@Override
protected void onPostExecute(Bitmap result) {
if (uri != null && result != null)
{
mBitmapCache.put(uri.toString(), result);
// confirm the holder is still paired to this uri
if( ! uri.equals( aHolder.mMediaUri ) ) {
return ;
}
// set the thumbnail
aHolder.mMediaThumbnail.setImageBitmap(result);
}
}
}.execute();
}
public final static int THUMBNAIL_SIZE_DEFAULT = 400;
public static Bitmap getThumbnail(ContentResolver cr, Uri uri) {
// Log.e( MessageView.class.getSimpleName(), "getThumbnail uri:" + uri);
if (ChatFileStore.isVfsUri(uri)) {
return ChatFileStore.getThumbnailVfs(uri, THUMBNAIL_SIZE_DEFAULT);
}
return getThumbnailFile(uri, THUMBNAIL_SIZE_DEFAULT);
}
public static Bitmap getThumbnailFile(Uri uri, int thumbnailSize) {
java.io.File image = new java.io.File(uri.getPath());
if (!image.exists())
{
image = new info.guardianproject.iocipher.File(uri.getPath());
if (!image.exists())
return null;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inInputShareable = true;
options.inPurgeable = true;
BitmapFactory.decodeFile(image.getPath(), options);
if ((options.outWidth == -1) || (options.outHeight == -1))
return null;
int originalSize = (options.outHeight > options.outWidth) ? options.outHeight
: options.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / thumbnailSize;
Bitmap scaledBitmap = BitmapFactory.decodeFile(image.getPath(), opts);
return scaledBitmap;
}
private String formatMessage (String body)
{
if (body != null)
return android.text.Html.fromHtml(body).toString();
else
return null;
}
public void bindOutgoingMessage(int id, int messageType, String address, final String mimeType, final String body, Date date, Markup smileyRes, boolean scrolling,
DeliveryState delivery, EncryptionState encryption) {
mHolder = (ViewHolder)getTag();
mHolder.mTextViewForMessages.setVisibility(View.VISIBLE);
mHolder.resetOnClickListenerMediaThumbnail();
if( mimeType != null ) {
lastMessage = "";
Uri mediaUri = Uri.parse( body ) ;
showMediaThumbnail(mimeType, mediaUri, id, mHolder);
mHolder.mTextViewForMessages.setVisibility(View.GONE);
mHolder.mMediaThumbnail.setVisibility(View.VISIBLE);
} else {
mHolder.mMediaThumbnail.setVisibility(View.GONE);
lastMessage = body;//formatMessage(body);
try {
SpannableString spannablecontent=new SpannableString(lastMessage);
EmojiManager.getInstance(getContext()).addEmoji(getContext(), spannablecontent);
mHolder.mTextViewForMessages.setText(spannablecontent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (date != null)
{
CharSequence tsText = null;
if (isSameDay(date,DATE_NOW))
tsText = formatTimeStamp(date,messageType, MESSAGE_TIME_FORMAT, delivery, encryption);
else
tsText = formatTimeStamp(date,messageType, MESSAGE_DATETIME_FORMAT, delivery, encryption);
mHolder.mTextViewForTimestamp.setText(tsText);
mHolder.mTextViewForTimestamp.setVisibility(View.VISIBLE);
}
else
{
mHolder.mTextViewForTimestamp.setText("");
}
if (linkify)
LinkifyHelper.addLinks(mHolder.mTextViewForMessages, new URLSpanConverter());
LinkifyHelper.addTorSafeLinks(mHolder.mTextViewForMessages);
}
private void showAvatar (String address, String nickname, boolean isLeft, int presenceStatus)
{
if (mHolder.mAvatar == null)
return;
mHolder.mAvatar.setVisibility(View.GONE);
if (address != null && isLeft)
{
RoundedAvatarDrawable avatar = null;
try { avatar = DatabaseUtils.getAvatarFromAddress(this.getContext().getContentResolver(),XmppAddress.stripResource(address), ImApp.DEFAULT_AVATAR_WIDTH,ImApp.DEFAULT_AVATAR_HEIGHT);}
catch (Exception e){}
if (avatar != null)
{
mHolder.mAvatar.setVisibility(View.VISIBLE);
mHolder.mAvatar.setImageDrawable(avatar);
setAvatarBorder(presenceStatus, avatar);
}
else
{
int color = getAvatarBorder(presenceStatus);
int padding = 16;
LetterAvatar lavatar = new LetterAvatar(getContext(), color, nickname.substring(0,1).toUpperCase(), padding);
mHolder.mAvatar.setVisibility(View.VISIBLE);
mHolder.mAvatar.setImageDrawable(lavatar);
}
}
}
public int getAvatarBorder(int status) {
switch (status) {
case Presence.AVAILABLE:
return (getResources().getColor(R.color.holo_green_light));
case Presence.IDLE:
return (getResources().getColor(R.color.holo_green_dark));
case Presence.AWAY:
return (getResources().getColor(R.color.holo_orange_light));
case Presence.DO_NOT_DISTURB:
return(getResources().getColor(R.color.holo_red_dark));
case Presence.OFFLINE:
return(getResources().getColor(R.color.holo_grey_dark));
default:
}
return Color.TRANSPARENT;
}
public void bindPresenceMessage(String contact, int type, boolean isGroupChat, boolean scrolling) {
mHolder = (ViewHolder)getTag();
CharSequence message = formatPresenceUpdates(contact, type, isGroupChat, scrolling);
mHolder.mTextViewForMessages.setText(message);
// mHolder.mTextViewForMessages.setTextColor(getResources().getColor(R.color.chat_msg_presence));
}
public void bindErrorMessage(int errCode) {
mHolder = (ViewHolder)getTag();
mHolder.mTextViewForMessages.setText(R.string.msg_sent_failed);
mHolder.mTextViewForMessages.setTextColor(getResources().getColor(R.color.error));
}
private SpannableString formatTimeStamp(Date date, int messageType, DateFormat format, MessageView.DeliveryState delivery, EncryptionState encryptionState) {
StringBuilder deliveryText = new StringBuilder();
deliveryText.append(format.format(date));
deliveryText.append(' ');
if (delivery != null)
{
//this is for delivery
if (delivery == DeliveryState.DELIVERED) {
deliveryText.append(DELIVERED_SUCCESS);
} else if (delivery == DeliveryState.UNDELIVERED) {
deliveryText.append(DELIVERED_FAIL);
}
}
if (messageType != Imps.MessageType.POSTPONED)
deliveryText.append(DELIVERED_SUCCESS);//this is for sent, so we know show 2 checks like WhatsApp!
SpannableString spanText = null;
if (encryptionState == EncryptionState.ENCRYPTED)
{
deliveryText.append('X');
spanText = new SpannableString(deliveryText.toString());
int len = spanText.length();
spanText.setSpan(new ImageSpan(getContext(), R.drawable.lock16), len-1,len,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
else if (encryptionState == EncryptionState.ENCRYPTED_AND_VERIFIED)
{
deliveryText.append('X');
spanText = new SpannableString(deliveryText.toString());
int len = spanText.length();
spanText.setSpan(new ImageSpan(getContext(), R.drawable.lock16), len-1,len,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
else
{
spanText = new SpannableString(deliveryText.toString());
int len = spanText.length();
}
// spanText.setSpan(new StyleSpan(Typeface.SANS_SERIF), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// spanText.setSpan(new RelativeSizeSpan(0.8f), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// spanText.setSpan(new ForegroundColorSpan(R.color.soft_grey),
// 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spanText;
}
private CharSequence formatPresenceUpdates(String contact, int type, boolean isGroupChat,
boolean scrolling) {
String body;
Resources resources =getResources();
switch (type) {
case Imps.MessageType.PRESENCE_AVAILABLE:
body = resources.getString(isGroupChat ? R.string.contact_joined
: R.string.contact_online, contact);
break;
case Imps.MessageType.PRESENCE_AWAY:
body = resources.getString(R.string.contact_away, contact);
break;
case Imps.MessageType.PRESENCE_DND:
body = resources.getString(R.string.contact_busy, contact);
break;
case Imps.MessageType.PRESENCE_UNAVAILABLE:
body = resources.getString(isGroupChat ? R.string.contact_left
: R.string.contact_offline, contact);
break;
default:
return null;
}
if (scrolling) {
return body;
} else {
SpannableString spanText = new SpannableString(body);
int len = spanText.length();
spanText.setSpan(new StyleSpan(Typeface.ITALIC), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanText.setSpan(new RelativeSizeSpan((float) 0.8), 0, len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spanText;
}
}
public void setAvatarBorder(int status, RoundedAvatarDrawable avatar) {
switch (status) {
case Presence.AVAILABLE:
avatar.setBorderColor(getResources().getColor(R.color.holo_green_light));
avatar.setAlpha(255);
break;
case Presence.IDLE:
avatar.setBorderColor(getResources().getColor(R.color.holo_green_dark));
avatar.setAlpha(255);
break;
case Presence.AWAY:
avatar.setBorderColor(getResources().getColor(R.color.holo_orange_light));
avatar.setAlpha(255);
break;
case Presence.DO_NOT_DISTURB:
avatar.setBorderColor(getResources().getColor(R.color.holo_red_dark));
avatar.setAlpha(255);
break;
case Presence.OFFLINE:
avatar.setBorderColor(getResources().getColor(R.color.holo_grey_light));
avatar.setAlpha(150);
break;
default:
}
}
}
| apache-2.0 |
lucafavatella/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java | 20473 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.ui.frame;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.EditorColorsAdapter;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.EditorFontType;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.changes.issueLinks.IssueLinkHtmlRenderer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.BrowserHyperlinkListener;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBLoadingPanel;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.util.NotNullProducer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcs.log.Hash;
import com.intellij.vcs.log.VcsFullCommitDetails;
import com.intellij.vcs.log.VcsRef;
import com.intellij.vcs.log.data.LoadingDetails;
import com.intellij.vcs.log.data.VcsLogDataManager;
import com.intellij.vcs.log.data.VisiblePack;
import com.intellij.vcs.log.ui.VcsLogColorManager;
import com.intellij.vcs.log.ui.render.VcsRefPainter;
import com.intellij.vcs.log.ui.tables.GraphTableModel;
import com.intellij.vcs.log.util.VcsUserUtil;
import net.miginfocom.swing.MigLayout;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.MatteBorder;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Document;
import javax.swing.text.Position;
import java.awt.*;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author Kirill Likhodedov
*/
class DetailsPanel extends JPanel implements ListSelectionListener {
private static final Logger LOG = Logger.getInstance("Vcs.Log");
private static final String STANDARD_LAYER = "Standard";
private static final String MESSAGE_LAYER = "Message";
@NotNull private final VcsLogDataManager myLogDataManager;
@NotNull private final VcsLogGraphTable myGraphTable;
@NotNull private final ReferencesPanel myReferencesPanel;
@NotNull private final DataPanel myCommitDetailsPanel;
@NotNull private final MessagePanel myMessagePanel;
@NotNull private final JScrollPane myScrollPane;
@NotNull private final JPanel myMainContentPanel;
@NotNull private final JBLoadingPanel myLoadingPanel;
@NotNull private final VcsLogColorManager myColorManager;
@NotNull private VisiblePack myDataPack;
@Nullable private VcsFullCommitDetails myCurrentCommitDetails;
DetailsPanel(@NotNull VcsLogDataManager logDataManager,
@NotNull VcsLogGraphTable graphTable,
@NotNull VcsLogColorManager colorManager,
@NotNull VisiblePack initialDataPack) {
myLogDataManager = logDataManager;
myGraphTable = graphTable;
myColorManager = colorManager;
myDataPack = initialDataPack;
myReferencesPanel = new ReferencesPanel(myColorManager);
myCommitDetailsPanel = new DataPanel(logDataManager.getProject(), logDataManager.isMultiRoot(), logDataManager);
myScrollPane = new JBScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
myScrollPane.getVerticalScrollBar().setUnitIncrement(8);
myMainContentPanel = new JPanel(new MigLayout("flowy, ins 0, hidemode 3, gapy 0")) {
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
if (myCommitDetailsPanel.isExpanded()) {
return size;
}
size.width = myScrollPane.getViewport().getWidth() - 5;
return size;
}
};
myMainContentPanel.setOpaque(false);
myScrollPane.setOpaque(false);
myScrollPane.getViewport().setOpaque(false);
myScrollPane.setViewportView(myMainContentPanel);
myScrollPane.setBorder(IdeBorderFactory.createEmptyBorder());
myScrollPane.setViewportBorder(IdeBorderFactory.createEmptyBorder());
myMainContentPanel.add(myReferencesPanel, "");
myMainContentPanel.add(myCommitDetailsPanel, "");
myLoadingPanel = new JBLoadingPanel(new BorderLayout(), logDataManager, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) {
@Override
public Color getBackground() {
return getDetailsBackground();
}
};
myLoadingPanel.add(myScrollPane);
myMessagePanel = new MessagePanel();
setLayout(new CardLayout());
add(myLoadingPanel, STANDARD_LAYER);
add(myMessagePanel, MESSAGE_LAYER);
showMessage("No commits selected");
}
@NotNull
public static String formatDateTime(long time) {
return " on " + DateFormatUtil.formatDate(time) + " at " + DateFormatUtil.formatTime(time);
}
@Override
public Color getBackground() {
return getDetailsBackground();
}
private static Color getDetailsBackground() {
return UIUtil.getTableBackground();
}
void updateDataPack(@NotNull VisiblePack dataPack) {
myDataPack = dataPack;
}
@Override
public void valueChanged(@Nullable ListSelectionEvent notUsed) {
if (notUsed != null && notUsed.getValueIsAdjusting()) return;
VcsFullCommitDetails newCommitDetails = null;
int[] rows = myGraphTable.getSelectedRows();
if (rows.length < 1) {
showMessage("No commits selected");
}
else if (rows.length > 1) {
showMessage("Several commits selected");
}
else {
((CardLayout)getLayout()).show(this, STANDARD_LAYER);
int row = rows[0];
GraphTableModel tableModel = myGraphTable.getModel();
VcsFullCommitDetails commitData = tableModel.getFullDetails(row);
if (commitData instanceof LoadingDetails) {
myLoadingPanel.startLoading();
myCommitDetailsPanel.setData(null);
myReferencesPanel.setReferences(Collections.<VcsRef>emptyList());
updateDetailsBorder(null);
}
else {
myLoadingPanel.stopLoading();
myCommitDetailsPanel.setData(commitData);
myReferencesPanel.setReferences(sortRefs(commitData.getId(), commitData.getRoot()));
updateDetailsBorder(commitData);
newCommitDetails = commitData;
}
List<String> branches = null;
if (!(commitData instanceof LoadingDetails)) {
branches = myLogDataManager.getContainingBranchesGetter().requestContainingBranches(commitData.getRoot(), commitData.getId());
}
myCommitDetailsPanel.setBranches(branches);
if (!Comparing.equal(myCurrentCommitDetails, newCommitDetails)) {
myCurrentCommitDetails = newCommitDetails;
myScrollPane.getVerticalScrollBar().setValue(0);
}
}
}
private void updateDetailsBorder(@Nullable VcsFullCommitDetails data) {
if (data == null || !myColorManager.isMultipleRoots()) {
myMainContentPanel.setBorder(BorderFactory.createEmptyBorder(VcsLogGraphTable.ROOT_INDICATOR_WHITE_WIDTH / 2,
VcsLogGraphTable.ROOT_INDICATOR_WHITE_WIDTH / 2, 0, 0));
}
else {
Color color = VcsLogGraphTable.getRootBackgroundColor(data.getRoot(), myColorManager);
myMainContentPanel.setBorder(new CompoundBorder(new MatteBorder(0, VcsLogGraphTable.ROOT_INDICATOR_COLORED_WIDTH, 0, 0, color),
new MatteBorder(VcsLogGraphTable.ROOT_INDICATOR_WHITE_WIDTH / 2,
VcsLogGraphTable.ROOT_INDICATOR_WHITE_WIDTH, 0, 0,
new JBColor(new NotNullProducer<Color>() {
@NotNull
@Override
public Color produce() {
return getDetailsBackground();
}
}))));
}
}
private void showMessage(String text) {
myLoadingPanel.stopLoading();
((CardLayout)getLayout()).show(this, MESSAGE_LAYER);
myMessagePanel.setText(text);
}
@NotNull
private List<VcsRef> sortRefs(@NotNull Hash hash, @NotNull VirtualFile root) {
Collection<VcsRef> refs = myDataPack.getRefs().refsToCommit(hash, root);
return ContainerUtil.sorted(refs, myLogDataManager.getLogProvider(root).getReferenceManager().getLabelsOrderComparator());
}
private static class DataPanel extends JEditorPane {
public static final int BRANCHES_LIMIT = 6;
public static final int BRANCHES_TABLE_COLUMN_COUNT = 3;
@NotNull public static final String LEFT_ALIGN = "left";
@NotNull private static String SHOW_OR_HIDE_BRANCHES = "Show or Hide Branches";
@NotNull private final Project myProject;
private final boolean myMultiRoot;
private String myMainText;
@Nullable private List<String> myBranches;
private boolean myExpanded = false;
DataPanel(@NotNull Project project, boolean multiRoot, @NotNull Disposable disposable) {
super(UIUtil.HTML_MIME, "");
myProject = project;
myMultiRoot = multiRoot;
setEditable(false);
setOpaque(false);
putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
EditorColorsManager.getInstance().addEditorColorsListener(new EditorColorsAdapter() {
@Override
public void globalSchemeChange(EditorColorsScheme scheme) {
update();
}
}, disposable);
DefaultCaret caret = (DefaultCaret)getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && SHOW_OR_HIDE_BRANCHES.equals(e.getDescription())) {
myExpanded = !myExpanded;
update();
}
else {
BrowserHyperlinkListener.INSTANCE.hyperlinkUpdate(e);
}
}
});
}
void setData(@Nullable VcsFullCommitDetails commit) {
if (commit == null) {
myMainText = null;
}
else {
String header = commit.getId().toShortString() + " " + getAuthorText(commit) +
(myMultiRoot ? " [" + commit.getRoot().getName() + "]" : "");
String body = getMessageText(commit);
myMainText = header + "<br/>" + body;
}
update();
}
void setBranches(@Nullable List<String> branches) {
if (branches == null) {
myBranches = null;
}
else {
myBranches = branches;
}
myExpanded = false;
update();
}
private void update() {
if (myMainText == null) {
setText("");
}
else {
setText("<html><head>" +
UIUtil.getCssFontDeclaration(EditorColorsManager.getInstance().getGlobalScheme().getFont(EditorFontType.PLAIN)) +
"</head><body>" +
myMainText +
"<br/>" +
"<br/>" +
getBranchesText() +
"</body></html>");
}
revalidate();
repaint();
}
@NotNull
private String getBranchesText() {
if (myBranches == null) {
return "<i>In branches: loading...</i>";
}
if (myBranches.isEmpty()) return "<i>Not in any branch</i>";
if (myExpanded) {
int rowCount = (int)Math.ceil((double)myBranches.size() / BRANCHES_TABLE_COLUMN_COUNT);
int[] means = new int[BRANCHES_TABLE_COLUMN_COUNT - 1];
int[] max = new int[BRANCHES_TABLE_COLUMN_COUNT - 1];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < BRANCHES_TABLE_COLUMN_COUNT - 1; j++) {
int index = rowCount * j + i;
if (index < myBranches.size()) {
means[j] += myBranches.get(index).length();
max[j] = Math.max(myBranches.get(index).length(), max[j]);
}
}
}
for (int j = 0; j < BRANCHES_TABLE_COLUMN_COUNT - 1; j++) {
means[j] /= rowCount;
}
HtmlTableBuilder builder = new HtmlTableBuilder();
for (int i = 0; i < rowCount; i++) {
builder.startRow();
if (i == 0) {
builder.append("<i>In " + myBranches.size() + " branches, </i><a href=\"" + SHOW_OR_HIDE_BRANCHES + "\"><i>hide</i></a>: ");
}
else {
builder.append("");
}
for (int j = 0; j < BRANCHES_TABLE_COLUMN_COUNT; j++) {
int index = rowCount * j + i;
if (index >= myBranches.size()) {
builder.append("");
}
else {
String branch = myBranches.get(index);
if (index != myBranches.size() - 1) {
int space = 0;
if (j < BRANCHES_TABLE_COLUMN_COUNT - 1 && branch.length() == max[j]) {
space = Math.max(means[j] + 20 - max[j], 5);
}
builder.append(branch + "," + StringUtil.repeat(" ", space), LEFT_ALIGN);
}
else {
builder.append(branch, LEFT_ALIGN);
}
}
}
builder.endRow();
}
return builder.build();
}
else {
String branchText;
if (myBranches.size() <= BRANCHES_LIMIT) {
branchText = StringUtil.join(myBranches, ", ");
}
else {
branchText = StringUtil.join(ContainerUtil.getFirstItems(myBranches, BRANCHES_LIMIT), ", ") +
", ... <a href=\"" +
SHOW_OR_HIDE_BRANCHES +
"\"><i>Show All</i></a>";
}
return "<i>In " + myBranches.size() + StringUtil.pluralize(" branch", myBranches.size()) + ":</i> " + branchText;
}
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.height = Math.max(size.height, 4 * getFontMetrics(getFont()).getHeight());
return size;
}
@NotNull
private String getMessageText(@NotNull VcsFullCommitDetails commit) {
String fullMessage = commit.getFullMessage();
int separator = fullMessage.indexOf("\n\n");
String subject = separator > 0 ? fullMessage.substring(0, separator) : fullMessage;
String description = fullMessage.substring(subject.length());
return "<b>" + escapeMultipleSpaces(IssueLinkHtmlRenderer.formatTextWithLinks(myProject, subject)) + "</b>" +
escapeMultipleSpaces(IssueLinkHtmlRenderer.formatTextWithLinks(myProject, description));
}
@NotNull
private String escapeMultipleSpaces(@NotNull String text) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ') {
if (i == text.length() - 1 || text.charAt(i + 1) != ' ') {
result.append(' ');
}
else {
result.append(" ");
}
}
else {
result.append(text.charAt(i));
}
}
return result.toString();
}
@NotNull
private static String getAuthorText(@NotNull VcsFullCommitDetails commit) {
long authorTime = commit.getAuthorTime();
long commitTime = commit.getCommitTime();
String authorText = VcsUserUtil.getShortPresentation(commit.getAuthor()) + formatDateTime(authorTime);
if (!VcsUserUtil.isSamePerson(commit.getAuthor(), commit.getCommitter())) {
String commitTimeText;
if (authorTime != commitTime) {
commitTimeText = formatDateTime(commitTime);
}
else {
commitTimeText = "";
}
authorText += " (committed by " + VcsUserUtil.getShortPresentation(commit.getCommitter()) + commitTimeText + ")";
}
else if (authorTime != commitTime) {
authorText += " (committed " + formatDateTime(commitTime) + ")";
}
return authorText;
}
@Override
public String getSelectedText() {
Document doc = getDocument();
int start = getSelectionStart();
int end = getSelectionEnd();
try {
Position p0 = doc.createPosition(start);
Position p1 = doc.createPosition(end);
StringWriter sw = new StringWriter(p1.getOffset() - p0.getOffset());
getEditorKit().write(sw, doc, p0.getOffset(), p1.getOffset() - p0.getOffset());
return StringUtil.removeHtmlTags(sw.toString());
}
catch (BadLocationException e) {
LOG.warn(e);
}
catch (IOException e) {
LOG.warn(e);
}
return super.getSelectedText();
}
@Override
public Color getBackground() {
return getDetailsBackground();
}
public boolean isExpanded() {
return myExpanded;
}
}
private static class ReferencesPanel extends JPanel {
@NotNull private final VcsRefPainter myReferencePainter;
@NotNull private List<VcsRef> myReferences;
ReferencesPanel(@NotNull VcsLogColorManager colorManager) {
super(new FlowLayout(FlowLayout.LEADING, 4, 2));
myReferencePainter = new VcsRefPainter(colorManager, false);
myReferences = Collections.emptyList();
setOpaque(false);
}
void setReferences(@NotNull List<VcsRef> references) {
removeAll();
myReferences = references;
for (VcsRef reference : references) {
add(new SingleReferencePanel(myReferencePainter, reference));
}
setVisible(!myReferences.isEmpty());
revalidate();
repaint();
}
@Override
public Color getBackground() {
return getDetailsBackground();
}
}
private static class SingleReferencePanel extends JPanel {
@NotNull private final VcsRefPainter myRefPainter;
@NotNull private VcsRef myReference;
SingleReferencePanel(@NotNull VcsRefPainter referencePainter, @NotNull VcsRef reference) {
myRefPainter = referencePainter;
myReference = reference;
setOpaque(false);
}
@Override
protected void paintComponent(Graphics g) {
myRefPainter.paint(myReference, g, 0, 0);
}
@Override
public Color getBackground() {
return getDetailsBackground();
}
@Override
public Dimension getPreferredSize() {
return myRefPainter.getSize(myReference, this);
}
}
private static class MessagePanel extends NonOpaquePanel {
@NotNull private final JLabel myLabel;
MessagePanel() {
super(new BorderLayout());
myLabel = new JLabel();
myLabel.setForeground(UIUtil.getInactiveTextColor());
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);
add(myLabel);
}
void setText(String text) {
myLabel.setText(text);
}
@Override
public Color getBackground() {
return getDetailsBackground();
}
}
}
| apache-2.0 |
wufuwei/dubbox | dubbo-osp/dubbo-osp-provider/src/main/java/com/osp/biz/service/impl/OspCatalogService.java | 2226 | /*
* Powered By wufuwei
*/
package com.osp.biz.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.osp.biz.service.IOspCatalogService;
import com.osp.biz.manager.IOspCatalogManager;
import com.osp.biz.model.OspCatalog;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;
/**
* @author David Wu email:oradb(a)163.com
* @version 1.0
* @since 1.0
*/
@Service
public class OspCatalogService implements IOspCatalogService{
private IOspCatalogManager ospCatalogManager;
/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性*/
@Autowired
public void setOspCatalogManager(IOspCatalogManager manager) {
this.ospCatalogManager = manager;
}
public IOspCatalogManager getEntityManager() {
return this.ospCatalogManager;
}
public OspCatalog getById(java.lang.Long id) {
return (OspCatalog)ospCatalogManager.getById(id);
}
public void save(OspCatalog entity) {
ospCatalogManager.save(entity);
}
public void removeById(java.lang.Long id) {
ospCatalogManager.removeById(id);
}
public void update(OspCatalog entity) {
ospCatalogManager.update(entity);
}
public boolean isUnique(OspCatalog entity, String uniquePropertyNames) {
return ospCatalogManager.isUnique(entity, uniquePropertyNames);
}
public Long pageSelectCount(OspCatalog entity){
return ospCatalogManager.pageSelectCount(entity);
}
public Page findByPageRequest(PageRequest pr) {
return ospCatalogManager.findByPageRequest(pr);
}
public OspCatalog getByInnercode(java.lang.String v) {
return ospCatalogManager.getByInnercode(v);
}
public List<OspCatalog> findAll() {
return ospCatalogManager.findAll();
}
public void updateDynamic(OspCatalog entity){
ospCatalogManager.updateDynamic(entity);
}
public List<OspCatalog> findByDynamicWhere(OspCatalog entity){
return ospCatalogManager.findByDynamicWhere(entity);
}
public void saveOrUpdate(OspCatalog entity){
ospCatalogManager.saveOrUpdate(entity);
}
}
| apache-2.0 |
LorenzoDV/closure-compiler | test/com/google/javascript/jscomp/GwtPropertiesTest.java | 1716 | /*
* Copyright 2016 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import junit.framework.TestCase;
/**
* Tests {@link GwtProperties}.
*/
public final class GwtPropertiesTest extends TestCase {
public void testLoadEmpty() {
GwtProperties p = GwtProperties.load("");
assertTrue(p.propertyNames().isEmpty());
}
public void testLoadWithComments() {
String src = "\n"
+ "# not.set=value\n"
+ "is.set=value\n";
GwtProperties p = GwtProperties.load(src);
assertEquals(null, p.getProperty("not.set"));
assertEquals("value", p.getProperty("is.set"));
}
public void testNoEquals() {
GwtProperties p = GwtProperties.load("foo bar");
assertEquals("bar", p.getProperty("foo"));
}
public void testExtraCR() {
GwtProperties p = GwtProperties.load("value is \\\r\nradical");
assertEquals("is radical", p.getProperty("value"));
}
public void testLongValue() {
String src = "\n"
+ "property : 1,\\\n"
+ " 2,\\\n"
+ " 3\n";
GwtProperties p = GwtProperties.load(src);
assertEquals("1,2,3", p.getProperty("property"));
}
}
| apache-2.0 |
davinash/geode | geode-redis/src/main/java/org/apache/geode/redis/internal/executor/RedisResponse.java | 4335 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
package org.apache.geode.redis.internal.executor;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import org.apache.geode.redis.internal.netty.Coder;
import org.apache.geode.redis.internal.netty.CoderException;
public class RedisResponse {
private final Function<ByteBufAllocator, ByteBuf> coderCallback;
private RedisResponse(Function<ByteBufAllocator, ByteBuf> coderCallback) {
this.coderCallback = coderCallback;
}
public ByteBuf encode(ByteBufAllocator allocator) {
return coderCallback.apply(allocator);
}
public static RedisResponse integer(long numericValue) {
return new RedisResponse((bba) -> Coder.getIntegerResponse(bba, numericValue));
}
public static RedisResponse integer(boolean exists) {
return new RedisResponse((bba) -> Coder.getIntegerResponse(bba, exists ? 1 : 0));
}
public static RedisResponse string(String stringValue) {
return new RedisResponse((bba) -> Coder.getSimpleStringResponse(bba, stringValue));
}
public static RedisResponse bulkString(Object value) {
return new RedisResponse((bba) -> {
try {
return Coder.getBulkStringResponse(bba, value);
} catch (CoderException e) {
return Coder.getErrorResponse(bba, "Internal server error: " + e.getMessage());
}
});
}
public static RedisResponse ok() {
return new RedisResponse((bba) -> Coder.getSimpleStringResponse(bba, "OK"));
}
public static RedisResponse nil() {
return new RedisResponse(Coder::getNilResponse);
}
public static RedisResponse flattenedArray(Collection<Collection<?>> nestedCollection) {
return new RedisResponse((bba) -> {
try {
return Coder.getFlattenedArrayResponse(bba, nestedCollection);
} catch (CoderException e) {
return Coder.getErrorResponse(bba, "Internal server error: " + e.getMessage());
}
});
}
public static RedisResponse array(Collection<?> collection) {
return new RedisResponse((bba) -> {
try {
return Coder.getArrayResponse(bba, collection);
} catch (CoderException e) {
return Coder.getErrorResponse(bba, "Internal server error: " + e.getMessage());
}
});
}
public static RedisResponse emptyArray() {
return new RedisResponse(Coder::getEmptyArrayResponse);
}
public static RedisResponse emptyString() {
return new RedisResponse(Coder::getEmptyStringResponse);
}
public static RedisResponse error(String error) {
return new RedisResponse((bba) -> Coder.getErrorResponse(bba, error));
}
public static RedisResponse customError(String error) {
return new RedisResponse((bba) -> Coder.getCustomErrorResponse(bba, error));
}
public static RedisResponse wrongType(String error) {
return new RedisResponse((bba) -> Coder.getWrongTypeResponse(bba, error));
}
public static RedisResponse scan(List<?> items) {
return new RedisResponse((bba) -> Coder.getScanResponse(bba, items));
}
/**
* Be aware that this implementation will create extra garbage since it allocates from the heap.
*/
public String toString() {
return encode(new UnpooledByteBufAllocator(false)).toString(Charset.defaultCharset());
}
public static RedisResponse doubleValue(double numericValue) {
return new RedisResponse((bba) -> Coder.getDoubleResponse(bba, numericValue));
}
}
| apache-2.0 |
sslavic/Thotti | thotticore/src/main/java/de/fischer/thotti/core/annotations/ParamVal.java | 981 | /*
* Copyright 2011 Oliver B. Fischer
*
* 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.fischer.thotti.core.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface ParamVal {
String name();
String value();
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-amplifyuibuilder/src/main/java/com/amazonaws/services/amplifyuibuilder/model/ExportThemesRequest.java | 6852 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.amplifyuibuilder.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/amplifyuibuilder-2021-08-11/ExportThemes" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ExportThemesRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The unique ID of the Amplify app to export the themes to.
* </p>
*/
private String appId;
/**
* <p>
* The name of the backend environment that is part of the Amplify app.
* </p>
*/
private String environmentName;
/**
* <p>
* The token to request the next page of results.
* </p>
*/
private String nextToken;
/**
* <p>
* The unique ID of the Amplify app to export the themes to.
* </p>
*
* @param appId
* The unique ID of the Amplify app to export the themes to.
*/
public void setAppId(String appId) {
this.appId = appId;
}
/**
* <p>
* The unique ID of the Amplify app to export the themes to.
* </p>
*
* @return The unique ID of the Amplify app to export the themes to.
*/
public String getAppId() {
return this.appId;
}
/**
* <p>
* The unique ID of the Amplify app to export the themes to.
* </p>
*
* @param appId
* The unique ID of the Amplify app to export the themes to.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ExportThemesRequest withAppId(String appId) {
setAppId(appId);
return this;
}
/**
* <p>
* The name of the backend environment that is part of the Amplify app.
* </p>
*
* @param environmentName
* The name of the backend environment that is part of the Amplify app.
*/
public void setEnvironmentName(String environmentName) {
this.environmentName = environmentName;
}
/**
* <p>
* The name of the backend environment that is part of the Amplify app.
* </p>
*
* @return The name of the backend environment that is part of the Amplify app.
*/
public String getEnvironmentName() {
return this.environmentName;
}
/**
* <p>
* The name of the backend environment that is part of the Amplify app.
* </p>
*
* @param environmentName
* The name of the backend environment that is part of the Amplify app.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ExportThemesRequest withEnvironmentName(String environmentName) {
setEnvironmentName(environmentName);
return this;
}
/**
* <p>
* The token to request the next page of results.
* </p>
*
* @param nextToken
* The token to request the next page of results.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The token to request the next page of results.
* </p>
*
* @return The token to request the next page of results.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The token to request the next page of results.
* </p>
*
* @param nextToken
* The token to request the next page of results.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ExportThemesRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAppId() != null)
sb.append("AppId: ").append(getAppId()).append(",");
if (getEnvironmentName() != null)
sb.append("EnvironmentName: ").append(getEnvironmentName()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ExportThemesRequest == false)
return false;
ExportThemesRequest other = (ExportThemesRequest) obj;
if (other.getAppId() == null ^ this.getAppId() == null)
return false;
if (other.getAppId() != null && other.getAppId().equals(this.getAppId()) == false)
return false;
if (other.getEnvironmentName() == null ^ this.getEnvironmentName() == null)
return false;
if (other.getEnvironmentName() != null && other.getEnvironmentName().equals(this.getEnvironmentName()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAppId() == null) ? 0 : getAppId().hashCode());
hashCode = prime * hashCode + ((getEnvironmentName() == null) ? 0 : getEnvironmentName().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ExportThemesRequest clone() {
return (ExportThemesRequest) super.clone();
}
}
| apache-2.0 |
pkcool/bmsuite | bmsuite-framework/src/main/java/com/enginemobi/core/generic/service/BmSuiteEntityService.java | 1220 | package com.enginemobi.core.generic.service;
import com.enginemobi.core.generic.domain.BmSuiteEntity;
import com.enginemobi.core.generic.exception.ServiceException;
import java.io.Serializable;
import java.util.List;
/**
* <p>Generic service interface</p>
*
* @param <K> type Primary Key
*/
public interface BmSuiteEntityService<K extends Serializable & Comparable<K>, E extends BmSuiteEntity<K, ?>> extends TransactionalAspectAwareService{
/**
* @param entity entity
*/
void save(E entity) throws ServiceException;
/**
*
* @param entity
*/
void update(E entity) throws ServiceException;
/**
*
* @param entity
*/
void create(E entity) throws ServiceException;
/**
*
* @param entity
*/
void delete(E entity) throws ServiceException;
/**
*
* @param entity
*/
E refresh(E entity);
/**
*
* @param id identification
* @return
*/
E getById(K id);
/**
*
* @return list of entities
*/
List<E> list();
E getEntity(Class<? extends E> clazz, K id);
Long count();
/**
* flush the session
*/
void flush();
void clear();
}
| apache-2.0 |
osmdroid/osmdroid | osmdroid-android/src/main/filtered/org/osmdroid/OsmdroidBuildInfo.java | 375 | package org.osmdroid;
//this file is automatically generated during the build
//when making changes, only edit ./src/main/filtered/...
//https://github.com/osmdroid/osmdroid/issues/1500
public class OsmdroidBuildInfo {
private OsmdroidBuildInfo() {
}
public static final String VERSION = "@pom.version@";
public static final String BUILD_DATE = "@date@";
} | apache-2.0 |
pmoerenhout/jsmpp-1 | jsmpp-examples/src/test/java/org/jsmpp/examples/receipts/ExampleDeliveryReceiptStripperTest.java | 1765 | package org.jsmpp.examples.receipts;
import java.io.UnsupportedEncodingException;
import org.apache.log4j.BasicConfigurator;
import org.jsmpp.bean.DefaultDeliveryReceiptStripper;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.bean.DeliveryReceipt;
import org.jsmpp.util.InvalidDeliveryReceiptException;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ExampleDeliveryReceiptStripperTest {
private ExampleDeliveryReceiptStripper deliveryReceiptStripper;
private DefaultDeliveryReceiptStripper defaultDeliveryReceiptStripper;
@BeforeMethod
public void setUp() throws Exception {
BasicConfigurator.configure();
deliveryReceiptStripper = new ExampleDeliveryReceiptStripper();
defaultDeliveryReceiptStripper = new DefaultDeliveryReceiptStripper();
}
@Test
public void testDeliveryReceiptStripper() {
final String message = "id:123456 sub:234 dlvrd:000 submit date:1604052345 done date:1605021145 stat:DELIVRD";
DeliveryReceipt deliveryReceipt = null;
try {
DeliverSm deliverSm = new DeliverSm();
// Short Message contains SMSC Delivery Receipt
deliverSm.setEsmClass((byte)0x04);
deliverSm.setShortMessage(message.getBytes("ASCII"));
deliveryReceipt = deliveryReceiptStripper.strip(deliverSm);
System.out.println(deliveryReceipt);
}
catch (InvalidDeliveryReceiptException e){
System.out.println("InvalidDeliveryReceiptException " + e.getMessage());
}catch (UnsupportedEncodingException e){
System.out.println("UnsupportedEncodingException " + e.getMessage());
}
Assert.assertEquals("123456", deliveryReceipt.getId());
Assert.assertEquals(234, deliveryReceipt.getSubmitted());
}
} | apache-2.0 |
gekowa/comicat-sdgo-android | app/src/main/java/cn/sdgundam/comicatsdgo/api_model/ApiResultWrapper.java | 613 | package cn.sdgundam.comicatsdgo.api_model;
/**
* Created by xhguo on 10/20/2014.
*/
public class ApiResultWrapper<T> {
private Exception e;
private T payload;
public Exception getE() {
return e;
}
public void setE(Exception e) {
this.e = e;
}
public T getPayload() {
return payload;
}
public void setPayload(T payload) {
this.payload = payload;
}
public ApiResultWrapper() { }
public ApiResultWrapper(T payload) {
this.payload = payload;
}
public ApiResultWrapper(Exception e) {
this.e = e;
}
}
| apache-2.0 |
ettoremaiorana/ReconcilerServer | src/main/java/com/fourcasters/forec/reconciler/server/trades/persist/TransactionPhaseListener.java | 228 | package com.fourcasters.forec.reconciler.server.trades.persist;
public interface TransactionPhaseListener {
void onTransactionStart(int transId);
void onTransactionEnd(int transId);
void onTaskEnd();
void onTaskStart();
}
| apache-2.0 |
kasunbg/wso2-samples-cxf | cxf_sts_client_w_wso2_is/src/main/java/com/cxf/sts/WSO2STSTest.java | 4539 | /*
* Copyright 2004,2013 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cxf.sts;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.trust.STSClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.ls.DOMImplementationLS;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
public class WSO2STSTest {
public static void main(String[] args) throws ParserConfigurationException {
System.out.println("base folder - " + new File("").getAbsolutePath());
System.setProperty("javax.net.ssl.trustStore",
"/home/kasun/wso2/products/420-packs/wso2is-4.6.0/repository/resources/security/client-truststore.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"classpath:wssec-sts-bean.xml");
doSTS(ctx);
}
private static void doSTS(ApplicationContext ctx) throws ParserConfigurationException {
STSClient sts = (STSClient) ctx.
getBean("{http://ws.apache.org/axis2}wso2carbon-stsHttpsSoap12Endpoint.sts-client");
//parse the ut policy xml, and get a DOM element
File f = new File("src/main/resources/sts.policy.xml");
Element stsPolicy = loadPolicy(f.getAbsolutePath());
sts.setPolicy(stsPolicy);
sts.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
sts.setKeyType("http://schemas.xmlsoap.org/ws/2005/02/trust/Bearer");
sts.setSoap11(false);
// //sts.setWsdlLocation("https://localhost:9443/services/wso2carbon-sts?wsdl");
// sts.setLocation("https://localhost:9443/services/wso2carbon-sts.wso2carbon-stsHttpsSoap12Endpoint");
// sts.setServiceName("{http://ws.apache.org/axis2}wso2carbon-sts");
// sts.setEndpointName("{http://ws.apache.org/axis2}wso2carbon-stsHttpsSoap12Endpoint");
// Map<String, Object> props = new HashMap<String, Object>();
// props.put(SecurityConstants.USERNAME, "admin");
// props.put(SecurityConstants.PASSWORD, "admin");
// props.put(SecurityConstants.CALLBACK_HANDLER, "com.cxf.sts.ClientCallbackHandler");
// props.put(SecurityConstants.ENCRYPT_PROPERTIES,
// "bearer-client.properties");
// props.put(SecurityConstants.ENCRYPT_USERNAME, "wso2carbon");
// sts.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
// sts.setKeyType("http://schemas.xmlsoap.org/ws/2005/02/trust/Bearer");
// sts.setProperties(props);
try {
SecurityToken samlToken =
sts.requestSecurityToken("http://localhost:9453/services/echo",
"http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT",
"/Issue", null);
//convert the token dom element to string
String token = ((DOMImplementationLS) samlToken.getToken().getOwnerDocument().getImplementation()).
createLSSerializer().writeToString(samlToken.getToken().getOwnerDocument());
System.out.println(token);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sts.getEndpointQName());
}
private static Element loadPolicy(String xmlPath) {
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse(new File(xmlPath));
return d.getDocumentElement();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
} | apache-2.0 |
stephanenicolas/toothpick | toothpick-runtime/src/test/java/toothpick/data/IFooWithBarProvider.java | 985 | /*
* Copyright 2019 Stephane Nicolas
* Copyright 2019 Daniel Molinero Reguera
*
* 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 toothpick.data;
import javax.inject.Inject;
import javax.inject.Provider;
public class IFooWithBarProvider implements Provider<IFoo> {
private Bar bar;
@Inject
public IFooWithBarProvider(Bar bar) {
this.bar = bar;
}
@Override
public IFoo get() {
Foo foo = new Foo();
foo.bar = bar;
return foo;
}
}
| apache-2.0 |
GE159/Weather-S | src/com/gwk/weathers/fragment/PicLiveFragment.java | 604 | package com.gwk.weathers.fragment;
import com.gwk.weathers.app.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/*
*作者:葛文凯
*邮箱:651517957@qq.com
*时间:2015年12月7日下午3:45:41
*/
public class PicLiveFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View picLiveFragment=inflater.inflate(R.layout.fragment_frag_pic_live, container,false);
return picLiveFragment;
}
}
| apache-2.0 |
seeburger-ag/commons-vfs | commons-vfs2/src/main/java/org/apache/commons/vfs2/util/RawMonitorInputStream.java | 5139 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* An InputStream that provides end-of-stream monitoring.
* <p>
* This is the same as {@link MonitorInputStream} but without the buffering.
* </p>
*
* @since 2.5.0
*/
public class RawMonitorInputStream extends FilterInputStream {
private static final int EOF_CHAR = -1;
private final AtomicBoolean finished = new AtomicBoolean(false);
private final AtomicLong atomicCount = new AtomicLong(0);
// @Override
// public synchronized void reset() throws IOException {
// if (!finished.get()) {
// super.reset();
// }
// }
//
// @Override
// public synchronized long skip(long n) throws IOException {
// if (finished.get()) {
// return 0;
// }
// return super.skip(n);
// }
/**
* Constructs a MonitorInputStream from the passed InputStream
*
* @param inputStream The input stream to wrap.
*/
public RawMonitorInputStream(final InputStream inputStream) {
super(inputStream);
}
/**
* Returns 0 if the stream is at EOF, else the underlying inputStream will be queried.
*
* @return The number of bytes that are available.
* @throws IOException if an error occurs.
*/
@Override
public synchronized int available() throws IOException {
if (finished.get()) {
return 0;
}
return super.available();
}
/**
* Reads a character.
*
* @return The character that was read as an integer.
* @throws IOException if an error occurs.
*/
@Override
public int read() throws IOException { // lgtm [java/non-sync-override]
if (finished.get()) {
return EOF_CHAR;
}
final int ch = super.read();
if (ch != EOF_CHAR) {
atomicCount.incrementAndGet();
}
return ch;
}
/**
* Reads bytes from this input stream.
*
* @param buffer A byte array in which to place the characters read.
* @param offset The offset at which to start reading.
* @param length The maximum number of bytes to read.
* @return The number of bytes read.
* @throws IOException if an error occurs.
*/
@Override
public int read(final byte[] buffer, final int offset, final int length) throws IOException { // lgtm [java/non-sync-override]
if (finished.get()) {
return EOF_CHAR;
}
final int nread = super.read(buffer, offset, length);
if (nread != EOF_CHAR) {
atomicCount.addAndGet(nread);
}
return nread;
}
/**
* Closes this input stream and releases any system resources associated with the stream.
*
* @throws IOException if an error occurs.
*/
@Override
public void close() throws IOException {
final boolean closed = finished.getAndSet(true);
if (closed) {
return;
}
// Close the stream
IOException exc = null;
try {
super.close();
} catch (final IOException ioe) {
exc = ioe;
}
// Notify that the stream has been closed
try {
onClose();
} catch (final IOException ioe) {
exc = ioe;
}
if (exc != null) {
throw exc;
}
}
/**
* Called after the stream has been closed. This implementation does nothing.
*
* @throws IOException if an error occurs.
*/
protected void onClose() throws IOException {
// noop
}
/**
* Gets the number of bytes read by this input stream.
*
* @return The number of bytes read by this input stream.
*/
public long getCount() {
return atomicCount.get();
}
@Override
public synchronized void mark(final int readlimit) {
// TODO Auto-generated method stub
super.mark(readlimit);
}
}
| apache-2.0 |
jiangyuanlin/hello | src/main/java/com/idp/web/system/service/impl/SysOrgServiceImpl.java | 2001 | package com.idp.web.system.service.impl;
import java.text.DecimalFormat;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.idp.web.system.dao.SysOrgDao;
import com.idp.web.system.entity.SysOrg;
import com.idp.web.system.service.SysOrgService;
@Service("SysOrgService")
public class SysOrgServiceImpl implements SysOrgService {
@Resource
private SysOrgDao sysOrgDao;
@Override
public List<SysOrg> find(SysOrg org) {
return sysOrgDao.find(org);
}
@Override
public List<SysOrg> findForTreeTable(Long parentId) {
return sysOrgDao.findForTreeTable(parentId);
}
@Override
public SysOrg getById(Long id) {
return sysOrgDao.getById(id);
}
@Override
public void add(SysOrg org) {
buildCode(org);
sysOrgDao.add(org);
}
@Override
public void update(SysOrg org) {
// 上层组织改变时,改变组织编码
SysOrg oldOrg = sysOrgDao.getById(org.getId());
if(org.getParentId() != oldOrg.getParentId()){
buildCode(org);
}
sysOrgDao.update(org);
}
@Override
public void delete(Long id) {
sysOrgDao.delete(id);
}
public void deleteChildren(Long id){
SysOrg param = new SysOrg();
param.setParentId(id);
List<SysOrg> children = sysOrgDao.find(param);
if(children != null && children.size() > 0){
for(SysOrg child : children){
deleteChildren(child.getId());
}
sysOrgDao.deleteByParentId(id);
}
}
public void buildCode(SysOrg org){
String maxCode = sysOrgDao.getMaxCode(org.getParentId());
if(StringUtils.isNotEmpty(maxCode)){
String preno = maxCode.substring(0, maxCode.length() - 3);
int no = Integer.valueOf(maxCode.substring(maxCode.length() - 3));
DecimalFormat df = new DecimalFormat("000");
org.setOrgCode(preno+df.format(no+1));
}
else{
SysOrg parentOrg = sysOrgDao.getById(org.getParentId());
org.setOrgCode(parentOrg.getOrgCode()+"001");
}
}
}
| apache-2.0 |
oliveti/resolver | spi/src/main/java/org/jboss/shrinkwrap/resolver/spi/format/InputStreamFormatProcessor.java | 3234 | /*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.shrinkwrap.resolver.spi.format;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.jboss.shrinkwrap.resolver.api.ResolvedArtifact;
/**
* {@link FormatProcessor} implementation to return an {@link InputStream} from the provided {@link ResolvedArtifact} argument.
*
* Implementation note: This format processor does not use type parameters to be able to process any type inherited from
* {@link ResolvedAritifact}.
*
* @author <a href="mailto:alr@jboss.org">Andrew Lee Rubinger</a>
*/
@SuppressWarnings("rawtypes")
public enum InputStreamFormatProcessor implements FormatProcessor {
INSTANCE;
/**
* {@inheritDoc}
*
* @see org.jboss.shrinkwrap.resolver.spi.format.FormatProcessor#process(File, Class)
*/
@Override
public InputStream process(final ResolvedArtifact artifact, final Class returnType)
throws IllegalArgumentException {
if (returnType.getClass() == null || InputStream.class.equals(returnType.getClass())) {
throw new IllegalArgumentException("InputStream processor must be called to return InputStream, not "
+ (returnType == null ? "null" : returnType.getClass()));
}
if (artifact == null) {
throw new IllegalArgumentException("Resolution artifact must be specified");
}
File file = artifact.asFile();
if (file == null) {
throw new IllegalArgumentException("Artifact was not resolved");
}
if (!file.exists()) {
throw new IllegalArgumentException("input file does not exist: " + file.getAbsolutePath());
}
if (file.isDirectory()) {
throw new IllegalArgumentException("input file is a directory: " + file.getAbsolutePath());
}
try {
// Return
return new FileInputStream(file);
} catch (final FileNotFoundException fnfe) {
// Wrap to make the compiler happy, even though we have the precondition checks above
throw new IllegalArgumentException(fnfe);
}
}
@Override
public boolean handles(Class resolvedTypeClass) {
return ResolvedArtifact.class.isAssignableFrom(resolvedTypeClass);
}
@Override
public boolean returns(Class returnTypeClass) {
return InputStream.class.equals(returnTypeClass);
}
}
| apache-2.0 |
masatomix01/helloworld | src/main/java/nu/mine/kino/web/MultiplyCalc.java | 594 | package nu.mine.kino.web;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Masatomi KINO
* @version $Revision$
*/
@RestController
@RequestMapping("/multiply")
public class MultiplyCalc {
@RequestMapping(value = "/{param1}/{param2}", method = RequestMethod.GET)
public Object add(@PathVariable int param1, @PathVariable int param2) {
return param1 * param2;
}
} | apache-2.0 |
mrniko/redisson | redisson/src/main/java/org/redisson/connection/balancer/RoundRobinLoadBalancer.java | 1173 | /**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* 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.redisson.connection.balancer;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.redisson.connection.ClientConnectionsEntry;
/**
*
* @author Nikita Koksharov
*
*/
public class RoundRobinLoadBalancer implements LoadBalancer {
private final AtomicInteger index = new AtomicInteger(-1);
@Override
public ClientConnectionsEntry getEntry(List<ClientConnectionsEntry> clientsCopy) {
int ind = Math.abs(index.incrementAndGet() % clientsCopy.size());
return clientsCopy.get(ind);
}
}
| apache-2.0 |
capergroup/bayou | src/main/java/edu/rice/cs/caper/floodgage/application/floodgage/model/directive/parser/xml/v1/JavaxXmlParser.java | 6601 | /*
Copyright 2017 Rice 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 edu.rice.cs.caper.floodgage.application.floodgage.model.directive.parser.xml.v1;
import edu.rice.cs.caper.floodgage.application.floodgage.model.directive.*;
import edu.rice.cs.caper.floodgage.application.floodgage.model.directive.parser.ParseException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
/**
* A DirectiveXmlV1Parser that is based on the javax.xml package for xml parsing.
*/
public class JavaxXmlParser implements DirectiveXmlV1Parser
{
@Override
public Directive parse(String directiveString) throws ParseException
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
/*
* Parse directiveString into a Document and normalize.
*/
Document doc;
try
{
DocumentBuilder dBuilder;
try
{
dBuilder = dbFactory.newDocumentBuilder();
}
catch (ParserConfigurationException e)
{
throw new RuntimeException(e);
}
doc = dBuilder.parse(new ByteArrayInputStream(directiveString.getBytes()));
//http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
}
catch (SAXException | IOException e)
{
throw new ParseException(e);
}
/*
* Take the (assumed root) <trials> element and collect the child <trial> elements.
*/
List<Trial> trials;
{
final String TRIALS = "trials";
NodeList list = doc.getElementsByTagName(TRIALS);
if(list.getLength() < 1)
{
throw new ParseException("No " + TRIALS + " elements found");
}
else if(list.getLength() == 1)
{
Element trialsElement = (Element)list.item(0);
trials = parseTrials(trialsElement);
}
else
{
throw new ParseException("Multiple " + TRIALS + " elements found");
}
}
/*
* Return a Directive containing the trials.
*/
return Directive.make(trials);
}
/*
* Collect the child <trial> elements.
*/
private List<Trial> parseTrials(Element trialsElement) throws ParseException
{
List<Trial> trials = new LinkedList<>();
NodeList list = trialsElement.getElementsByTagName("trial");
for (int i = 0; i < list.getLength(); i++)
{
Trial trial = parseTrial((Element)list.item(i));
trials.add(trial);
}
return trials;
}
/*
* Create a Trial from a <trial> element.
*/
private Trial parseTrial(Element trialElement) throws ParseException
{
if(trialElement == null)
throw new NullPointerException("trialElement");
// nulls ok because they signal element not present
String description = getSingleChildElementTextContentOrNull(trialElement, "description");
String draftProgramPath = getSingleChildElementTextContentOrNull(trialElement, "draftProgramPath");
String expectedSketchProgramPath = getSingleChildElementTextContentOrNull(trialElement, "expectedSketchPath");
List<Hole> holes = new LinkedList<>();
{
final String HOLES = "holes";
NodeList list = trialElement.getElementsByTagName(HOLES);
if(list.getLength() == 1)
{
Element holesElement = (Element)list.item(0);
NodeList holesList = holesElement.getElementsByTagName("hole");
for (int i = 0; i < holesList.getLength(); i++)
{
Hole hole = parseHole((Element) holesList.item(i));
holes.add(hole);
}
}
else if(list.getLength() > 1)
{
throw new ParseException("Multiple " + HOLES + " elements found");
}
}
return Trial.make(description, draftProgramPath, expectedSketchProgramPath, holes);
}
/*
* Create a Hole from a <hole> element.
*/
private Hole parseHole(Element holeElement)
{
List<Evidence> evidences = new LinkedList<>();
NodeList list = holeElement.getElementsByTagName("evidence");
for (int i = 0; i < list.getLength(); i++)
{
Evidence evidence = parseEvidence((Element)list.item(i));
evidences.add(evidence);
}
String id = getAttributeOrNull(holeElement, "id");
return Hole.make(id, evidences);
}
/*
* Create Evidence from evidenceElement
*/
private Evidence parseEvidence(Element evidenceElement)
{
String type = getAttributeOrNull(evidenceElement, "type");
return Evidence.make(type, evidenceElement.getTextContent());
}
private String getAttributeOrNull(Element item, String name)
{
if(item.hasAttribute(name))
return item.getAttribute(name);
return null;
}
private String getSingleChildElementTextContentOrNull(Element parentElement, String childElementName)
throws ParseException
{
NodeList list = parentElement.getElementsByTagName(childElementName);
if(list.getLength() < 1)
{
return null;
}
else if(list.getLength() == 1)
{
return list.item(0).getTextContent();
}
else
{
throw new ParseException("Multiple " + childElementName + " elements found");
}
}
}
| apache-2.0 |
stephanenicolas/toothpick | toothpick-compiler/src/main/java/toothpick/compiler/factory/FactoryProcessor.java | 24457 | /*
* Copyright 2019 Stephane Nicolas
* Copyright 2019 Daniel Molinero Reguera
*
* 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 toothpick.compiler.factory;
import static java.lang.String.format;
import static javax.lang.model.element.Modifier.PRIVATE;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedOptions;
import javax.inject.Inject;
import javax.inject.Scope;
import javax.inject.Singleton;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter;
import toothpick.Factory;
import toothpick.InjectConstructor;
import toothpick.ProvidesReleasable;
import toothpick.ProvidesSingleton;
import toothpick.Releasable;
import toothpick.compiler.common.ToothpickProcessor;
import toothpick.compiler.factory.generators.FactoryGenerator;
import toothpick.compiler.factory.targets.ConstructorInjectionTarget;
/**
* This processor's role is to create {@link Factory}. We create factories in different situations :
*
* <ul>
* <li>When a class {@code Foo} has an {@link javax.inject.Inject} annotated constructor : <br>
* --> we create a Factory to create {@code Foo} instances.
* </ul>
*
* The processor will also try to relax the constraints to generate factories in a few cases. These
* factories are helpful as they require less work from developers :
*
* <ul>
* <li>When a class {@code Foo} is annotated with {@link javax.inject.Singleton} : <br>
* --> it will use the annotated constructor or the default constructor if possible. Otherwise
* an error is raised.
* <li>When a class {@code Foo} is annotated with {@link ProvidesSingleton} : <br>
* --> it will use the annotated constructor or the default constructor if possible. Otherwise
* an error is raised.
* <li>When a class {@code Foo} has an {@link javax.inject.Inject} annotated field {@code @Inject
* B b} : <br>
* --> it will use the annotated constructor or the default constructor if possible. Otherwise
* an error is raised.
* <li>When a class {@code Foo} has an {@link javax.inject.Inject} method {@code @Inject m()} :
* <br>
* --> it will use the annotated constructor or the default constructor if possible. Otherwise
* an error is raised.
* </ul>
*
* Note that if a class is abstract, the relax mechanism doesn't generate a factory and raises no
* error.
*/
// http://stackoverflow.com/a/2067863/693752
@SupportedOptions({
ToothpickProcessor.PARAMETER_EXCLUDES, //
ToothpickProcessor.PARAMETER_ANNOTATION_TYPES, //
ToothpickProcessor.PARAMETER_CRASH_WHEN_NO_FACTORY_CAN_BE_CREATED, //
}) //
public class FactoryProcessor extends ToothpickProcessor {
private static final String SUPPRESS_WARNING_ANNOTATION_INJECTABLE_VALUE = "injectable";
private Map<TypeElement, ConstructorInjectionTarget> mapTypeElementToConstructorInjectionTarget;
private Boolean crashWhenNoFactoryCanBeCreated;
private Map<String, TypeElement> allRoundsGeneratedToTypeElement = new HashMap<>();
@Override
public Set<String> getSupportedAnnotationTypes() {
supportedAnnotationTypes.add(ToothpickProcessor.INJECT_ANNOTATION_CLASS_NAME);
supportedAnnotationTypes.add(ToothpickProcessor.SINGLETON_ANNOTATION_CLASS_NAME);
supportedAnnotationTypes.add(ToothpickProcessor.PRODUCES_SINGLETON_ANNOTATION_CLASS_NAME);
supportedAnnotationTypes.add(ToothpickProcessor.INJECT_CONSTRUCTOR_ANNOTATION_CLASS_NAME);
readOptionAnnotationTypes();
return supportedAnnotationTypes;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
readCommonProcessorOptions();
readCrashWhenNoFactoryCanBeCreatedOption();
mapTypeElementToConstructorInjectionTarget = new LinkedHashMap<>();
findAndParseTargets(roundEnv, annotations);
// Generate Factories
for (Map.Entry<TypeElement, ConstructorInjectionTarget> entry :
mapTypeElementToConstructorInjectionTarget.entrySet()) {
ConstructorInjectionTarget constructorInjectionTarget = entry.getValue();
FactoryGenerator factoryGenerator =
new FactoryGenerator(constructorInjectionTarget, typeUtils);
TypeElement typeElement = entry.getKey();
String fileDescription = format("Factory for type %s", typeElement);
writeToFile(factoryGenerator, fileDescription, typeElement);
allRoundsGeneratedToTypeElement.put(factoryGenerator.getFqcn(), typeElement);
}
return false;
}
private void readCrashWhenNoFactoryCanBeCreatedOption() {
Map<String, String> options = processingEnv.getOptions();
if (crashWhenNoFactoryCanBeCreated == null) {
crashWhenNoFactoryCanBeCreated =
Boolean.parseBoolean(options.get(PARAMETER_CRASH_WHEN_NO_FACTORY_CAN_BE_CREATED));
}
}
private void findAndParseTargets(
RoundEnvironment roundEnv, Set<? extends TypeElement> annotations) {
createFactoriesForClassesAnnotatedWithInjectConstructor(roundEnv);
createFactoriesForClassesWithInjectAnnotatedConstructors(roundEnv);
createFactoriesForClassesAnnotatedWith(roundEnv, ProvidesSingleton.class);
createFactoriesForClassesWithInjectAnnotatedFields(roundEnv);
createFactoriesForClassesWithInjectAnnotatedMethods(roundEnv);
createFactoriesForClassesAnnotatedWithScopeAnnotations(roundEnv, annotations);
}
private void createFactoriesForClassesAnnotatedWithScopeAnnotations(
RoundEnvironment roundEnv, Set<? extends TypeElement> annotations) {
for (TypeElement annotation : annotations) {
if (annotation.getAnnotation(Scope.class) != null) {
checkScopeAnnotationValidity(annotation);
createFactoriesForClassesAnnotatedWith(roundEnv, annotation);
}
}
}
private void createFactoriesForClassesWithInjectAnnotatedMethods(RoundEnvironment roundEnv) {
for (ExecutableElement methodElement :
ElementFilter.methodsIn(roundEnv.getElementsAnnotatedWith(Inject.class))) {
processClassContainingInjectAnnotatedMember(
methodElement.getEnclosingElement(), mapTypeElementToConstructorInjectionTarget);
}
}
private void createFactoriesForClassesWithInjectAnnotatedFields(RoundEnvironment roundEnv) {
for (VariableElement fieldElement :
ElementFilter.fieldsIn(roundEnv.getElementsAnnotatedWith(Inject.class))) {
processClassContainingInjectAnnotatedMember(
fieldElement.getEnclosingElement(), mapTypeElementToConstructorInjectionTarget);
}
}
private void createFactoriesForClassesAnnotatedWith(
RoundEnvironment roundEnv, Class<? extends Annotation> annotationClass) {
for (Element annotatedElement :
ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(annotationClass))) {
TypeElement annotatedTypeElement = (TypeElement) annotatedElement;
processClassContainingInjectAnnotatedMember(
annotatedTypeElement, mapTypeElementToConstructorInjectionTarget);
}
}
private void createFactoriesForClassesAnnotatedWith(
RoundEnvironment roundEnv, TypeElement annotationType) {
for (Element annotatedElement :
ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(annotationType))) {
TypeElement annotatedTypeElement = (TypeElement) annotatedElement;
processClassContainingInjectAnnotatedMember(
annotatedTypeElement, mapTypeElementToConstructorInjectionTarget);
}
}
private void createFactoriesForClassesWithInjectAnnotatedConstructors(RoundEnvironment roundEnv) {
for (ExecutableElement constructorElement :
ElementFilter.constructorsIn(roundEnv.getElementsAnnotatedWith(Inject.class))) {
TypeElement enclosingElement = (TypeElement) constructorElement.getEnclosingElement();
if (!isSingleInjectAnnotatedConstructor(constructorElement)) {
error(
constructorElement,
"Class %s cannot have more than one @Inject annotated constructor.",
enclosingElement.getQualifiedName());
}
processInjectAnnotatedConstructor(
constructorElement, mapTypeElementToConstructorInjectionTarget);
}
}
private void createFactoriesForClassesAnnotatedWithInjectConstructor(RoundEnvironment roundEnv) {
for (Element annotatedElement :
ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(InjectConstructor.class))) {
TypeElement annotatedTypeElement = (TypeElement) annotatedElement;
List<ExecutableElement> constructorElements =
ElementFilter.constructorsIn(annotatedTypeElement.getEnclosedElements());
if (constructorElements.size() != 1
|| constructorElements.get(0).getAnnotation(Inject.class) != null) {
error(
constructorElements.get(0),
"Class %s is annotated with @InjectInjectConstructor. Therefore, It must have one unique constructor and it should not be annotated with @Inject.",
annotatedTypeElement.getQualifiedName());
}
processInjectAnnotatedConstructor(
constructorElements.get(0), mapTypeElementToConstructorInjectionTarget);
}
}
private void processClassContainingInjectAnnotatedMember(
Element enclosingElement,
Map<TypeElement, ConstructorInjectionTarget> mapTypeElementToConstructorInjectionTarget) {
final TypeElement typeElement = (TypeElement) typeUtils.asElement(enclosingElement.asType());
if (mapTypeElementToConstructorInjectionTarget.containsKey(typeElement)) {
// the class is already known
return;
}
if (isExcludedByFilters(typeElement)) {
return;
}
// Verify common generated code restrictions.
if (!canTypeHaveAFactory(typeElement)) {
return;
}
ConstructorInjectionTarget constructorInjectionTarget =
createConstructorInjectionTarget(typeElement);
if (constructorInjectionTarget != null) {
mapTypeElementToConstructorInjectionTarget.put(typeElement, constructorInjectionTarget);
}
}
private boolean isSingleInjectAnnotatedConstructor(Element constructorElement) {
TypeElement enclosingElement = (TypeElement) constructorElement.getEnclosingElement();
boolean isSingleInjectedConstructor = true;
List<ExecutableElement> constructorElements =
ElementFilter.constructorsIn(enclosingElement.getEnclosedElements());
for (ExecutableElement constructorElementInClass : constructorElements) {
if (constructorElementInClass.getAnnotation(Inject.class) != null
&& !constructorElement.equals(constructorElementInClass)) {
isSingleInjectedConstructor = false;
}
}
return isSingleInjectedConstructor;
}
private void processInjectAnnotatedConstructor(
ExecutableElement constructorElement,
Map<TypeElement, ConstructorInjectionTarget> targetClassMap) {
TypeElement enclosingElement = (TypeElement) constructorElement.getEnclosingElement();
// Verify common generated code restrictions.
if (!isValidInjectAnnotatedConstructor(constructorElement)) {
return;
}
if (isExcludedByFilters(enclosingElement)) {
return;
}
if (!canTypeHaveAFactory(enclosingElement)) {
error(
enclosingElement,
"The class %s is abstract or private. It cannot have an injected constructor.",
enclosingElement.getQualifiedName());
return;
}
targetClassMap.put(enclosingElement, createConstructorInjectionTarget(constructorElement));
}
private boolean isValidInjectAnnotatedConstructor(ExecutableElement element) {
TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
// Verify modifiers.
Set<Modifier> modifiers = element.getModifiers();
if (modifiers.contains(PRIVATE)) {
error(
element,
"@Inject constructors must not be private in class %s.",
enclosingElement.getQualifiedName());
return false;
}
// Verify parentScope modifiers.
Set<Modifier> parentModifiers = enclosingElement.getModifiers();
if (parentModifiers.contains(PRIVATE)) {
error(
element,
"Class %s is private. @Inject constructors are not allowed in private classes.",
enclosingElement.getQualifiedName());
return false;
}
if (isNonStaticInnerClass(enclosingElement)) {
return false;
}
for (VariableElement paramElement : element.getParameters()) {
if (!isValidInjectedType(paramElement)) {
return false;
}
}
return true;
}
private ConstructorInjectionTarget createConstructorInjectionTarget(
ExecutableElement constructorElement) {
TypeElement enclosingElement = (TypeElement) constructorElement.getEnclosingElement();
final String scopeName = getScopeName(enclosingElement);
final boolean hasSingletonAnnotation = hasSingletonAnnotation(enclosingElement);
final boolean hasReleasableAnnotation = hasReleasableAnnotation(enclosingElement);
final boolean hasProvidesSingletonInScopeAnnotation =
hasProvidesSingletonInScopeAnnotation(enclosingElement);
final boolean hasProvidesReleasableAnnotation =
hasProvidesReleasableAnnotation(enclosingElement);
checkReleasableAnnotationValidity(
enclosingElement, hasReleasableAnnotation, hasSingletonAnnotation);
checkProvidesReleasableAnnotationValidity(
enclosingElement, hasReleasableAnnotation, hasSingletonAnnotation);
if (hasProvidesSingletonInScopeAnnotation && scopeName == null) {
error(
enclosingElement,
"The type %s uses @ProvidesSingleton but doesn't have a scope annotation.",
enclosingElement.getQualifiedName().toString());
}
TypeElement superClassWithInjectedMembers =
getMostDirectSuperClassWithInjectedMembers(enclosingElement, false);
ConstructorInjectionTarget constructorInjectionTarget =
new ConstructorInjectionTarget(
enclosingElement,
scopeName,
hasSingletonAnnotation,
hasReleasableAnnotation,
hasProvidesSingletonInScopeAnnotation,
hasProvidesReleasableAnnotation,
superClassWithInjectedMembers);
constructorInjectionTarget.parameters.addAll(getParamInjectionTargetList(constructorElement));
constructorInjectionTarget.throwsThrowable = !constructorElement.getThrownTypes().isEmpty();
return constructorInjectionTarget;
}
private ConstructorInjectionTarget createConstructorInjectionTarget(TypeElement typeElement) {
final String scopeName = getScopeName(typeElement);
final boolean hasSingletonAnnotation = hasSingletonAnnotation(typeElement);
final boolean hasReleasableAnnotation = hasReleasableAnnotation(typeElement);
final boolean hasProvidesSingletonInScopeAnnotation =
hasProvidesSingletonInScopeAnnotation(typeElement);
final boolean hasProvidesReleasableAnnotation = hasProvidesReleasableAnnotation(typeElement);
checkReleasableAnnotationValidity(typeElement, hasReleasableAnnotation, hasSingletonAnnotation);
checkProvidesReleasableAnnotationValidity(
typeElement, hasReleasableAnnotation, hasSingletonAnnotation);
if (hasProvidesSingletonInScopeAnnotation && scopeName == null) {
error(
typeElement,
"The type %s uses @ProvidesSingleton but doesn't have a scope annotation.",
typeElement.getQualifiedName().toString());
}
TypeElement superClassWithInjectedMembers =
getMostDirectSuperClassWithInjectedMembers(typeElement, false);
List<ExecutableElement> constructorElements =
ElementFilter.constructorsIn(typeElement.getEnclosedElements());
// we just need to deal with the case of the default constructor only.
// like Guice, we will call it by default in the optimistic factory
// injected constructors will be handled at some point in the compilation cycle
// if there is an injected constructor, it will be caught later, just leave
for (ExecutableElement constructorElement : constructorElements) {
if (constructorElement.getAnnotation(Inject.class) != null) {
return null;
}
}
final String cannotCreateAFactoryMessage =
" Toothpick can't create a factory for it." //
+ " If this class is itself a DI entry point (i.e. you call TP.inject(this) at some point), " //
+ " then you can remove this warning by adding @SuppressWarnings(\"Injectable\") to the class." //
+ " A typical example is a class using injection to assign its fields, that calls TP.inject(this)," //
+ " but it needs a parameter for its constructor and this parameter is not injectable.";
// search for default constructor
for (ExecutableElement constructorElement : constructorElements) {
if (constructorElement.getParameters().isEmpty()) {
if (constructorElement.getModifiers().contains(Modifier.PRIVATE)) {
if (!isInjectableWarningSuppressed(typeElement)) {
String message =
format(
"The class %s has a private default constructor. "
+ cannotCreateAFactoryMessage, //
typeElement.getQualifiedName().toString());
crashOrWarnWhenNoFactoryCanBeCreated(constructorElement, message);
}
return null;
}
ConstructorInjectionTarget constructorInjectionTarget =
new ConstructorInjectionTarget(
typeElement,
scopeName,
hasSingletonAnnotation,
hasReleasableAnnotation,
hasProvidesSingletonInScopeAnnotation,
hasProvidesReleasableAnnotation,
superClassWithInjectedMembers);
return constructorInjectionTarget;
}
}
if (!isInjectableWarningSuppressed(typeElement)) {
String message =
format(
"The class %s has injected members or a scope annotation "
+ "but has no @Inject annotated (non-private) constructor " //
+ " nor a non-private default constructor. "
+ cannotCreateAFactoryMessage, //
typeElement.getQualifiedName().toString());
crashOrWarnWhenNoFactoryCanBeCreated(typeElement, message);
}
return null;
}
private void crashOrWarnWhenNoFactoryCanBeCreated(Element element, String message) {
if (crashWhenNoFactoryCanBeCreated != null && crashWhenNoFactoryCanBeCreated) {
error(element, message);
} else {
warning(element, message);
}
}
/**
* Lookup {@link javax.inject.Scope} annotated annotations to provide the name of the scope the
* {@code typeElement} belongs to. The method logs an error if the {@code typeElement} has
* multiple scope annotations.
*
* @param typeElement the element for which a scope is to be found.
* @return the scope of this {@code typeElement} or {@code null} if it has no scope annotations.
*/
private String getScopeName(TypeElement typeElement) {
String scopeName = null;
boolean hasScopeAnnotation = false;
for (AnnotationMirror annotationMirror : typeElement.getAnnotationMirrors()) {
TypeElement annotationTypeElement =
(TypeElement) annotationMirror.getAnnotationType().asElement();
boolean isSingletonAnnotation =
annotationTypeElement.getQualifiedName().contentEquals("javax.inject.Singleton");
if (!isSingletonAnnotation && annotationTypeElement.getAnnotation(Scope.class) != null) {
checkScopeAnnotationValidity(annotationTypeElement);
if (scopeName != null) {
error(typeElement, "Only one @Scope qualified annotation is allowed : %s", scopeName);
}
scopeName = annotationTypeElement.getQualifiedName().toString();
}
if (isSingletonAnnotation) {
hasScopeAnnotation = true;
}
}
if (hasScopeAnnotation && scopeName == null) {
scopeName = "javax.inject.Singleton";
}
return scopeName;
}
private boolean hasSingletonAnnotation(TypeElement typeElement) {
return typeElement.getAnnotation(Singleton.class) != null;
}
private boolean hasReleasableAnnotation(TypeElement typeElement) {
return typeElement.getAnnotation(Releasable.class) != null;
}
private boolean hasProvidesSingletonInScopeAnnotation(TypeElement typeElement) {
return typeElement.getAnnotation(ProvidesSingleton.class) != null;
}
private boolean hasProvidesReleasableAnnotation(TypeElement typeElement) {
return typeElement.getAnnotation(ProvidesReleasable.class) != null;
}
private void checkReleasableAnnotationValidity(
TypeElement typeElement, boolean hasReleasableAnnotation, boolean hasSingletonAnnotation) {
if (hasReleasableAnnotation && !hasSingletonAnnotation) {
error(
typeElement,
"Class %s is annotated with @Releasable, "
+ "it should also be annotated with either @Singleton.",
typeElement.getQualifiedName());
}
}
private void checkProvidesReleasableAnnotationValidity(
TypeElement typeElement,
boolean hasProvidesReleasableAnnotation,
boolean hasProvideSingletonInScopeAnnotation) {
if (hasProvidesReleasableAnnotation && !hasProvideSingletonInScopeAnnotation) {
error(
typeElement,
"Class %s is annotated with @ProvidesReleasable, "
+ "it should also be annotated with either @ProvidesSingleton.",
typeElement.getQualifiedName());
}
}
private void checkScopeAnnotationValidity(TypeElement annotation) {
if (annotation.getAnnotation(Scope.class) == null) {
error(
annotation,
"Scope Annotation %s does not contain Scope annotation.",
annotation.getQualifiedName());
return;
}
Retention retention = annotation.getAnnotation(Retention.class);
if (retention == null || retention.value() != RetentionPolicy.RUNTIME) {
error(
annotation,
"Scope Annotation %s does not have RUNTIME retention policy.",
annotation.getQualifiedName());
}
}
/**
* Checks if the injectable warning is suppressed for the TypeElement, through the usage
* of @SuppressWarning("Injectable").
*
* @param typeElement the element to check if the warning is suppressed.
* @return true is the injectable warning is suppressed, false otherwise.
*/
private boolean isInjectableWarningSuppressed(TypeElement typeElement) {
return hasWarningSuppressed(typeElement, SUPPRESS_WARNING_ANNOTATION_INJECTABLE_VALUE);
}
private boolean canTypeHaveAFactory(TypeElement typeElement) {
boolean isAbstract = typeElement.getModifiers().contains(Modifier.ABSTRACT);
boolean isPrivate = typeElement.getModifiers().contains(Modifier.PRIVATE);
return !isAbstract && !isPrivate;
}
// used for testing only
void setToothpickExcludeFilters(String toothpickExcludeFilters) {
this.toothpickExcludeFilters = toothpickExcludeFilters;
}
// used for testing only
void setCrashWhenNoFactoryCanBeCreated(boolean crashWhenNoFactoryCanBeCreated) {
this.crashWhenNoFactoryCanBeCreated = crashWhenNoFactoryCanBeCreated;
}
// used for testing only
TypeElement getOriginatingElement(String generatedQualifiedName) {
return allRoundsGeneratedToTypeElement.get(generatedQualifiedName);
}
}
| apache-2.0 |
KavaProject/KavaTouch | src/main/java/org/kavaproject/kavatouch/foundation/DefaultBundle.java | 7083 | /*
* Copyright 2013 The Kava Project Developers. See the COPYRIGHT file at the top-level directory of this distribution
* and at http://kavaproject.org/COPYRIGHT.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the
* MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. This file may not be copied,
* modified, or distributed except according to those terms.
*/
package org.kavaproject.kavatouch.foundation;
import org.kavaproject.kavatouch.corefoundation.CoreBundle;
import org.kavaproject.kavatouch.corefoundation.CoreURL;
import org.kavaproject.kavatouch.internal.Header;
import org.kavaproject.kavatouch.runtime.Factory;
import org.kavaproject.kavatouch.util.NotImplementedException;
import java.util.List;
import java.util.Map;
public class DefaultBundle implements Bundle {
private final URLFactory mURLFactory;
private final BundleFactory mBundleFactory;
private CoreBundle mCoreBundle;
protected DefaultBundle(CoreBundle coreBundle, BundleFactory bundleFactory, URLFactory urlFactory) {
mBundleFactory = bundleFactory;
mURLFactory = urlFactory;
mCoreBundle = coreBundle;
}
@Override
public Factory factoryNamed(String name) {
throw new NotImplementedException(); //TODO
}
@Override
public Factory principalFactory() {
throw new NotImplementedException(); //TODO
}
@Override
public URL urlForResource(String name, String extension, String subpath) {
throw new NotImplementedException(); //TODO
}
@Override
public URL urlForResource(String name, String extension) {
throw new NotImplementedException(); //TODO
}
@Override
public String pathForResourceOfType(String resourceName, String extension) {
throw new NotImplementedException();
}
@Override
public List<URL> urlsForResources(String extension, String subdirectory) {
throw new NotImplementedException(); //TODO
}
@Override
public String pathForResource(String resourceName, String extension, String directory) {
throw new NotImplementedException(); //TODO
}
@Override
public URL urlForResource(String name, String extension, String subdirectory, String localizationName) {
throw new NotImplementedException(); //TODO
}
@Override
public String pathForResource(String name, String typeExtension, String directory, String localizationName) {
throw new NotImplementedException(); //TODO
}
@Override
public List<String> pathsForResources(String extension, String directory) {
throw new NotImplementedException();
}
@Override
public List<URL> urlsForResources(String extension, String subdirectory, String localizationName) {
throw new NotImplementedException(); //TODO
}
@Override
public List<String> pathsForResources(String extension, String directory, String localizationName) {
throw new NotImplementedException(); //TODO
}
@Override
public String resourcePath() {
CoreURL cfURL = mCoreBundle.copyResourcesDirectoryURL();
return mURLFactory.create(cfURL).path();
}
@Override
public URL bundleURL() {
throw new NotImplementedException(); //TODO
}
@Override
public String bundlePath() {
throw new NotImplementedException(); //TODO
}
@Override
public String bundleIdentifier() {
throw new NotImplementedException(); //TODO
}
@Override
public Map<String, Object> infoDictionary() {
throw new NotImplementedException(); //TODO
}
@Override
public Object objectForInfoDictionaryKey() {
throw new NotImplementedException(); //TODO
}
@Override
public URL builtInPlugInsURL() {
throw new NotImplementedException(); //TODO
}
@Override
public String builtInPlugInsPath() {
throw new NotImplementedException(); //TODO
}
@Override
public URL executableURL() {
throw new NotImplementedException(); //TODO
}
@Override
public String executablePath() {
throw new NotImplementedException(); //TODO
}
@Override
public URL URLForAuxiliaryExecutable(String executableName) {
throw new NotImplementedException(); //TODO
}
@Override
public String pathForAuxiliaryExecutable(String executableName) {
throw new NotImplementedException(); //TODO
}
@Override
public URL privateFrameworksURL() {
throw new NotImplementedException(); //TODO
}
@Override
public String privateFrameworksPath() {
throw new NotImplementedException(); //TODO
}
@Override
public URL sharedFrameworksURL() {
throw new NotImplementedException(); //TODO
}
@Override
public String sharedFrameworksPath() {
throw new NotImplementedException(); //TODO
}
@Override
public URL sharedSupportURL() {
throw new NotImplementedException(); //TODO
}
@Override
public String sharedSupportPath() {
throw new NotImplementedException(); //TODO
}
@Override
public URL resourceURL() {
throw new NotImplementedException(); //TODO
}
@Override
public String localizedStringForKeyValueTable(FoundationString key, String value, FoundationString tableName) {
throw new NotImplementedException(); //TODO
}
@Override
public List executableArchitectures() {
throw new NotImplementedException(); //TODO
}
@Override
public boolean preflight() throws RuntimeException {
throw new NotImplementedException(); //TODO
}
// @OccInstanceMethod("load")
// public boolean load() {
// throw new NotImplementedException(); //TODO
// }
@Override
public boolean load() throws RuntimeException {
throw new NotImplementedException(); //TODO
}
@Override
public boolean isLoaded() {
throw new NotImplementedException(); //TODO
}
@Override
public boolean unload() {
throw new NotImplementedException(); //TODO
}
@Override
public List<String> localizations() {
throw new NotImplementedException(); //TODO
}
@Override
public String developmentLocalization() {
throw new NotImplementedException(); //TODO
}
@Override
public List<String> preferredLocalizations() {
throw new NotImplementedException(); //TODO
}
@Override
public Map<String, Object> localizedInfoDictionary() {
throw new NotImplementedException(); //TODO
}
@Override
@Header("UINibLoading")
public List loadNib(String filename, Object owner, UINibLoadingOptions options) {
throw new NotImplementedException(); //TODO
}
@Override
public BundleFactory getFactory() {
return mBundleFactory;
}
@Override
public CoreBundle toCoreType() {
return mCoreBundle;
}
}
| apache-2.0 |
leeyazhou/activiti-app | activiti-demo/src/main/java/com/xyz/core/rest/diagram/services/BaseProcessDefinitionDiagramLayoutResource.java | 22692 | /* 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.xyz.core.rest.diagram.services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.bpmn.behavior.BoundaryEventActivityBehavior;
import org.activiti.engine.impl.bpmn.behavior.CallActivityBehavior;
import org.activiti.engine.impl.bpmn.parser.BpmnParse;
import org.activiti.engine.impl.bpmn.parser.ErrorEventDefinition;
import org.activiti.engine.impl.bpmn.parser.EventSubscriptionDeclaration;
import org.activiti.engine.impl.jobexecutor.TimerDeclarationImpl;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.delegate.ActivityBehavior;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.Lane;
import org.activiti.engine.impl.pvm.process.LaneSet;
import org.activiti.engine.impl.pvm.process.ParticipantProcess;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class BaseProcessDefinitionDiagramLayoutResource {
@Autowired
private RuntimeService runtimeService;
@Autowired
private RepositoryService repositoryService;
@Autowired
private HistoryService historyService;
public ObjectNode getDiagramNode(String processInstanceId, String processDefinitionId) {
List<String> highLightedFlows = Collections.<String> emptyList();
List<String> highLightedActivities = Collections.<String> emptyList();
Map<String, ObjectNode> subProcessInstanceMap = new HashMap<String, ObjectNode>();
ProcessInstance processInstance = null;
if (processInstanceId != null) {
processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
if (processInstance == null) {
throw new ActivitiObjectNotFoundException("Process instance could not be found");
}
processDefinitionId = processInstance.getProcessDefinitionId();
List<ProcessInstance> subProcessInstances = runtimeService
.createProcessInstanceQuery()
.superProcessInstanceId(processInstanceId).list();
for (ProcessInstance subProcessInstance : subProcessInstances) {
String subDefId = subProcessInstance.getProcessDefinitionId();
String superExecutionId = ((ExecutionEntity) subProcessInstance)
.getSuperExecutionId();
ProcessDefinitionEntity subDef = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(subDefId);
ObjectNode processInstanceJSON = new ObjectMapper().createObjectNode();
processInstanceJSON.put("processInstanceId", subProcessInstance.getId());
processInstanceJSON.put("superExecutionId", superExecutionId);
processInstanceJSON.put("processDefinitionId", subDef.getId());
processInstanceJSON.put("processDefinitionKey", subDef.getKey());
processInstanceJSON.put("processDefinitionName", subDef.getName());
subProcessInstanceMap.put(superExecutionId, processInstanceJSON);
}
}
if (processDefinitionId == null) {
throw new ActivitiObjectNotFoundException("No process definition id provided");
}
ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processDefinitionId);
if (processDefinition == null) {
throw new ActivitiException("Process definition " + processDefinitionId + " could not be found");
}
ObjectNode responseJSON = new ObjectMapper().createObjectNode();
// Process definition
JsonNode pdrJSON = getProcessDefinitionResponse(processDefinition);
if (pdrJSON != null) {
responseJSON.put("processDefinition", pdrJSON);
}
// Highlighted activities
if (processInstance != null) {
ArrayNode activityArray = new ObjectMapper().createArrayNode();
ArrayNode flowsArray = new ObjectMapper().createArrayNode();
highLightedActivities = runtimeService.getActiveActivityIds(processInstanceId);
highLightedFlows = getHighLightedFlows(processInstanceId, processDefinition);
for (String activityName : highLightedActivities) {
activityArray.add(activityName);
}
for (String flow : highLightedFlows)
flowsArray.add(flow);
responseJSON.put("highLightedActivities", activityArray);
responseJSON.put("highLightedFlows", flowsArray);
}
// Pool shape, if process is participant in collaboration
if (processDefinition.getParticipantProcess() != null) {
ParticipantProcess pProc = processDefinition.getParticipantProcess();
ObjectNode participantProcessJSON = new ObjectMapper().createObjectNode();
participantProcessJSON.put("id", pProc.getId());
if (StringUtils.isNotEmpty(pProc.getName())) {
participantProcessJSON.put("name", pProc.getName());
} else {
participantProcessJSON.put("name", "");
}
participantProcessJSON.put("x", pProc.getX());
participantProcessJSON.put("y", pProc.getY());
participantProcessJSON.put("width", pProc.getWidth());
participantProcessJSON.put("height", pProc.getHeight());
responseJSON.put("participantProcess", participantProcessJSON);
}
// Draw lanes
if (processDefinition.getLaneSets() != null && !processDefinition.getLaneSets().isEmpty()) {
ArrayNode laneSetArray = new ObjectMapper().createArrayNode();
for (LaneSet laneSet : processDefinition.getLaneSets()) {
ArrayNode laneArray = new ObjectMapper().createArrayNode();
if (laneSet.getLanes() != null && !laneSet.getLanes().isEmpty()) {
for (Lane lane : laneSet.getLanes()) {
ObjectNode laneJSON = new ObjectMapper().createObjectNode();
laneJSON.put("id", lane.getId());
if (StringUtils.isNotEmpty(lane.getName())) {
laneJSON.put("name", lane.getName());
} else {
laneJSON.put("name", "");
}
laneJSON.put("x", lane.getX());
laneJSON.put("y", lane.getY());
laneJSON.put("width", lane.getWidth());
laneJSON.put("height", lane.getHeight());
List<String> flowNodeIds = lane.getFlowNodeIds();
ArrayNode flowNodeIdsArray = new ObjectMapper().createArrayNode();
for (String flowNodeId : flowNodeIds) {
flowNodeIdsArray.add(flowNodeId);
}
laneJSON.put("flowNodeIds", flowNodeIdsArray);
laneArray.add(laneJSON);
}
}
ObjectNode laneSetJSON = new ObjectMapper().createObjectNode();
laneSetJSON.put("id", laneSet.getId());
if (StringUtils.isNotEmpty(laneSet.getName())) {
laneSetJSON.put("name", laneSet.getName());
} else {
laneSetJSON.put("name", "");
}
laneSetJSON.put("lanes", laneArray);
laneSetArray.add(laneSetJSON);
}
if (laneSetArray.size() > 0)
responseJSON.put("laneSets", laneSetArray);
}
ArrayNode sequenceFlowArray = new ObjectMapper().createArrayNode();
ArrayNode activityArray = new ObjectMapper().createArrayNode();
// Activities and their sequence-flows
for (ActivityImpl activity : processDefinition.getActivities()) {
getActivity(processInstanceId, activity, activityArray, sequenceFlowArray,
processInstance, highLightedFlows, subProcessInstanceMap);
}
responseJSON.put("activities", activityArray);
responseJSON.put("sequenceFlows", sequenceFlowArray);
return responseJSON;
}
private List<String> getHighLightedFlows(String processInstanceId, ProcessDefinitionEntity processDefinition) {
List<String> highLightedFlows = new ArrayList<String>();
List<HistoricActivityInstance> historicActivityInstances = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(processInstanceId)
.orderByHistoricActivityInstanceStartTime().asc().list();
List<String> historicActivityInstanceList = new ArrayList<String>();
for (HistoricActivityInstance hai : historicActivityInstances) {
historicActivityInstanceList.add(hai.getActivityId());
}
// add current activities to list
List<String> highLightedActivities = runtimeService.getActiveActivityIds(processInstanceId);
historicActivityInstanceList.addAll(highLightedActivities);
// activities and their sequence-flows
for (ActivityImpl activity : processDefinition.getActivities()) {
int index = historicActivityInstanceList.indexOf(activity.getId());
if (index >= 0 && index + 1 < historicActivityInstanceList.size()) {
List<PvmTransition> pvmTransitionList = activity
.getOutgoingTransitions();
for (PvmTransition pvmTransition : pvmTransitionList) {
String destinationFlowId = pvmTransition.getDestination().getId();
if (destinationFlowId.equals(historicActivityInstanceList.get(index + 1))) {
highLightedFlows.add(pvmTransition.getId());
}
}
}
}
return highLightedFlows;
}
private void getActivity(String processInstanceId, ActivityImpl activity, ArrayNode activityArray,
ArrayNode sequenceFlowArray, ProcessInstance processInstance, List<String> highLightedFlows,
Map<String, ObjectNode> subProcessInstanceMap) {
ObjectNode activityJSON = new ObjectMapper().createObjectNode();
// Gather info on the multi instance marker
String multiInstance = (String) activity.getProperty("multiInstance");
if (multiInstance != null) {
if (!"sequential".equals(multiInstance)) {
multiInstance = "parallel";
}
}
ActivityBehavior activityBehavior = activity.getActivityBehavior();
// Gather info on the collapsed marker
Boolean collapsed = (activityBehavior instanceof CallActivityBehavior);
Boolean expanded = (Boolean) activity.getProperty(BpmnParse.PROPERTYNAME_ISEXPANDED);
if (expanded != null) {
collapsed = !expanded;
}
Boolean isInterrupting = null;
if (activityBehavior instanceof BoundaryEventActivityBehavior) {
isInterrupting = ((BoundaryEventActivityBehavior) activityBehavior).isInterrupting();
}
// Outgoing transitions of activity
for (PvmTransition sequenceFlow : activity.getOutgoingTransitions()) {
String flowName = (String) sequenceFlow.getProperty("name");
boolean isHighLighted = (highLightedFlows.contains(sequenceFlow.getId()));
boolean isConditional = sequenceFlow.getProperty(BpmnParse.PROPERTYNAME_CONDITION) != null &&
!((String) activity.getProperty("type")).toLowerCase().contains("gateway");
boolean isDefault = sequenceFlow.getId().equals(activity.getProperty("default"))
&& ((String) activity.getProperty("type")).toLowerCase().contains("gateway");
List<Integer> waypoints = ((TransitionImpl) sequenceFlow).getWaypoints();
ArrayNode xPointArray = new ObjectMapper().createArrayNode();
ArrayNode yPointArray = new ObjectMapper().createArrayNode();
for (int i = 0; i < waypoints.size(); i += 2) { // waypoints.size()
// minimally 4: x1, y1,
// x2, y2
xPointArray.add(waypoints.get(i));
yPointArray.add(waypoints.get(i + 1));
}
ObjectNode flowJSON = new ObjectMapper().createObjectNode();
flowJSON.put("id", sequenceFlow.getId());
flowJSON.put("name", flowName);
flowJSON.put("flow", "(" + sequenceFlow.getSource().getId() + ")--"
+ sequenceFlow.getId() + "-->("
+ sequenceFlow.getDestination().getId() + ")");
if (isConditional)
flowJSON.put("isConditional", isConditional);
if (isDefault)
flowJSON.put("isDefault", isDefault);
if (isHighLighted)
flowJSON.put("isHighLighted", isHighLighted);
flowJSON.put("xPointArray", xPointArray);
flowJSON.put("yPointArray", yPointArray);
sequenceFlowArray.add(flowJSON);
}
// Nested activities (boundary events)
ArrayNode nestedActivityArray = new ObjectMapper().createArrayNode();
for (ActivityImpl nestedActivity : activity.getActivities()) {
nestedActivityArray.add(nestedActivity.getId());
}
Map<String, Object> properties = activity.getProperties();
ObjectNode propertiesJSON = new ObjectMapper().createObjectNode();
for (String key : properties.keySet()) {
Object prop = properties.get(key);
if (prop instanceof String)
propertiesJSON.put(key, (String) properties.get(key));
else if (prop instanceof Integer)
propertiesJSON.put(key, (Integer) properties.get(key));
else if (prop instanceof Boolean)
propertiesJSON.put(key, (Boolean) properties.get(key));
else if ("initial".equals(key)) {
ActivityImpl act = (ActivityImpl) properties.get(key);
propertiesJSON.put(key, act.getId());
} else if ("timerDeclarations".equals(key)) {
ArrayList<TimerDeclarationImpl> timerDeclarations = (ArrayList<TimerDeclarationImpl>) properties.get(key);
ArrayNode timerDeclarationArray = new ObjectMapper().createArrayNode();
if (timerDeclarations != null)
for (TimerDeclarationImpl timerDeclaration : timerDeclarations) {
ObjectNode timerDeclarationJSON = new ObjectMapper().createObjectNode();
timerDeclarationJSON.put("isExclusive", timerDeclaration.isExclusive());
if (timerDeclaration.getRepeat() != null)
timerDeclarationJSON.put("repeat", timerDeclaration.getRepeat());
timerDeclarationJSON.put("retries", String.valueOf(timerDeclaration.getRetries()));
timerDeclarationJSON.put("type", timerDeclaration.getJobHandlerType());
timerDeclarationJSON.put("configuration", timerDeclaration.getJobHandlerConfiguration());
//timerDeclarationJSON.put("expression", timerDeclaration.getDescription());
timerDeclarationArray.add(timerDeclarationJSON);
}
if (timerDeclarationArray.size() > 0)
propertiesJSON.put(key, timerDeclarationArray);
// TODO: implement getting description
} else if ("eventDefinitions".equals(key)) {
ArrayList<EventSubscriptionDeclaration> eventDefinitions = (ArrayList<EventSubscriptionDeclaration>) properties.get(key);
ArrayNode eventDefinitionsArray = new ObjectMapper().createArrayNode();
if (eventDefinitions != null) {
for (EventSubscriptionDeclaration eventDefinition : eventDefinitions) {
ObjectNode eventDefinitionJSON = new ObjectMapper().createObjectNode();
if (eventDefinition.getActivityId() != null)
eventDefinitionJSON.put("activityId",eventDefinition.getActivityId());
eventDefinitionJSON.put("eventName", eventDefinition.getEventName());
eventDefinitionJSON.put("eventType", eventDefinition.getEventType());
eventDefinitionJSON.put("isAsync", eventDefinition.isAsync());
eventDefinitionJSON.put("isStartEvent", eventDefinition.isStartEvent());
eventDefinitionsArray.add(eventDefinitionJSON);
}
}
if (eventDefinitionsArray.size() > 0)
propertiesJSON.put(key, eventDefinitionsArray);
// TODO: implement it
} else if ("errorEventDefinitions".equals(key)) {
ArrayList<ErrorEventDefinition> errorEventDefinitions = (ArrayList<ErrorEventDefinition>) properties.get(key);
ArrayNode errorEventDefinitionsArray = new ObjectMapper().createArrayNode();
if (errorEventDefinitions != null) {
for (ErrorEventDefinition errorEventDefinition : errorEventDefinitions) {
ObjectNode errorEventDefinitionJSON = new ObjectMapper().createObjectNode();
if (errorEventDefinition.getErrorCode() != null)
errorEventDefinitionJSON.put("errorCode", errorEventDefinition.getErrorCode());
else
errorEventDefinitionJSON.putNull("errorCode");
errorEventDefinitionJSON.put("handlerActivityId",
errorEventDefinition.getHandlerActivityId());
errorEventDefinitionsArray.add(errorEventDefinitionJSON);
}
}
if (errorEventDefinitionsArray.size() > 0)
propertiesJSON.put(key, errorEventDefinitionsArray);
}
}
if ("callActivity".equals(properties.get("type"))) {
CallActivityBehavior callActivityBehavior = null;
if (activityBehavior instanceof CallActivityBehavior) {
callActivityBehavior = (CallActivityBehavior) activityBehavior;
}
if (callActivityBehavior != null) {
propertiesJSON.put("processDefinitonKey", callActivityBehavior.getProcessDefinitonKey());
// get processDefinitonId from execution or get last processDefinitonId
// by key
ArrayNode processInstanceArray = new ObjectMapper().createArrayNode();
if (processInstance != null) {
List<Execution> executionList = runtimeService.createExecutionQuery()
.processInstanceId(processInstanceId)
.activityId(activity.getId()).list();
if (!executionList.isEmpty()) {
for (Execution execution : executionList) {
ObjectNode processInstanceJSON = subProcessInstanceMap.get(execution.getId());
processInstanceArray.add(processInstanceJSON);
}
}
}
// If active activities nas no instance of this callActivity then add
// last definition
if (processInstanceArray.size() == 0 && StringUtils.isNotEmpty(callActivityBehavior.getProcessDefinitonKey())) {
// Get last definition by key
ProcessDefinition lastProcessDefinition = repositoryService
.createProcessDefinitionQuery()
.processDefinitionKey(callActivityBehavior.getProcessDefinitonKey())
.latestVersion().singleResult();
// TODO: unuseful fields there are processDefinitionName, processDefinitionKey
if (lastProcessDefinition != null) {
ObjectNode processInstanceJSON = new ObjectMapper().createObjectNode();
processInstanceJSON.put("processDefinitionId", lastProcessDefinition.getId());
processInstanceJSON.put("processDefinitionKey", lastProcessDefinition.getKey());
processInstanceJSON.put("processDefinitionName", lastProcessDefinition.getName());
processInstanceArray.add(processInstanceJSON);
}
}
if (processInstanceArray.size() > 0) {
propertiesJSON.put("processDefinitons", processInstanceArray);
}
}
}
activityJSON.put("activityId", activity.getId());
activityJSON.put("properties", propertiesJSON);
if (multiInstance != null)
activityJSON.put("multiInstance", multiInstance);
if (collapsed)
activityJSON.put("collapsed", collapsed);
if (nestedActivityArray.size() > 0)
activityJSON.put("nestedActivities", nestedActivityArray);
if (isInterrupting != null)
activityJSON.put("isInterrupting", isInterrupting);
activityJSON.put("x", activity.getX());
activityJSON.put("y", activity.getY());
activityJSON.put("width", activity.getWidth());
activityJSON.put("height", activity.getHeight());
activityArray.add(activityJSON);
// Nested activities (boundary events)
for (ActivityImpl nestedActivity : activity.getActivities()) {
getActivity(processInstanceId, nestedActivity, activityArray, sequenceFlowArray,
processInstance, highLightedFlows, subProcessInstanceMap);
}
}
private JsonNode getProcessDefinitionResponse(ProcessDefinitionEntity processDefinition) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode pdrJSON = mapper.createObjectNode();
pdrJSON.put("id", processDefinition.getId());
pdrJSON.put("name", processDefinition.getName());
pdrJSON.put("key", processDefinition.getKey());
pdrJSON.put("version", processDefinition.getVersion());
pdrJSON.put("deploymentId", processDefinition.getDeploymentId());
pdrJSON.put("isGraphicNotationDefined", isGraphicNotationDefined(processDefinition));
return pdrJSON;
}
private boolean isGraphicNotationDefined(ProcessDefinitionEntity processDefinition) {
return ((ProcessDefinitionEntity) repositoryService
.getProcessDefinition(processDefinition.getId()))
.isGraphicalNotationDefined();
}
}
| apache-2.0 |
MegatronKing/SVG-Android | svg-iconlibs/action/src/main/java/com/github/megatronking/svg/iconlibs/ic_lightbulb_outline.java | 2892 | package com.github.megatronking.svg.iconlibs;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import com.github.megatronking.svg.support.SVGRenderer;
/**
* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* SVG-Generator. It should not be modified by hand.
*/
public class ic_lightbulb_outline extends SVGRenderer {
public ic_lightbulb_outline(Context context) {
super(context);
mAlpha = 1.0f;
mWidth = dip2px(24.0f);
mHeight = dip2px(24.0f);
}
@Override
public void render(Canvas canvas, int w, int h, ColorFilter filter) {
final float scaleX = w / 24.0f;
final float scaleY = h / 24.0f;
mPath.reset();
mRenderPath.reset();
mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f});
mFinalPathMatrix.postScale(scaleX, scaleY);
mPath.moveTo(9.0f, 21.0f);
mPath.rCubicTo(0.0f, 0.55f, 0.45f, 1.0f, 1.0f, 1.0f);
mPath.rLineTo(4.0f, 0f);
mPath.rCubicTo(0.55f, 0.0f, 1.0f, -0.45f, 1.0f, -1.0f);
mPath.rLineTo(0f, -1.0f);
mPath.lineTo(9.0f, 20.0f);
mPath.rLineTo(0f, 1.0f);
mPath.close();
mPath.moveTo(9.0f, 21.0f);
mPath.rMoveTo(3.0f, -19.0f);
mPath.cubicTo(8.14f, 2.0f, 5.0f, 5.14f, 5.0f, 9.0f);
mPath.rCubicTo(0.0f, 2.38f, 1.19f, 4.47f, 3.0f, 5.74f);
mPath.lineTo(8.0f, 17.0f);
mPath.rCubicTo(0.0f, 0.55f, 0.45f, 1.0f, 1.0f, 1.0f);
mPath.rLineTo(6.0f, 0f);
mPath.rCubicTo(0.55f, 0.0f, 1.0f, -0.45f, 1.0f, -1.0f);
mPath.rLineTo(0f, -2.26f);
mPath.rCubicTo(1.81f, -1.27f, 3.0f, -3.36f, 3.0f, -5.74f);
mPath.rCubicTo(0.0f, -3.86f, -3.14f, -7.0f, -7.0f, -7.0f);
mPath.close();
mPath.moveTo(12.0f, 2.0f);
mPath.rMoveTo(2.85f, 11.1f);
mPath.rLineTo(-0.85f, 0.6f);
mPath.lineTo(14.0f, 16.0f);
mPath.rLineTo(-4.0f, 0f);
mPath.rLineTo(0f, -2.3f);
mPath.rLineTo(-0.85f, -0.6f);
mPath.cubicTo(7.8f, 12.16f, 7.0f, 10.63f, 7.0f, 9.0f);
mPath.rCubicTo(0.0f, -2.76f, 2.24f, -5.0f, 5.0f, -5.0f);
mPath.rCubicTo(2.7600002f, 0.0f, 5.0f, 2.24f, 5.0f, 5.0f);
mPath.rCubicTo(0.0f, 1.63f, -0.8f, 3.16f, -2.15f, 4.1f);
mPath.close();
mPath.moveTo(14.85f, 13.1f);
mRenderPath.addPath(mPath, mFinalPathMatrix);
if (mFillPaint == null) {
mFillPaint = new Paint();
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
}
mFillPaint.setColor(applyAlpha(-16777216, 1.0f));
mFillPaint.setColorFilter(filter);
canvas.drawPath(mRenderPath, mFillPaint);
}
} | apache-2.0 |
youdonghai/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamToLoop/beforeCollectExtendsGroupingBy.java | 704 | // "Replace Stream API chain with loop" "true"
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
static class MyList<T, X> extends ArrayList<X> {}
public List<CharSequence> getList() {
return Collections.emptyList();
}
public MyList<? extends Number, CharSequence> createList() {
return new MyList<>();
}
private void collect() {
Map<Integer, ? extends MyList<? extends Number, ? extends CharSequence>> map =
getList().stream().co<caret>llect(Collectors.groupingBy(x -> x.length(), Collectors.toCollection(this::createList)));
System.out.println(map);
}
| apache-2.0 |
LittleLazyCat/TXEYXXK | jeesite/src/main/java/com/jeesite/modules/txey/dao/PatientDao.java | 380 | package com.jeesite.modules.txey.dao;
import com.jeesite.common.persistence.annotation.MyBatisDao;
import com.jeesite.modules.txey.entity.Patient;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@MyBatisDao
public interface PatientDao {
@Select("select brxm,csny,sfzh from zy_brry where brxm like '张守威'")
public List<Patient> getPatient();
}
| apache-2.0 |
GerritCodeReview/gerrit | java/com/google/gerrit/server/restapi/account/GetAgreements.java | 4833 | // Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.restapi.account;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.entities.AccountGroup;
import com.google.gerrit.entities.ContributorAgreement;
import com.google.gerrit.entities.PermissionRule;
import com.google.gerrit.entities.PermissionRule.Action;
import com.google.gerrit.extensions.common.AgreementInfo;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.MethodNotAllowedException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.account.AccountResource;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.permissions.GlobalPermission;
import com.google.gerrit.server.permissions.PermissionBackend;
import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.restapi.config.AgreementJson;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.jgit.lib.Config;
/**
* REST endpoint to get all contributor agreements that have been signed by an account.
*
* <p>This REST endpoint handles {@code GET /accounts/<account-identifier>/agreements} requests.
*
* <p>Contributor agreements are only available if contributor agreements have been enabled in
* {@code gerrit.config} (see {@code auth.contributorAgreements}).
*/
@Singleton
public class GetAgreements implements RestReadView<AccountResource> {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final Provider<CurrentUser> self;
private final ProjectCache projectCache;
private final AgreementJson agreementJson;
private final boolean agreementsEnabled;
private final PermissionBackend permissionBackend;
@Inject
GetAgreements(
Provider<CurrentUser> self,
ProjectCache projectCache,
AgreementJson agreementJson,
PermissionBackend permissionBackend,
@GerritServerConfig Config config) {
this.self = self;
this.projectCache = projectCache;
this.agreementJson = agreementJson;
this.agreementsEnabled = config.getBoolean("auth", "contributorAgreements", false);
this.permissionBackend = permissionBackend;
}
@Override
public Response<List<AgreementInfo>> apply(AccountResource resource)
throws RestApiException, PermissionBackendException {
if (!agreementsEnabled) {
throw new MethodNotAllowedException("contributor agreements disabled");
}
if (!self.get().isIdentifiedUser()) {
throw new AuthException("not allowed to get contributor agreements");
}
IdentifiedUser user = self.get().asIdentifiedUser();
if (user != resource.getUser()) {
try {
permissionBackend.user(user).check(GlobalPermission.ADMINISTRATE_SERVER);
} catch (AuthException e) {
throw new AuthException("not allowed to get contributor agreements", e);
}
}
List<AgreementInfo> results = new ArrayList<>();
Collection<ContributorAgreement> cas =
projectCache.getAllProjects().getConfig().getContributorAgreements().values();
for (ContributorAgreement ca : cas) {
List<AccountGroup.UUID> groupIds = new ArrayList<>();
for (PermissionRule rule : ca.getAccepted()) {
if ((rule.getAction() == Action.ALLOW) && (rule.getGroup() != null)) {
if (rule.getGroup().getUUID() != null) {
groupIds.add(rule.getGroup().getUUID());
} else {
logger.atWarning().log(
"group \"%s\" does not exist, referenced in CLA \"%s\"",
rule.getGroup().getName(), ca.getName());
}
}
}
if (user.getEffectiveGroups().containsAnyOf(groupIds)) {
results.add(agreementJson.format(ca));
}
}
return Response.ok(results);
}
}
| apache-2.0 |
maloubobola/Udacity | SuperDuo/alexandria/app/src/androidTest/java/it/jaschke/alexandria/TestProvider.java | 7474 | package it.jaschke.alexandria;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
import it.jaschke.alexandria.contract.DatabaseContract;
/**
* Created by saj on 23/12/14.
*/
public class TestProvider extends AndroidTestCase {
public static final String LOG_TAG = TestProvider.class.getSimpleName();
public void setUp() {
deleteAllRecords();
}
public void deleteAllRecords() {
mContext.getContentResolver().delete(
DatabaseContract.BookEntry.CONTENT_URI,
null,
null
);
mContext.getContentResolver().delete(
DatabaseContract.CategoryEntry.CONTENT_URI,
null,
null
);
mContext.getContentResolver().delete(
DatabaseContract.AuthorEntry.CONTENT_URI,
null,
null
);
Cursor cursor = mContext.getContentResolver().query(
DatabaseContract.BookEntry.CONTENT_URI,
null,
null,
null,
null
);
assertEquals(0, cursor.getCount());
cursor.close();
cursor = mContext.getContentResolver().query(
DatabaseContract.AuthorEntry.CONTENT_URI,
null,
null,
null,
null
);
assertEquals(0, cursor.getCount());
cursor.close();
cursor = mContext.getContentResolver().query(
DatabaseContract.CategoryEntry.CONTENT_URI,
null,
null,
null,
null
);
assertEquals(0, cursor.getCount());
cursor.close();
}
public void testGetType() {
String type = mContext.getContentResolver().getType(DatabaseContract.BookEntry.CONTENT_URI);
assertEquals(DatabaseContract.BookEntry.CONTENT_TYPE, type);
type = mContext.getContentResolver().getType(DatabaseContract.AuthorEntry.CONTENT_URI);
assertEquals(DatabaseContract.AuthorEntry.CONTENT_TYPE, type);
type = mContext.getContentResolver().getType(DatabaseContract.CategoryEntry.CONTENT_URI);
assertEquals(DatabaseContract.CategoryEntry.CONTENT_TYPE, type);
long id = 9780137903955L;
type = mContext.getContentResolver().getType(DatabaseContract.BookEntry.buildBookUri(id));
assertEquals(DatabaseContract.BookEntry.CONTENT_ITEM_TYPE, type);
type = mContext.getContentResolver().getType(DatabaseContract.BookEntry.buildFullBookUri(id));
assertEquals(DatabaseContract.BookEntry.CONTENT_ITEM_TYPE, type);
type = mContext.getContentResolver().getType(DatabaseContract.AuthorEntry.buildAuthorUri(id));
assertEquals(DatabaseContract.AuthorEntry.CONTENT_ITEM_TYPE, type);
type = mContext.getContentResolver().getType(DatabaseContract.CategoryEntry.buildCategoryUri(id));
assertEquals(DatabaseContract.CategoryEntry.CONTENT_ITEM_TYPE, type);
}
public void testInsertRead(){
insertReadBook();
insertReadAuthor();
insertReadCategory();
readFullBook();
readFullList();
}
public void insertReadBook(){
ContentValues bookValues = TestDb.getBookValues();
Uri bookUri = mContext.getContentResolver().insert(DatabaseContract.BookEntry.CONTENT_URI, bookValues);
long bookRowId = ContentUris.parseId(bookUri);
assertTrue(bookRowId != -1);
Cursor cursor = mContext.getContentResolver().query(
DatabaseContract.BookEntry.CONTENT_URI,
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestDb.validateCursor(cursor, bookValues);
cursor = mContext.getContentResolver().query(
DatabaseContract.BookEntry.buildBookUri(bookRowId),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestDb.validateCursor(cursor, bookValues);
}
public void insertReadAuthor(){
ContentValues authorValues = TestDb.getAuthorValues();
Uri authorUri = mContext.getContentResolver().insert(DatabaseContract.AuthorEntry.CONTENT_URI, authorValues);
long authorRowId = ContentUris.parseId(authorUri);
assertTrue(authorRowId != -1);
assertEquals(authorRowId,TestDb.ean);
Cursor cursor = mContext.getContentResolver().query(
DatabaseContract.AuthorEntry.CONTENT_URI,
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestDb.validateCursor(cursor, authorValues);
cursor = mContext.getContentResolver().query(
DatabaseContract.AuthorEntry.buildAuthorUri(authorRowId),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestDb.validateCursor(cursor, authorValues);
}
public void insertReadCategory(){
ContentValues categoryValues = TestDb.getCategoryValues();
Uri categoryUri = mContext.getContentResolver().insert(DatabaseContract.CategoryEntry.CONTENT_URI, categoryValues);
long categoryRowId = ContentUris.parseId(categoryUri);
assertTrue(categoryRowId != -1);
assertEquals(categoryRowId,TestDb.ean);
Cursor cursor = mContext.getContentResolver().query(
DatabaseContract.CategoryEntry.CONTENT_URI,
null, // projection
null, // selection
null, // selection args
null // sort order
);
TestDb.validateCursor(cursor, categoryValues);
cursor = mContext.getContentResolver().query(
DatabaseContract.CategoryEntry.buildCategoryUri(categoryRowId),
null, // projection
null, // selection
null, // selection args
null // sort order
);
TestDb.validateCursor(cursor, categoryValues);
}
public void readFullBook(){
Cursor cursor = mContext.getContentResolver().query(
DatabaseContract.BookEntry.buildFullBookUri(TestDb.ean),
null, // projection
null, // selection
null, // selection args
null // sort order
);
TestDb.validateCursor(cursor, TestDb.getFullDetailValues());
}
public void readFullList(){
Cursor cursor = mContext.getContentResolver().query(
DatabaseContract.BookEntry.FULL_CONTENT_URI,
null, // projection
null, // selection
null, // selection args
null // sort order
);
TestDb.validateCursor(cursor, TestDb.getFullListValues());
}
} | apache-2.0 |
kostarion/DataAccessObject | my_steps/src/classes/Employee.java | 350 | package classes;
import annotations.KeyField;
import annotations.TaggedObject;
@TaggedObject(name = "Workers")
public class Employee {
@KeyField
int id;
String name;
String position;
public Employee () {
}
public Employee (int i, String n, String p) {
id = i;
name = n;
position = p;
}
}
| apache-2.0 |
spohnan/geowave | core/cli/src/main/java/org/locationtech/geowave/core/cli/utils/FileUtils.java | 3251 | /**
* Copyright (c) 2013-2019 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
/** */
package org.locationtech.geowave.core.cli.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import com.beust.jcommander.ParameterException;
/** Common file utilities, for performing common operations */
public class FileUtils {
/**
* Method to format file paths, similar to how command-line substitutions will function. For
* example, we want to substitute '~' for a user's home directory, or environment variables
*
* @param filePath
* @return
*/
public static String formatFilePath(String filePath) {
if (filePath != null) {
if (filePath.indexOf("~") != -1) {
filePath = filePath.replace("~", System.getProperty("user.home", "~"));
}
if (filePath.indexOf("$") != -1) {
int startIndex = 0;
while ((startIndex != -1) && (filePath.indexOf("$", startIndex) != -1)) {
final String variable = getVariable(filePath.substring(startIndex));
final String resolvedValue = resolveVariableValue(variable);
// if variable was not resolved to a system property, no
// need to perform string replace
if (!variable.equals(resolvedValue)) {
filePath = filePath.replace(variable, resolvedValue);
}
startIndex = filePath.indexOf("$", (startIndex + 1));
}
}
}
return filePath;
}
/**
* If an environment variable, or something resembling one, is detected - i.e. starting with '$',
* try to resolve it's actual value for resolving a path
*
* @param variable
* @return
*/
private static String getVariable(final String variable) {
final StringBuilder sb = new StringBuilder();
char nextChar;
for (int index = 0; index < variable.length(); index++) {
nextChar = variable.charAt(index);
if ((nextChar == '$')
|| Character.isLetterOrDigit(nextChar)
|| (nextChar != File.separatorChar)) {
sb.append(nextChar);
} else {
break;
}
}
return sb.toString();
}
private static String resolveVariableValue(final String variable) {
if (System.getenv().containsKey(variable)) {
return System.getenv(variable);
} else if (System.getProperties().containsKey(variable)) {
return System.getProperty(variable);
}
return variable;
}
/**
* Reads the content of a file
*
* @param inputFile
* @return
*/
public static String readFileContent(final File inputFile) throws Exception {
Scanner scanner = null;
try {
scanner = new Scanner(inputFile, "UTF-8");
return scanner.nextLine();
} catch (final FileNotFoundException e) {
throw new ParameterException(e);
} finally {
if (scanner != null) {
scanner.close();
}
}
}
}
| apache-2.0 |
gin-fizz/pollistics | src/test/java/com/pollistics/models/validators/UserValidatorTest.java | 2570 | package com.pollistics.models.validators;
import static org.junit.Assert.*;
import org.junit.Test;
import com.pollistics.models.User;
import org.springframework.validation.DirectFieldBindingResult;
public class UserValidatorTest {
@Test
public void validateUsernameTest() {
User user = new User();
DirectFieldBindingResult errors = new DirectFieldBindingResult(user, "user");
UserValidator userValidator = new UserValidator();
user.setUsername("valid_user"); // valid
user.setPassword("ValidPass123");
userValidator.validate(user, errors);
assertFalse(errors.hasErrors());
user.setUsername("el"); // too short
userValidator.validate(user, errors);
assertTrue(errors.hasFieldErrors("username"));
errors = new DirectFieldBindingResult(user, "user");
user.setUsername("qwertyuiopasdfghjklzxcvnbm"); // too long
userValidator.validate(user, errors);
assertTrue(errors.hasFieldErrors("username"));
errors = new DirectFieldBindingResult(user, "user");
user.setUsername("user*name"); // only _. special chars
userValidator.validate(user, errors);
assertTrue(errors.hasFieldErrors("username"));
errors = new DirectFieldBindingResult(user, "user");
user.setUsername("username_"); // no ._ at the start or end
userValidator.validate(user, errors);
assertTrue(errors.hasFieldErrors("username"));
errors = new DirectFieldBindingResult(user, "user");
user.setUsername("user..name"); // no 2 signs in sequence
userValidator.validate(user, errors);
assertTrue(errors.hasFieldErrors("username"));
}
@Test
public void validatePasswordTest() {
User user = new User();
DirectFieldBindingResult errors = new DirectFieldBindingResult(user, "user");
UserValidator userValidator = new UserValidator();
user.setUsername("valid_user");
user.setPassword("Testje1"); // too short
userValidator.validate(user, errors);
assertTrue(errors.hasFieldErrors("password"));
errors = new DirectFieldBindingResult(user, "user");
user.setPassword("TestTestTest"); // no number
userValidator.validate(user, errors);
assertTrue(errors.hasFieldErrors("password"));
errors = new DirectFieldBindingResult(user, "user");
user.setPassword("testtest123"); // no uppercase letter
userValidator.validate(user, errors);
assertTrue(errors.hasFieldErrors("password"));
errors = new DirectFieldBindingResult(user, "user");
user.setPassword("TESTTEST123"); // no lowercase character
userValidator.validate(user, errors);
assertTrue(errors.hasFieldErrors("password"));
}
}
| apache-2.0 |
kucera-jan-cz/kickshare | kickshare-rest/kickshare-rest/src/main/java/com/github/kickshare/service/impl/SchedulingService.java | 2333 | package com.github.kickshare.service.impl;
import java.io.IOException;
import java.util.List;
import com.github.kickshare.common.io.ResourceUtil;
import com.github.kickshare.db.jooq.Tables;
import com.github.kickshare.db.jooq.enums.TokenTypeDB;
import com.github.kickshare.db.jooq.tables.TokenRequestDB;
import com.github.kickshare.gmail.GMailService;
import org.jooq.DSLContext;
import org.jooq.Record1;
import org.jooq.ResultQuery;
import org.springframework.scheduling.annotation.Scheduled;
/**
* @author Jan.Kucera
* @since 29.9.2017
*/
public class SchedulingService {
private DSLContext dsl;
private GMailService gmailService;
private MailService mailService;
private ResultQuery<Record1<String>> generatedPasswordQuery = dsl.select(Tables.TOKEN_REQUEST.TOKEN)
.from(TokenRequestDB.TOKEN_REQUEST)
.where(TokenRequestDB.TOKEN_REQUEST.TOKEN_TYPE.eq(TokenTypeDB.PASSWORD_RESET))
.keepStatement(true);
private ResultQuery<Record1<String>> generatedPasswordResetQuery = dsl.select(Tables.TOKEN_REQUEST.TOKEN)
.from(TokenRequestDB.TOKEN_REQUEST)
.where(TokenRequestDB.TOKEN_REQUEST.TOKEN_TYPE.eq(TokenTypeDB.PASSWORD_MAIL))
.keepStatement(true);
@Scheduled(cron = "* * * * * *")
public void deleteDeprecatedTokens() {
//@TODO - add insert time to records and consider token as id??
}
@Scheduled(cron = "* * * * * *")
public void sendPasswordResetLinks() {
final List<String> tokens = generatedPasswordQuery.fetchInto(String.class);
for (String token : tokens) {
mailService.resetPassword(token);
}
}
@Scheduled(cron = "* * * * * *")
public void sendGeneratedPasswords() {
final List<String> tokens = generatedPasswordQuery.fetchInto(String.class);
for (String token : tokens) {
mailService.resetPassword(token);
}
}
//@TODO - implement rating calculations
public void updateLeaderRatings() throws IOException {
String sql = ResourceUtil.toString("db/sql/update_leader_rating.sql");
this.dsl.execute(sql);
}
public void updateBackerRatings() throws IOException {
String sql = ResourceUtil.toString("db/sql/update_backer_rating.sql");
this.dsl.execute(sql);
}
}
| apache-2.0 |
Banno/sbt-plantuml-plugin | src/main/java/net/sourceforge/plantuml/code/CompressionNone.java | 1127 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.code;
public class CompressionNone implements Compression {
public byte[] compress(byte[] in) {
return in;
}
public byte[] decompress(byte[] in) {
return in;
}
}
| apache-2.0 |
opetrovski/development | oscm-billing/javasrc/org/oscm/billingservice/business/model/suppliershare/BrokerRevenue.java | 3004 | /*******************************************************************************
* Copyright FUJITSU LIMITED 2017
*******************************************************************************/
package org.oscm.billingservice.business.model.suppliershare;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.oscm.billingservice.business.BigDecimalAdapter;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BrokerRevenue")
public class BrokerRevenue {
@XmlAttribute(name = "serviceRevenue")
@XmlJavaTypeAdapter(BigDecimalAdapter.class)
protected BigDecimal serviceRevenue;
@XmlAttribute(name = "marketplaceRevenue", required = true)
@XmlJavaTypeAdapter(BigDecimalAdapter.class)
protected BigDecimal marketplaceRevenue;
@XmlAttribute(name = "operatorRevenue", required = true)
@XmlJavaTypeAdapter(BigDecimalAdapter.class)
protected BigDecimal operatorRevenue;
@XmlAttribute(name = "brokerRevenue", required = true)
@XmlJavaTypeAdapter(BigDecimalAdapter.class)
protected BigDecimal brokerRevenue;
public BigDecimal getServiceRevenue() {
return serviceRevenue;
}
public void setServiceRevenue(BigDecimal serviceRevenue) {
this.serviceRevenue = serviceRevenue;
}
public BigDecimal getMarketplaceRevenue() {
return marketplaceRevenue;
}
public void setMarketplaceRevenue(BigDecimal marketplaceRevenue) {
this.marketplaceRevenue = marketplaceRevenue;
}
public BigDecimal getOperatorRevenue() {
return operatorRevenue;
}
public void setOperatorRevenue(BigDecimal value) {
this.operatorRevenue = value;
}
public BigDecimal getBrokerRevenue() {
return brokerRevenue;
}
public void setBrokerRevenue(BigDecimal brokerRevenue) {
this.brokerRevenue = brokerRevenue;
}
public void sumServiceRevenue(BigDecimal valueToAdd) {
if (serviceRevenue == null) {
serviceRevenue = BigDecimal.ZERO;
}
this.serviceRevenue = serviceRevenue.add(valueToAdd);
}
public void sumMarketplaceRevenue(BigDecimal valueToAdd) {
if (marketplaceRevenue == null) {
marketplaceRevenue = BigDecimal.ZERO;
}
this.marketplaceRevenue = marketplaceRevenue.add(valueToAdd);
}
public void sumOperatorRevenue(BigDecimal valueToAdd) {
if (operatorRevenue == null) {
operatorRevenue = BigDecimal.ZERO;
}
this.operatorRevenue = operatorRevenue.add(valueToAdd);
}
public void sumBrokerRevenue(BigDecimal valueToAdd) {
if (brokerRevenue == null) {
brokerRevenue = BigDecimal.ZERO;
}
this.brokerRevenue = brokerRevenue.add(valueToAdd);
}
}
| apache-2.0 |
nik1202/EduProject | chapter_009/src/main/java/ru/crud2/model/Role.java | 178 | package ru.crud2.model;
/**
* Created by nikolay on 14/09/17.
*/
public enum Role {
/**
* Admin role.
*/
Admin,
/**
* User role.
*/
User
}
| apache-2.0 |
tiobe/closure-compiler | test/com/google/javascript/jscomp/DefaultNameGeneratorTest.java | 6577 | /*
* Copyright 2005 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class DefaultNameGeneratorTest extends TestCase {
private static final ImmutableSet<String> RESERVED_NAMES = ImmutableSet.of("ba", "xba");
private static String[] generate(
DefaultNameGenerator ng, String prefix, int num) throws Exception {
String[] result = new String[num];
for (int i = 0; i < num; i++) {
result[i] = ng.generateNextName();
if (!result[i].startsWith(prefix)) {
assertWithMessage("Error: " + result[i]).fail();
}
}
return result;
}
@Test
public void testNameGeneratorInvalidPrefixes() throws Exception {
try {
new DefaultNameGenerator(Collections.<String>emptySet(), "123abc", null);
assertWithMessage(
"Constructor should throw exception when the first char of prefix is invalid")
.fail();
} catch (IllegalArgumentException ex) {
// The error messages should contain meaningful information.
assertThat(ex).hasMessageThat().contains("W, X, Y, Z, $]");
}
try {
new DefaultNameGenerator(Collections.<String>emptySet(), "abc%", null);
assertWithMessage(
"Constructor should throw exception when one of prefix characters is invalid")
.fail();
} catch (IllegalArgumentException ex) {
assertThat(ex).hasMessageThat().contains("W, X, Y, Z, _, 0, 1");
}
}
@Test
public void testGenerate() throws Exception {
DefaultNameGenerator ng = new DefaultNameGenerator(
RESERVED_NAMES, "", null);
String[] result = generate(ng, "", 106);
assertThat(result[0]).isEqualTo("a");
assertThat(result[25]).isEqualTo("z");
assertThat(result[26]).isEqualTo("A");
assertThat(result[51]).isEqualTo("Z");
assertThat(result[52]).isEqualTo("$");
assertThat(result[53]).isEqualTo("aa");
// ba is reserved
assertThat(result[54]).isEqualTo("ca");
assertThat(result[104]).isEqualTo("$a");
ng = new DefaultNameGenerator(RESERVED_NAMES, "x", null);
result = generate(ng, "x", 132);
// Expected: x, xa, ..., x$, xaa, ..., x$$
assertThat(result[0]).isEqualTo("x");
assertThat(result[1]).isEqualTo("xa");
assertThat(result[64]).isEqualTo("x$");
assertThat(result[65]).isEqualTo("xaa");
// xba is reserved
assertThat(result[66]).isEqualTo("xca");
}
@Test
public void testReserve() throws Exception {
DefaultNameGenerator ng = new DefaultNameGenerator(
RESERVED_NAMES, "", new char[] {'$'});
String[] result = generate(ng, "", 106);
assertThat(result[0]).isEqualTo("a");
assertThat(result[25]).isEqualTo("z");
assertThat(result[26]).isEqualTo("A");
assertThat(result[51]).isEqualTo("Z");
assertThat(result[52]).isEqualTo("aa");
// ba is reserved
assertThat(result[53]).isEqualTo("ca");
assertThat(result[103]).isEqualTo("ab");
}
@Test
public void testGenerateWithPriority1() throws Exception {
DefaultNameGenerator ng = new DefaultNameGenerator(
RESERVED_NAMES, "", null);
String[] result = generate(ng, "", 106);
assertThat(result[0]).isEqualTo("a");
assertThat(result[25]).isEqualTo("z");
assertThat(result[26]).isEqualTo("A");
assertThat(result[51]).isEqualTo("Z");
assertThat(result[52]).isEqualTo("$");
assertThat(result[53]).isEqualTo("aa");
ng.favors("b");
ng.reset(RESERVED_NAMES, "", null);
result = generate(ng, "", 106);
assertThat(result[0]).isEqualTo("b");
assertThat(result[1]).isEqualTo("a");
assertThat(result[2]).isEqualTo("c");
assertThat(result[3]).isEqualTo("d");
ng.favors("cc");
ng.reset(RESERVED_NAMES, "", null);
result = generate(ng, "", 106);
assertThat(result[0]).isEqualTo("c");
assertThat(result[1]).isEqualTo("b");
assertThat(result[2]).isEqualTo("a");
assertThat(result[3]).isEqualTo("d");
}
@Test
public void testGenerateWithPriority2() throws Exception {
DefaultNameGenerator ng = new DefaultNameGenerator(
RESERVED_NAMES, "", null);
String[] result = generate(ng, "", 106);
assertThat(result[0]).isEqualTo("a");
assertThat(result[25]).isEqualTo("z");
assertThat(result[26]).isEqualTo("A");
assertThat(result[51]).isEqualTo("Z");
assertThat(result[52]).isEqualTo("$");
assertThat(result[53]).isEqualTo("aa");
ng.favors("function");
ng.favors("function");
ng.favors("function");
ng.reset(RESERVED_NAMES, "", null);
result = generate(ng, "", 106);
// All the letters of function should come first. In alphabetical order.
assertThat(result[0]).isEqualTo("n");
assertThat(result[1]).isEqualTo("c");
assertThat(result[2]).isEqualTo("f");
assertThat(result[3]).isEqualTo("i");
assertThat(result[4]).isEqualTo("o");
assertThat(result[5]).isEqualTo("t");
assertThat(result[6]).isEqualTo("u");
// Back to normal.
assertThat(result[7]).isEqualTo("a");
assertThat(result[8]).isEqualTo("b");
// c has been prioritized.
assertThat(result[9]).isEqualTo("d");
assertThat(result[10]).isEqualTo("e");
// This used to start with 'aa' but now n is prioritized over it.
assertThat(result[53]).isEqualTo("nn");
assertThat(result[54]).isEqualTo("cn");
}
@Test
public void testGenerateWithPriority3() throws Exception {
DefaultNameGenerator ng = new DefaultNameGenerator(
RESERVED_NAMES, "", null);
String[] result = generate(ng, "", 106);
ng.favors("???");
ng.reset(RESERVED_NAMES, "", null);
result = generate(ng, "", 106);
assertThat(result[0]).isEqualTo("a");
}
}
| apache-2.0 |
Top-Q/jsystem | jsystem-core-projects/jsystemCore/src/main/java/jsystem/framework/report/DefaultReporterImpl.java | 7160 | /*
* Created on 28/07/2006
*
* Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved.
*/
package jsystem.framework.report;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import jsystem.framework.FrameworkOptions;
import jsystem.framework.JSystemProperties;
import jsystem.framework.common.CommonResources;
import jsystem.utils.FileUtils;
import jsystem.utils.StringUtils;
import junit.framework.JSystemJUnit4ClassRunner;
import junit.framework.SystemTest;
import junit.framework.Test;
public abstract class DefaultReporterImpl implements Reporter {
private Logger log = Logger.getLogger(DefaultReporterImpl.class.getName());
protected boolean failToWarning = false;
protected boolean failToPass = false;
protected String date = null;
protected Test currentTest = null;
protected SystemTest systemTest;
protected boolean printBufferdReportsInRunTime = false;
/**
* Used to buffer reports when startBufferReports is called
*/
protected ArrayList<ReportElement> reportsBuffer = null;
protected boolean buffering = false;
public void report(String title, String message, boolean status, boolean bold) {
int stat;
if (status) {
stat = Reporter.PASS;
} else {
stat = Reporter.FAIL;
}
report(title, message, stat, bold, false, false, false);
}
public void report(String title, String message, boolean status) {
report(title, message, status, false);
}
public void report(String title, boolean status) {
report(title, null, status);
}
public void report(String title) {
report(title, true);
}
public void step(String stepDescription) {
report(stepDescription, null, Reporter.PASS, false, false, true, false);
}
public void report(String title, Throwable t) {
report(title, StringUtils.getStackTrace(t), false);
}
public void reportHtml(String title, String html, boolean status) {
int stat;
if (status) {
stat = Reporter.PASS;
} else {
stat = Reporter.FAIL;
}
report(title, html, stat, false, true, false, false);
}
public void addLink(String title, String link) {
report(title, link, Reporter.PASS, false, false, false, true);
}
public void report(String title, int status) {
report(title, null, status, false, false, false, false);
}
public void report(String title, String message, int status) {
report(title, message, status, false, false, false, false);
}
public void report(String title, String message, int status, boolean bold) {
report(title, message, status, bold, false, false, false);
}
public void report(String title, String message, int status, boolean bold, boolean html, boolean step, boolean link) {
report(title, message, status, bold, html, step, link, System.currentTimeMillis());
}
public void report(String title, ReportAttribute attribute){
report(title,null, Reporter.PASS, attribute);
}
public void report(String title, String message, ReportAttribute attribute){
report(title,message, Reporter.PASS, attribute);
}
public void report(String title, String message, int status, ReportAttribute attribute){
report(title, message, status, attribute == ReportAttribute.BOLD, attribute == ReportAttribute.HTML, attribute == ReportAttribute.STEP, attribute == ReportAttribute.LINK);
}
public boolean isFailToPass() {
return failToPass;
}
public void setFailToPass(boolean failToPass) {
this.failToPass = failToPass;
}
public boolean isFailToWarning() {
return failToWarning;
}
public void setFailToWarning(boolean failToWarning) {
this.failToWarning = failToWarning;
}
public void startReport(String methodName, String parameters) {
startReport(methodName, parameters, null, null);
}
public synchronized void endReport() {
endReport(null, null);
}
public synchronized String getCurrentTestFolder() {
String logDir = JSystemProperties.getInstance().getPreference(FrameworkOptions.LOG_FOLDER);
String testDir = getValueFromTmpFile("test.dir.last");
if (testDir != null) {
File file = new File(logDir + File.separator + "current" + File.separator + testDir);
if (!file.exists()) {
file.mkdirs();
}
return logDir + File.separator + "current" + File.separator + testDir;
}
return logDir + File.separator + "current";
}
public String getLastReportFile() {
try{
Thread.sleep(200);
}catch (Exception e) {
log.log(Level.WARNING,"Thread sleep interrupted",e);
}
try {
Properties p = FileUtils.loadPropertiesFromFile(CommonResources.TEST_INNER_TEMP_FILENAME);
String value = p.getProperty(CommonResources.LAST_REPORT_NAME);
return value == null? "" : value;
} catch (IOException e) {
log.log(Level.WARNING,"Failed reading last report file name",e);
return "";
}
}
private String getValueFromTmpFile(String key){
Properties currentProperties = new Properties();
try {
currentProperties = FileUtils.loadPropertiesFromFile(CommonResources.TEST_INNER_TEMP_FILENAME);
String value = currentProperties.getProperty(key);
return value;
} catch (Exception e) {
log.warning("couldn't read the "+CommonResources.TEST_INNER_TEMP_FILENAME+" file");
}
return null;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public List<ReportElement> getReportsBuffer() {
return reportsBuffer;
}
public void clearReportsBuffer() {
boolean runGC = (reportsBuffer != null);
reportsBuffer = null;
if(runGC){
System.gc();
}
}
public void startBufferingReports() {
startBufferingReports(printBufferdReportsInRunTime);
}
public void startBufferingReports(boolean printBufferdReportsInRunTime) {
this.printBufferdReportsInRunTime = printBufferdReportsInRunTime;
if (printBufferdReportsInRunTime){
try {
startLevel("Reports in buffer", 0);
} catch (IOException e) {
e.printStackTrace();
}
}
buffering = true;
}
public void startLevel(String level) throws IOException{
startLevel(level, Reporter.CurrentPlace);
}
public void stopBufferingReports() {
buffering = false;
if (printBufferdReportsInRunTime){
try {
stopLevel();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void report(ReportElement report) {
if(report.isStartLevel()){
try {
startLevel(report.getTitle(), report.getLevelPlace());
} catch (IOException e) {
e.printStackTrace();
}
} else if(report.isStopLevel()){
try {
stopLevel();
} catch (IOException e) {
e.printStackTrace();
}
} else {
report(report.getTitle(), report.getMessage(), report.getStatus(), report.isBold(), report.isHtml(), report
.isStep(), report.isLink(), report.getTime());
}
}
protected void updateCurrentTest(Test test){
currentTest = test;
systemTest = null;
if (currentTest instanceof SystemTest){
systemTest = (SystemTest) currentTest;
}else if (currentTest instanceof JSystemJUnit4ClassRunner.TestInfo){
systemTest = ((JSystemJUnit4ClassRunner.TestInfo)currentTest).getSystemTest();
}
}
}
| apache-2.0 |
Muhamedali/crazy_text | src/main/java/com/input/text/crazy/client/utils/Utils.java | 4928 | package com.input.text.crazy.client.utils;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.event.dom.client.KeyCodes;
import com.input.text.crazy.client.widget.textbox.Symbol;
import java.util.Collection;
public final class Utils {
// not the best way, but it should be work correct for more cases
private static native int getDevicePixelRatio() /*-{
return window.devicePixelRatio;
}-*/;
// Test this approach on different platforms and browsers + android/ios devices
// function isHighDensity(){
// return ((window.matchMedia && (window.matchMedia('only screen and (min-resolution: 124dpi), only screen and (min-resolution: 1.3dppx), only screen and (min-resolution: 48.8dpcm)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3)').matches)) || (window.devicePixelRatio && window.devicePixelRatio > 1.3));
// }
//
//
// function isRetina(){
// return ((window.matchMedia && (window.matchMedia('only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx), only screen and (min-resolution: 75.6dpcm)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min--moz-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2)').matches)) || (window.devicePixelRatio && window.devicePixelRatio > 2)) && /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
// }
public static int highResolutionFactor;
static {
highResolutionFactor = getDevicePixelRatio() > 1 ? 2 : 1;
}
public static int resolution(int value) {
return value * highResolutionFactor;
}
public static int symbolWidth(final Context2d context, final String symbol) {
assert context != null;
assert symbol != null;
return (int) Math.round(context.measureText(symbol).getWidth());
}
public static final String UNIT_PX = "px";
// get size from String like "12px"
public static int getSize(String sizeWithUnit) {
assert sizeWithUnit != null;
String[] parts = sizeWithUnit.split(UNIT_PX);
int size = 0;
try {
size = parts.length == 0 ? 0 : Integer.parseInt(parts[0]);
} catch (NumberFormatException e) {
Logger.infoLog("You try to parse integer incorrect value");
}
return size;
}
// 0 .. 32 ascii codes is for non-printing characters
public static final int NON_PRINTING = 32;
public static Rectangle getRectangle(final Symbol symbol) {
assert symbol != null;
Font font = symbol.getFont();
assert font != null;
assert font.getFontMetrics() != null;
return new Rectangle(
symbol.getX(),
symbol.getBaseline() - font.getFontMetrics().getBaseline(),
symbol.getWidth(),
font.getFontSize()
);
}
// create new rectangle, which include both rectangles
public static Rectangle getRectangle(final Rectangle r1, final Rectangle r2) {
assert r1 != null;
assert r2 != null;
int x;
int y;
int width;
int height;
// get top rectangle
boolean cond = r1.getY() < r2.getY();
Rectangle top = cond ? r1 : r2;
Rectangle bottom = cond ? r2 : r1;
y = top.getY();
height = bottom.getY() + bottom.getHeight() - top.getY();
// get left rectangle
cond = r1.getX() < r2.getX();
Rectangle left = cond ? r1 : r2;
Rectangle right = cond ? r2 : r1;
x = left.getX();
width = right.getX() + right.getWidth() - left.getX();
return new Rectangle(x, y, width, height);
}
public static Pair<Integer, Integer> getWordPosition(final String text, final int index) {
assert text != null;
assert !text.isEmpty();
int first = -1;
int last = -10; // incorrect position
for (int i = 0; i < text.length(); ++i) {
if (text.charAt(i) == KeyCodes.KEY_SPACE) {
if (index <= i) {
last = i;
break;
} else {
first = i;
}
}
}
if (last == -10) {
last = text.length() - 1;
}
return new Pair<>(first, last);
}
public static String textToString(final Collection<Symbol> symbols) {
assert symbols != null;
StringBuilder builder = new StringBuilder();
for (Symbol symbol : symbols) {
assert symbol != null;
builder.append(symbol.getSymbol());
}
return builder.toString();
}
}
| apache-2.0 |
VincentFxz/EAM | target/tomcat/work/localEngine-8181/localhost/smarteam/org/apache/jsp/WEB_002dINF/views/modules/gen/genTableList_jsp.java | 40279 | package org.apache.jsp.WEB_002dINF.views.modules.gen;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class genTableList_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
static private org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_0;
static private org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_1;
static {
_jspx_fnmap_0= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fns:getAdminPath", com.dc.smarteam.common.config.Global.class, "getAdminPath", new Class[] {});
_jspx_fnmap_1= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fns:getDictLabel", com.dc.smarteam.modules.sys.utils.DictUtils.class, "getDictLabel", new Class[] {java.lang.String.class, java.lang.String.class, java.lang.String.class});
}
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
static {
_jspx_dependants = new java.util.ArrayList(6);
_jspx_dependants.add("/WEB-INF/views/include/taglib.jsp");
_jspx_dependants.add("/WEB-INF/tlds/shiros.tld");
_jspx_dependants.add("/WEB-INF/tlds/fns.tld");
_jspx_dependants.add("/WEB-INF/tlds/fnc.tld");
_jspx_dependants.add("/WEB-INF/tags/sys/tableSort.tag");
_jspx_dependants.add("/WEB-INF/tags/sys/message.tag");
}
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fform_005finput_0026_005fpath_005fmaxlength_005fhtmlEscape_005fclass_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fform_005finput_0026_005fpath_005fmaxlength_005fhtmlEscape_005fclass_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.release();
_005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.release();
_005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction.release();
_005fjspx_005ftagPool_005fform_005finput_0026_005fpath_005fmaxlength_005fhtmlEscape_005fclass_005fnobody.release();
_005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write('\n');
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
if (_jspx_meth_c_005fset_005f0(_jspx_page_context))
return;
out.write('\n');
if (_jspx_meth_c_005fset_005f1(_jspx_page_context))
return;
out.write("\n");
out.write("<html>\n");
out.write("<head>\n");
out.write(" <title>业务表管理</title>\n");
out.write(" <meta name=\"decorator\" content=\"default\"/>\n");
out.write(" <script type=\"text/javascript\">\n");
out.write(" $(document).ready(function () {\n");
out.write("\n");
out.write(" });\n");
out.write(" function page(n, s) {\n");
out.write(" if (n) $(\"#pageNo\").val(n);\n");
out.write(" if (s) $(\"#pageSize\").val(s);\n");
out.write(" $(\"#searchForm\").submit();\n");
out.write(" return false;\n");
out.write(" }\n");
out.write(" </script>\n");
out.write("</head>\n");
out.write("<body>\n");
out.write("<ul class=\"nav nav-tabs\">\n");
out.write(" <li class=\"active\"><a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("/gen/genTable/\">业务表列表</a></li>\n");
out.write(" ");
if (_jspx_meth_shiro_005fhasPermission_005f0(_jspx_page_context))
return;
out.write("\n");
out.write("</ul>\n");
if (_jspx_meth_form_005fform_005f0(_jspx_page_context))
return;
out.write('\n');
if (_jspx_meth_sys_005fmessage_005f0(_jspx_page_context))
return;
out.write("\n");
out.write("<table id=\"contentTable\" class=\"table table-striped table-bordered table-condensed\">\n");
out.write(" <thead>\n");
out.write(" <tr>\n");
out.write(" <th class=\"sort-column name\">表名</th>\n");
out.write(" <th>说明</th>\n");
out.write(" <th class=\"sort-column class_name\">类名</th>\n");
out.write(" <th class=\"sort-column parent_table\">状态</th>\n");
out.write(" <th class=\"sort-column parent_table\">父表</th>\n");
out.write(" ");
if (_jspx_meth_shiro_005fhasPermission_005f1(_jspx_page_context))
return;
out.write("</tr>\n");
out.write(" </thead>\n");
out.write(" <tbody>\n");
out.write(" ");
if (_jspx_meth_c_005fforEach_005f0(_jspx_page_context))
return;
out.write("\n");
out.write(" </tbody>\n");
out.write("</table>\n");
out.write("<div class=\"pagination\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("</div>\n");
out.write("</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else log(t.getMessage(), t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_005fset_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_005fset_005f0.setPageContext(_jspx_page_context);
_jspx_th_c_005fset_005f0.setParent(null);
// /WEB-INF/views/include/taglib.jsp(11,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fset_005f0.setVar("ctx");
// /WEB-INF/views/include/taglib.jsp(11,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fset_005f0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}${fns:getAdminPath()}", java.lang.Object.class, (PageContext)_jspx_page_context, _jspx_fnmap_0, false));
int _jspx_eval_c_005fset_005f0 = _jspx_th_c_005fset_005f0.doStartTag();
if (_jspx_th_c_005fset_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0);
return true;
}
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0);
return false;
}
private boolean _jspx_meth_c_005fset_005f1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:set
org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f1 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
_jspx_th_c_005fset_005f1.setPageContext(_jspx_page_context);
_jspx_th_c_005fset_005f1.setParent(null);
// /WEB-INF/views/include/taglib.jsp(12,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fset_005f1.setVar("ctxStatic");
// /WEB-INF/views/include/taglib.jsp(12,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fset_005f1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}/static", java.lang.Object.class, (PageContext)_jspx_page_context, null, false));
int _jspx_eval_c_005fset_005f1 = _jspx_th_c_005fset_005f1.doStartTag();
if (_jspx_th_c_005fset_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1);
return true;
}
_005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1);
return false;
}
private boolean _jspx_meth_shiro_005fhasPermission_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// shiro:hasPermission
org.apache.shiro.web.tags.HasPermissionTag _jspx_th_shiro_005fhasPermission_005f0 = (org.apache.shiro.web.tags.HasPermissionTag) _005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.get(org.apache.shiro.web.tags.HasPermissionTag.class);
_jspx_th_shiro_005fhasPermission_005f0.setPageContext(_jspx_page_context);
_jspx_th_shiro_005fhasPermission_005f0.setParent(null);
// /WEB-INF/views/modules/gen/genTableList.jsp(22,4) name = name type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_shiro_005fhasPermission_005f0.setName("gen:genTable:edit");
int _jspx_eval_shiro_005fhasPermission_005f0 = _jspx_th_shiro_005fhasPermission_005f0.doStartTag();
if (_jspx_eval_shiro_005fhasPermission_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <li><a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("/gen/genTable/form\">业务表添加</a></li>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_shiro_005fhasPermission_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_shiro_005fhasPermission_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.reuse(_jspx_th_shiro_005fhasPermission_005f0);
return true;
}
_005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.reuse(_jspx_th_shiro_005fhasPermission_005f0);
return false;
}
private boolean _jspx_meth_form_005fform_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:form
org.springframework.web.servlet.tags.form.FormTag _jspx_th_form_005fform_005f0 = (org.springframework.web.servlet.tags.form.FormTag) _005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction.get(org.springframework.web.servlet.tags.form.FormTag.class);
_jspx_th_form_005fform_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005fform_005f0.setParent(null);
// /WEB-INF/views/modules/gen/genTableList.jsp(26,0) name = id type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setId("searchForm");
// /WEB-INF/views/modules/gen/genTableList.jsp(26,0) name = modelAttribute type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setModelAttribute("genTable");
// /WEB-INF/views/modules/gen/genTableList.jsp(26,0) name = action type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setAction((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}/gen/genTable/", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
// /WEB-INF/views/modules/gen/genTableList.jsp(26,0) name = method type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005fform_005f0.setMethod("post");
// /WEB-INF/views/modules/gen/genTableList.jsp(26,0) null
_jspx_th_form_005fform_005f0.setDynamicAttribute(null, "class", new String("breadcrumb form-search"));
int[] _jspx_push_body_count_form_005fform_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005fform_005f0 = _jspx_th_form_005fform_005f0.doStartTag();
if (_jspx_eval_form_005fform_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <input id=\"pageNo\" name=\"pageNo\" type=\"hidden\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.pageNo}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("\"/>\n");
out.write(" <input id=\"pageSize\" name=\"pageSize\" type=\"hidden\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.pageSize}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("\"/>\n");
out.write(" ");
if (_jspx_meth_sys_005ftableSort_005f0(_jspx_th_form_005fform_005f0, _jspx_page_context, _jspx_push_body_count_form_005fform_005f0))
return true;
out.write("\n");
out.write(" <label>表名:</label>");
if (_jspx_meth_form_005finput_005f0(_jspx_th_form_005fform_005f0, _jspx_page_context, _jspx_push_body_count_form_005fform_005f0))
return true;
out.write("\n");
out.write(" <label>说明:</label>");
if (_jspx_meth_form_005finput_005f1(_jspx_th_form_005fform_005f0, _jspx_page_context, _jspx_push_body_count_form_005fform_005f0))
return true;
out.write("\n");
out.write(" <label>父表表名:</label>");
if (_jspx_meth_form_005finput_005f2(_jspx_th_form_005fform_005f0, _jspx_page_context, _jspx_push_body_count_form_005fform_005f0))
return true;
out.write("\n");
out.write(" <input id=\"btnSubmit\" class=\"btn btn-primary\" type=\"submit\" value=\"查询\"/>\n");
int evalDoAfterBody = _jspx_th_form_005fform_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_form_005fform_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005fform_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005fform_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005fform_005f0.doFinally();
_005fjspx_005ftagPool_005fform_005fform_0026_005fmodelAttribute_005fmethod_005fid_005fclass_005faction.reuse(_jspx_th_form_005fform_005f0);
}
return false;
}
private boolean _jspx_meth_sys_005ftableSort_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fform_005f0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fform_005f0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sys:tableSort
org.apache.jsp.tag.web.sys.tableSort_tag _jspx_th_sys_005ftableSort_005f0 = new org.apache.jsp.tag.web.sys.tableSort_tag();
org.apache.jasper.runtime.AnnotationHelper.postConstruct(_jsp_annotationprocessor, _jspx_th_sys_005ftableSort_005f0);
_jspx_th_sys_005ftableSort_005f0.setJspContext(_jspx_page_context);
_jspx_th_sys_005ftableSort_005f0.setParent(_jspx_th_form_005fform_005f0);
// /WEB-INF/views/modules/gen/genTableList.jsp(30,4) name = id type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null
_jspx_th_sys_005ftableSort_005f0.setId("orderBy");
// /WEB-INF/views/modules/gen/genTableList.jsp(30,4) name = name type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null
_jspx_th_sys_005ftableSort_005f0.setName("orderBy");
// /WEB-INF/views/modules/gen/genTableList.jsp(30,4) name = value type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null
_jspx_th_sys_005ftableSort_005f0.setValue((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.orderBy}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
// /WEB-INF/views/modules/gen/genTableList.jsp(30,4) name = callback type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null
_jspx_th_sys_005ftableSort_005f0.setCallback("page();");
_jspx_th_sys_005ftableSort_005f0.doTag();
org.apache.jasper.runtime.AnnotationHelper.preDestroy(_jsp_annotationprocessor, _jspx_th_sys_005ftableSort_005f0);
return false;
}
private boolean _jspx_meth_form_005finput_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fform_005f0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fform_005f0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:input
org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_005finput_005f0 = (org.springframework.web.servlet.tags.form.InputTag) _005fjspx_005ftagPool_005fform_005finput_0026_005fpath_005fmaxlength_005fhtmlEscape_005fclass_005fnobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
_jspx_th_form_005finput_005f0.setPageContext(_jspx_page_context);
_jspx_th_form_005finput_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fform_005f0);
// /WEB-INF/views/modules/gen/genTableList.jsp(31,22) name = path type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f0.setPath("nameLike");
// /WEB-INF/views/modules/gen/genTableList.jsp(31,22) name = htmlEscape type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f0.setHtmlEscape(false);
// /WEB-INF/views/modules/gen/genTableList.jsp(31,22) name = maxlength type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f0.setMaxlength("50");
// /WEB-INF/views/modules/gen/genTableList.jsp(31,22) null
_jspx_th_form_005finput_005f0.setDynamicAttribute(null, "class", new String("input-medium"));
int[] _jspx_push_body_count_form_005finput_005f0 = new int[] { 0 };
try {
int _jspx_eval_form_005finput_005f0 = _jspx_th_form_005finput_005f0.doStartTag();
if (_jspx_th_form_005finput_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005finput_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005finput_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005finput_005f0.doFinally();
_005fjspx_005ftagPool_005fform_005finput_0026_005fpath_005fmaxlength_005fhtmlEscape_005fclass_005fnobody.reuse(_jspx_th_form_005finput_005f0);
}
return false;
}
private boolean _jspx_meth_form_005finput_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fform_005f0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fform_005f0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:input
org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_005finput_005f1 = (org.springframework.web.servlet.tags.form.InputTag) _005fjspx_005ftagPool_005fform_005finput_0026_005fpath_005fmaxlength_005fhtmlEscape_005fclass_005fnobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
_jspx_th_form_005finput_005f1.setPageContext(_jspx_page_context);
_jspx_th_form_005finput_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fform_005f0);
// /WEB-INF/views/modules/gen/genTableList.jsp(32,22) name = path type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f1.setPath("comments");
// /WEB-INF/views/modules/gen/genTableList.jsp(32,22) name = htmlEscape type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f1.setHtmlEscape(false);
// /WEB-INF/views/modules/gen/genTableList.jsp(32,22) name = maxlength type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f1.setMaxlength("50");
// /WEB-INF/views/modules/gen/genTableList.jsp(32,22) null
_jspx_th_form_005finput_005f1.setDynamicAttribute(null, "class", new String("input-medium"));
int[] _jspx_push_body_count_form_005finput_005f1 = new int[] { 0 };
try {
int _jspx_eval_form_005finput_005f1 = _jspx_th_form_005finput_005f1.doStartTag();
if (_jspx_th_form_005finput_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005finput_005f1[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005finput_005f1.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005finput_005f1.doFinally();
_005fjspx_005ftagPool_005fform_005finput_0026_005fpath_005fmaxlength_005fhtmlEscape_005fclass_005fnobody.reuse(_jspx_th_form_005finput_005f1);
}
return false;
}
private boolean _jspx_meth_form_005finput_005f2(javax.servlet.jsp.tagext.JspTag _jspx_th_form_005fform_005f0, PageContext _jspx_page_context, int[] _jspx_push_body_count_form_005fform_005f0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// form:input
org.springframework.web.servlet.tags.form.InputTag _jspx_th_form_005finput_005f2 = (org.springframework.web.servlet.tags.form.InputTag) _005fjspx_005ftagPool_005fform_005finput_0026_005fpath_005fmaxlength_005fhtmlEscape_005fclass_005fnobody.get(org.springframework.web.servlet.tags.form.InputTag.class);
_jspx_th_form_005finput_005f2.setPageContext(_jspx_page_context);
_jspx_th_form_005finput_005f2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_form_005fform_005f0);
// /WEB-INF/views/modules/gen/genTableList.jsp(33,24) name = path type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f2.setPath("parentTable");
// /WEB-INF/views/modules/gen/genTableList.jsp(33,24) name = htmlEscape type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f2.setHtmlEscape(false);
// /WEB-INF/views/modules/gen/genTableList.jsp(33,24) name = maxlength type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_form_005finput_005f2.setMaxlength("50");
// /WEB-INF/views/modules/gen/genTableList.jsp(33,24) null
_jspx_th_form_005finput_005f2.setDynamicAttribute(null, "class", new String("input-medium"));
int[] _jspx_push_body_count_form_005finput_005f2 = new int[] { 0 };
try {
int _jspx_eval_form_005finput_005f2 = _jspx_th_form_005finput_005f2.doStartTag();
if (_jspx_th_form_005finput_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_form_005finput_005f2[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_form_005finput_005f2.doCatch(_jspx_exception);
} finally {
_jspx_th_form_005finput_005f2.doFinally();
_005fjspx_005ftagPool_005fform_005finput_0026_005fpath_005fmaxlength_005fhtmlEscape_005fclass_005fnobody.reuse(_jspx_th_form_005finput_005f2);
}
return false;
}
private boolean _jspx_meth_sys_005fmessage_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sys:message
org.apache.jsp.tag.web.sys.message_tag _jspx_th_sys_005fmessage_005f0 = new org.apache.jsp.tag.web.sys.message_tag();
org.apache.jasper.runtime.AnnotationHelper.postConstruct(_jsp_annotationprocessor, _jspx_th_sys_005fmessage_005f0);
_jspx_th_sys_005fmessage_005f0.setJspContext(_jspx_page_context);
// /WEB-INF/views/modules/gen/genTableList.jsp(36,0) name = content type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null
_jspx_th_sys_005fmessage_005f0.setContent((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${message}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
_jspx_th_sys_005fmessage_005f0.doTag();
org.apache.jasper.runtime.AnnotationHelper.preDestroy(_jsp_annotationprocessor, _jspx_th_sys_005fmessage_005f0);
return false;
}
private boolean _jspx_meth_shiro_005fhasPermission_005f1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// shiro:hasPermission
org.apache.shiro.web.tags.HasPermissionTag _jspx_th_shiro_005fhasPermission_005f1 = (org.apache.shiro.web.tags.HasPermissionTag) _005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.get(org.apache.shiro.web.tags.HasPermissionTag.class);
_jspx_th_shiro_005fhasPermission_005f1.setPageContext(_jspx_page_context);
_jspx_th_shiro_005fhasPermission_005f1.setParent(null);
// /WEB-INF/views/modules/gen/genTableList.jsp(45,8) name = name type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_shiro_005fhasPermission_005f1.setName("gen:genTable:edit");
int _jspx_eval_shiro_005fhasPermission_005f1 = _jspx_th_shiro_005fhasPermission_005f1.doStartTag();
if (_jspx_eval_shiro_005fhasPermission_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <th>操作</th>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_shiro_005fhasPermission_005f1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_shiro_005fhasPermission_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.reuse(_jspx_th_shiro_005fhasPermission_005f1);
return true;
}
_005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.reuse(_jspx_th_shiro_005fhasPermission_005f1);
return false;
}
private boolean _jspx_meth_c_005fforEach_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_005fforEach_005f0.setPageContext(_jspx_page_context);
_jspx_th_c_005fforEach_005f0.setParent(null);
// /WEB-INF/views/modules/gen/genTableList.jsp(50,4) name = items type = java.lang.Object reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fforEach_005f0.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.list}", java.lang.Object.class, (PageContext)_jspx_page_context, null, false));
// /WEB-INF/views/modules/gen/genTableList.jsp(50,4) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fforEach_005f0.setVar("genTable");
int[] _jspx_push_body_count_c_005fforEach_005f0 = new int[] { 0 };
try {
int _jspx_eval_c_005fforEach_005f0 = _jspx_th_c_005fforEach_005f0.doStartTag();
if (_jspx_eval_c_005fforEach_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <tr>\n");
out.write(" <td><a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("/gen/genTable/form?id=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${genTable.id}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write('"');
out.write('>');
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${genTable.name}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("</a></td>\n");
out.write(" <td>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${genTable.comments}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("</td>\n");
out.write(" <td>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${genTable.className}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("</td>\n");
out.write(" <td>");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${fns:getDictLabel(genTable.tableStatus, 'table_status', '')}", java.lang.String.class, (PageContext)_jspx_page_context, _jspx_fnmap_1, false));
out.write("</td>\n");
out.write("\n");
out.write(" <td title=\"点击查询子表\"><a href=\"javascript:\"\n");
out.write(" onclick=\"$('#parentTable').val('");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${genTable.parentTable}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("');$('#searchForm').submit();\">");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${genTable.parentTable}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("</a>\n");
out.write(" </td>\n");
out.write(" ");
if (_jspx_meth_shiro_005fhasPermission_005f2(_jspx_th_c_005fforEach_005f0, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f0))
return true;
out.write("\n");
out.write(" </tr>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_005fforEach_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_005fforEach_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_005fforEach_005f0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_005fforEach_005f0.doCatch(_jspx_exception);
} finally {
_jspx_th_c_005fforEach_005f0.doFinally();
_005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f0);
}
return false;
}
private boolean _jspx_meth_shiro_005fhasPermission_005f2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f0, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f0)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// shiro:hasPermission
org.apache.shiro.web.tags.HasPermissionTag _jspx_th_shiro_005fhasPermission_005f2 = (org.apache.shiro.web.tags.HasPermissionTag) _005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.get(org.apache.shiro.web.tags.HasPermissionTag.class);
_jspx_th_shiro_005fhasPermission_005f2.setPageContext(_jspx_page_context);
_jspx_th_shiro_005fhasPermission_005f2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f0);
// /WEB-INF/views/modules/gen/genTableList.jsp(60,12) name = name type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_shiro_005fhasPermission_005f2.setName("gen:genTable:edit");
int _jspx_eval_shiro_005fhasPermission_005f2 = _jspx_th_shiro_005fhasPermission_005f2.doStartTag();
if (_jspx_eval_shiro_005fhasPermission_005f2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write(" <td>\n");
out.write(" <a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("/gen/genTable/form?id=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${genTable.id}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("\">修改</a>\n");
out.write(" <a href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("/gen/genTable/delete?id=");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${genTable.id}", java.lang.String.class, (PageContext)_jspx_page_context, null, false));
out.write("\"\n");
out.write(" onclick=\"return confirmx('确认要删除该业务表吗?', this.href)\">删除</a>\n");
out.write(" </td>\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_shiro_005fhasPermission_005f2.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_shiro_005fhasPermission_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.reuse(_jspx_th_shiro_005fhasPermission_005f2);
return true;
}
_005fjspx_005ftagPool_005fshiro_005fhasPermission_0026_005fname.reuse(_jspx_th_shiro_005fhasPermission_005f2);
return false;
}
}
| apache-2.0 |
rajapulau/qiscus-sdk-android | chat/src/main/java/com/qiscus/sdk/event/QiscusCommentReceivedEvent.java | 964 | /*
* Copyright (c) 2016 Qiscus.
*
* 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.qiscus.sdk.event;
import com.qiscus.sdk.data.model.QiscusComment;
public class QiscusCommentReceivedEvent {
private QiscusComment qiscusComment;
public QiscusCommentReceivedEvent(QiscusComment qiscusComment) {
this.qiscusComment = qiscusComment;
}
public QiscusComment getQiscusComment() {
return qiscusComment;
}
}
| apache-2.0 |
headstar/scheelite-library | samples/calculator/src/main/java/com/headstartech/scheelite/samples/calculator/Operand1State.java | 844 | package com.headstartech.scheelite.samples.calculator;
import com.headstartech.scheelite.StateAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by per on 20/02/14.
*/
public class Operand1State extends StateAdapter<CalculatorContext, CalculatorState> {
private static final Logger logger = LoggerFactory.getLogger(Operand1State.class);
@Override
public CalculatorState getId() {
return CalculatorState.OPERAND1;
}
@Override
public boolean onEvent(CalculatorContext context, Object event) {
if(event instanceof OperationEvent) {
OperationEvent ev = (OperationEvent) event;
context.setOp(ev.getOp());
logger.info("Operation entered: operation={}", ev.getOp().name());
return true;
}
return false;
}
}
| apache-2.0 |
ThingPlug/thingplug-app-android-wis | onem2m/src/main/java/tp/skt/onem2m/net/mqtt/MQTTCallback.java | 319 | package tp.skt.onem2m.net.mqtt;
/**
* MQTT request callback
* <p>
* Copyright (C) 2017. SK Telecom, All Rights Reserved.
* Written 2017, by SK Telecom
*/
public abstract class MQTTCallback<T> {
public abstract void onResponse(T response);
public abstract void onFailure(int errorCode, String message);
}
| apache-2.0 |
eswdd/disco | disco-framework/disco-util/src/test/java/uk/co/exemel/disco/util/stream/ByteCountingDataInputTest.java | 9060 | /*
* Copyright 2014, The Sporting Exchange Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.exemel.disco.util.stream;
import org.junit.Test;
import java.io.*;
import java.util.Arrays;
import static org.junit.Assert.*;
/**
* Test case for ByteCountingDataInput class
*/
public class ByteCountingDataInputTest {
private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
@Test
public void testBoolean() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
output.writeBoolean(true);
output.writeBoolean(false);
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
assertTrue(bcdi.readBoolean());
assertFalse(bcdi.readBoolean());
assertEquals("Incorrect byte count returned", 2, bcdi.getCount());
}
@Test
public void testByte() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
output.writeByte('7');
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
assertEquals(55, bcdi.readByte());
assertEquals("Incorrect byte count returned", 1, bcdi.getCount());
}
@Test
public void testChar() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
output.writeChar('7');
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
assertEquals('7', bcdi.readChar());
assertEquals("Incorrect byte count returned", 2, bcdi.getCount());
}
@Test
public void testDouble() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
double d = 2.3456;
output.writeDouble(d);
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
assertEquals(d, bcdi.readDouble(), 0);
assertEquals("Incorrect byte count returned", 8, bcdi.getCount());
}
@Test
public void testFloat() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
float f = 3.21F;
output.writeFloat(f);
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
assertEquals(f, bcdi.readFloat(), 0);
assertEquals("Incorrect byte count returned", 4, bcdi.getCount());
}
@Test
public void testReadFully() throws Exception {
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(alphabet.getBytes())));
byte[] bytes = new byte[26];
bcdi.readFully(bytes);
assertEquals(26, bcdi.getCount());
assertArrayEquals(alphabet.getBytes(), bytes);
}
@Test
public void testReadFully2() throws Exception {
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(alphabet.getBytes())));
byte[] bytes = new byte[10];
bcdi.readFully(bytes, 2, 8);
assertEquals(8, bcdi.getCount());
assertArrayEquals(Arrays.copyOfRange(alphabet.getBytes(), 0, 8), Arrays.copyOfRange(bytes, 2, 10));
}
@Test
public void testInt() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
output.writeInt(3);
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
assertEquals(3, bcdi.readInt());
assertEquals("Incorrect byte count returned", 4, bcdi.getCount());
}
@Test
public void testReadLine() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
String expectedString = "A perfectly formed sentence";
String nextExpectedString = "With other nonsense on the end";
String theString = expectedString + "\r\n" + nextExpectedString + "\n";
output.write(theString.getBytes());
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
assertEquals(expectedString, bcdi.readLine());
long count= bcdi.getCount();
assertEquals("Incorrect byte count returned", expectedString.getBytes().length, count);
assertEquals(nextExpectedString, bcdi.readLine());
assertEquals("Incorrect byte count returned", nextExpectedString.getBytes().length, bcdi.getCount() - count);
}
@Test
public void testLong() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
long val = (long)Math.pow(2, 60);
output.writeLong(val);
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
assertEquals(val, bcdi.readLong());
assertEquals("Incorrect byte count returned", 8, bcdi.getCount());
}
@Test
public void testShort() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
short val = -395;
output.writeShort(val);
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
assertEquals(val, bcdi.readShort());
assertEquals("Incorrect byte count returned", 2, bcdi.getCount());
}
@Test
public void testUnsignedByte() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
output.writeInt(255);
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
bcdi.skipBytes(3);
assertEquals(255, (short)bcdi.readUnsignedByte());
assertEquals("Incorrect byte count returned", 1, bcdi.getCount()-3);
}
@Test
public void testUnsignedShort() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
output.writeInt(300);
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
//an int is 4 bytes, skip the first two
bcdi.skipBytes(2);
assertEquals(300, (int)bcdi.readUnsignedShort());
assertEquals("Incorrect byte count returned", 2, bcdi.getCount()-2);
}
@Test
public void testReadUTF() throws Exception {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutput output = new DataOutputStream(stream);
output.writeUTF(alphabet);
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(stream.toByteArray())));
String readAlphabet = bcdi.readUTF();
assertEquals("Incorrect byte count read for string", 28, bcdi.getCount());
long countBefore = bcdi.getCount();
try {
bcdi.readUTF();
} catch (IOException expected) {}
assertEquals(countBefore, bcdi.getCount());
}
@Test
public void testSkipPart() throws Exception {
ByteCountingDataInput bcdi = new ByteCountingDataInput(new DataInputStream(new ByteArrayInputStream(alphabet.getBytes())));
byte[] bytes = new byte[2];
bcdi.readFully(bytes);
assertArrayEquals("incorrect bytes read", Arrays.copyOfRange(alphabet.getBytes(), 0, 2), bytes);
bcdi.skipBytes(2);
bcdi.readFully(bytes);
assertArrayEquals("incorrect bytes read", Arrays.copyOfRange(alphabet.getBytes(), 4, 6), bytes);
assertEquals("incorrect byte count read", 6, bcdi.getCount());
}
}
| apache-2.0 |