repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
sbryzak/DeltaSpike | deltaspike/modules/security/impl/src/main/java/org/apache/deltaspike/security/impl/authentication/DefaultIdentity.java | 7347 | /*
* 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.deltaspike.security.impl.authentication;
import org.apache.deltaspike.core.util.ExceptionUtils;
import org.apache.deltaspike.security.api.Identity;
import org.apache.deltaspike.security.api.User;
import org.apache.deltaspike.security.api.authentication.AuthenticationException;
import org.apache.deltaspike.security.api.authentication.UnexpectedCredentialException;
import org.apache.deltaspike.security.api.authentication.event.AlreadyLoggedInEvent;
import org.apache.deltaspike.security.api.authentication.event.LoggedInEvent;
import org.apache.deltaspike.security.api.authentication.event.LoginFailedEvent;
import org.apache.deltaspike.security.api.authentication.event.PostAuthenticateEvent;
import org.apache.deltaspike.security.api.authentication.event.PostLoggedOutEvent;
import org.apache.deltaspike.security.api.authentication.event.PreAuthenticateEvent;
import org.apache.deltaspike.security.api.authentication.event.PreLoggedOutEvent;
import org.apache.deltaspike.security.api.credential.LoginCredential;
import org.apache.deltaspike.security.spi.authentication.Authenticator;
import org.apache.deltaspike.security.spi.authentication.Authenticator.AuthenticationStatus;
import org.apache.deltaspike.security.spi.authentication.AuthenticatorSelector;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
/**
* Default Identity implementation
*/
@SuppressWarnings("UnusedDeclaration")
@SessionScoped
public class DefaultIdentity implements Identity
{
private static final long serialVersionUID = 3696702275353144429L;
@Inject
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private AuthenticatorSelector authenticatorSelector;
@Inject
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private BeanManager beanManager;
@Inject
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private LoginCredential loginCredential;
/**
* Flag indicating whether we are currently authenticating
*/
private boolean authenticating;
private User user;
public boolean isLoggedIn()
{
// If there is a user set, then the user is logged in.
return this.user != null;
}
@Override
public User getUser()
{
return this.user;
}
@Override
public AuthenticationResult login()
{
try
{
if (isLoggedIn())
{
if (isAuthenticationRequestWithDifferentUserId())
{
throw new UnexpectedCredentialException("active user: " + this.user.getId() +
" provided credentials: " + this.loginCredential.getUserId());
}
beanManager.fireEvent(new AlreadyLoggedInEvent());
return AuthenticationResult.SUCCESS;
}
boolean success = authenticate();
if (success)
{
beanManager.fireEvent(new LoggedInEvent()); //X TODO beanManager.fireEvent(new LoggedInEvent(user));
return AuthenticationResult.SUCCESS;
}
beanManager.fireEvent(new LoginFailedEvent(null));
return AuthenticationResult.FAILED;
}
catch (Exception e)
{
//X TODO discuss special handling of UnexpectedCredentialException
beanManager.fireEvent(new LoginFailedEvent(e));
if (e instanceof RuntimeException)
{
throw (RuntimeException)e;
}
ExceptionUtils.throwAsRuntimeException(e);
//Attention: the following line is just for the compiler (and analysis tools) - it won't get executed
throw new IllegalStateException(e);
}
}
private boolean isAuthenticationRequestWithDifferentUserId()
{
return isLoggedIn() && this.loginCredential.getUserId() != null &&
!this.loginCredential.getUserId().equals(this.user.getId());
}
protected boolean authenticate() throws AuthenticationException
{
if (authenticating)
{
authenticating = false; //X TODO discuss it
throw new IllegalStateException("Authentication already in progress.");
}
try
{
authenticating = true;
beanManager.fireEvent(new PreAuthenticateEvent());
Authenticator activeAuthenticator = authenticatorSelector.getSelectedAuthenticator();
activeAuthenticator.authenticate();
if (activeAuthenticator.getStatus() == null)
{
throw new AuthenticationException("Authenticator must return a valid authentication status");
}
if (activeAuthenticator.getStatus() == AuthenticationStatus.SUCCESS)
{
postAuthenticate(activeAuthenticator);
this.user = activeAuthenticator.getUser();
return true;
}
}
catch (Exception ex)
{
if (ex instanceof AuthenticationException)
{
throw (AuthenticationException) ex;
}
else
{
throw new AuthenticationException("Authentication failed.", ex);
}
}
finally
{
authenticating = false;
}
return false;
}
protected void postAuthenticate(Authenticator activeAuthenticator)
{
activeAuthenticator.postAuthenticate();
if (!activeAuthenticator.getStatus().equals(AuthenticationStatus.SUCCESS))
{
return;
}
beanManager.fireEvent(new PostAuthenticateEvent());
}
@Override
public void logout()
{
logout(true);
}
protected void logout(boolean invalidateLoginCredential)
{
if (isLoggedIn())
{
beanManager.fireEvent(new PreLoggedOutEvent(this.user));
PostLoggedOutEvent postLoggedOutEvent = new PostLoggedOutEvent(this.user);
unAuthenticate(invalidateLoginCredential);
beanManager.fireEvent(postLoggedOutEvent);
}
}
/**
* Resets all security state and loginCredential
*/
private void unAuthenticate(boolean invalidateLoginCredential)
{
this.user = null;
if (invalidateLoginCredential)
{
loginCredential.invalidate();
}
}
}
| apache-2.0 |
bryce-anderson/netty | handler/src/test/java/io/netty/handler/flow/FlowControlHandlerTest.java | 15662 | /*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.netty.handler.flow;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.ReferenceCountUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.net.SocketAddress;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.concurrent.TimeUnit.*;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class FlowControlHandlerTest {
private static EventLoopGroup GROUP;
@BeforeClass
public static void init() {
GROUP = new NioEventLoopGroup();
}
@AfterClass
public static void destroy() {
GROUP.shutdownGracefully();
}
/**
* The {@link OneByteToThreeStringsDecoder} decodes this {@code byte[]} into three messages.
*/
private static ByteBuf newOneMessage() {
return Unpooled.wrappedBuffer(new byte[]{ 1 });
}
private static Channel newServer(final boolean autoRead, final ChannelHandler... handlers) {
assertTrue(handlers.length >= 1);
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(GROUP)
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.AUTO_READ, autoRead)
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new OneByteToThreeStringsDecoder());
pipeline.addLast(handlers);
}
});
return serverBootstrap.bind(0)
.syncUninterruptibly()
.channel();
}
private static Channel newClient(SocketAddress server) {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(GROUP)
.channel(NioSocketChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
.handler(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
fail("In this test the client is never receiving a message from the server.");
}
});
return bootstrap.connect(server)
.syncUninterruptibly()
.channel();
}
/**
* This test demonstrates the default behavior if auto reading
* is turned on from the get-go and you're trying to turn it off
* once you've received your first message.
*
* NOTE: This test waits for the client to disconnect which is
* interpreted as the signal that all {@code byte}s have been
* transferred to the server.
*/
@Test
public void testAutoReadingOn() throws Exception {
final CountDownLatch latch = new CountDownLatch(3);
ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ReferenceCountUtil.release(msg);
// We're turning off auto reading in the hope that no
// new messages are being sent but that is not true.
ctx.channel().config().setAutoRead(false);
latch.countDown();
}
};
Channel server = newServer(true, handler);
Channel client = newClient(server.localAddress());
try {
client.writeAndFlush(newOneMessage())
.syncUninterruptibly();
// We received three messages even through auto reading
// was turned off after we received the first message.
assertTrue(latch.await(1L, SECONDS));
} finally {
client.close();
server.close();
}
}
/**
* This test demonstrates the default behavior if auto reading
* is turned off from the get-go and you're calling read() in
* the hope that only one message will be returned.
*
* NOTE: This test waits for the client to disconnect which is
* interpreted as the signal that all {@code byte}s have been
* transferred to the server.
*/
@Test
public void testAutoReadingOff() throws Exception {
final Exchanger<Channel> peerRef = new Exchanger<Channel>();
final CountDownLatch latch = new CountDownLatch(3);
ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
peerRef.exchange(ctx.channel(), 1L, SECONDS);
ctx.fireChannelActive();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ReferenceCountUtil.release(msg);
latch.countDown();
}
};
Channel server = newServer(false, handler);
Channel client = newClient(server.localAddress());
try {
// The client connection on the server side
Channel peer = peerRef.exchange(null, 1L, SECONDS);
// Write the message
client.writeAndFlush(newOneMessage())
.syncUninterruptibly();
// Read the message
peer.read();
// We received all three messages but hoped that only one
// message was read because auto reading was off and we
// invoked the read() method only once.
assertTrue(latch.await(1L, SECONDS));
} finally {
client.close();
server.close();
}
}
/**
* The {@link FlowControlHandler} will simply pass-through all messages
* if auto reading is on and remains on.
*/
@Test
public void testFlowAutoReadOn() throws Exception {
final CountDownLatch latch = new CountDownLatch(3);
ChannelInboundHandlerAdapter handler = new ChannelDuplexHandler() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
latch.countDown();
}
};
FlowControlHandler flow = new FlowControlHandler();
Channel server = newServer(true, flow, handler);
Channel client = newClient(server.localAddress());
try {
// Write the message
client.writeAndFlush(newOneMessage())
.syncUninterruptibly();
// We should receive 3 messages
assertTrue(latch.await(1L, SECONDS));
assertTrue(flow.isQueueEmpty());
} finally {
client.close();
server.close();
}
}
/**
* The {@link FlowControlHandler} will pass down messages one by one
* if {@link ChannelConfig#setAutoRead(boolean)} is being toggled.
*/
@Test
public void testFlowToggleAutoRead() throws Exception {
final Exchanger<Channel> peerRef = new Exchanger<Channel>();
final CountDownLatch msgRcvLatch1 = new CountDownLatch(1);
final CountDownLatch msgRcvLatch2 = new CountDownLatch(1);
final CountDownLatch msgRcvLatch3 = new CountDownLatch(1);
final CountDownLatch setAutoReadLatch1 = new CountDownLatch(1);
final CountDownLatch setAutoReadLatch2 = new CountDownLatch(1);
ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {
private int msgRcvCount;
private int expectedMsgCount;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
peerRef.exchange(ctx.channel(), 1L, SECONDS);
ctx.fireChannelActive();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws InterruptedException {
ReferenceCountUtil.release(msg);
// Disable auto reading after each message
ctx.channel().config().setAutoRead(false);
if (msgRcvCount++ != expectedMsgCount) {
return;
}
switch (msgRcvCount) {
case 1:
msgRcvLatch1.countDown();
if (setAutoReadLatch1.await(1L, SECONDS)) {
++expectedMsgCount;
}
break;
case 2:
msgRcvLatch2.countDown();
if (setAutoReadLatch2.await(1L, SECONDS)) {
++expectedMsgCount;
}
break;
default:
msgRcvLatch3.countDown();
break;
}
}
};
FlowControlHandler flow = new FlowControlHandler();
Channel server = newServer(true, flow, handler);
Channel client = newClient(server.localAddress());
try {
// The client connection on the server side
Channel peer = peerRef.exchange(null, 1L, SECONDS);
client.writeAndFlush(newOneMessage())
.syncUninterruptibly();
// channelRead(1)
assertTrue(msgRcvLatch1.await(1L, SECONDS));
// channelRead(2)
peer.config().setAutoRead(true);
setAutoReadLatch1.countDown();
assertTrue(msgRcvLatch1.await(1L, SECONDS));
// channelRead(3)
peer.config().setAutoRead(true);
setAutoReadLatch2.countDown();
assertTrue(msgRcvLatch3.await(1L, SECONDS));
assertTrue(flow.isQueueEmpty());
} finally {
client.close();
server.close();
}
}
/**
* The {@link FlowControlHandler} will pass down messages one by one
* if auto reading is off and the user is calling {@code read()} on
* their own.
*/
@Test
public void testFlowAutoReadOff() throws Exception {
final Exchanger<Channel> peerRef = new Exchanger<Channel>();
final CountDownLatch msgRcvLatch1 = new CountDownLatch(1);
final CountDownLatch msgRcvLatch2 = new CountDownLatch(2);
final CountDownLatch msgRcvLatch3 = new CountDownLatch(3);
ChannelInboundHandlerAdapter handler = new ChannelDuplexHandler() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelActive();
peerRef.exchange(ctx.channel(), 1L, SECONDS);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
msgRcvLatch1.countDown();
msgRcvLatch2.countDown();
msgRcvLatch3.countDown();
}
};
FlowControlHandler flow = new FlowControlHandler();
Channel server = newServer(false, flow, handler);
Channel client = newClient(server.localAddress());
try {
// The client connection on the server side
Channel peer = peerRef.exchange(null, 1L, SECONDS);
// Write the message
client.writeAndFlush(newOneMessage())
.syncUninterruptibly();
// channelRead(1)
peer.read();
assertTrue(msgRcvLatch1.await(1L, SECONDS));
// channelRead(2)
peer.read();
assertTrue(msgRcvLatch2.await(1L, SECONDS));
// channelRead(3)
peer.read();
assertTrue(msgRcvLatch3.await(1L, SECONDS));
assertTrue(flow.isQueueEmpty());
} finally {
client.close();
server.close();
}
}
@Test
public void testReentranceNotCausesNPE() throws Throwable {
final Exchanger<Channel> peerRef = new Exchanger<Channel>();
final CountDownLatch latch = new CountDownLatch(3);
final AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
ChannelInboundHandlerAdapter handler = new ChannelDuplexHandler() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.fireChannelActive();
peerRef.exchange(ctx.channel(), 1L, SECONDS);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
latch.countDown();
ctx.read();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
causeRef.set(cause);
}
};
FlowControlHandler flow = new FlowControlHandler();
Channel server = newServer(false, flow, handler);
Channel client = newClient(server.localAddress());
try {
// The client connection on the server side
Channel peer = peerRef.exchange(null, 1L, SECONDS);
// Write the message
client.writeAndFlush(newOneMessage())
.syncUninterruptibly();
// channelRead(1)
peer.read();
assertTrue(latch.await(1L, SECONDS));
assertTrue(flow.isQueueEmpty());
Throwable cause = causeRef.get();
if (cause != null) {
throw cause;
}
} finally {
client.close();
server.close();
}
}
/**
* This is a fictional message decoder. It decodes each {@code byte}
* into three strings.
*/
private static final class OneByteToThreeStringsDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
for (int i = 0; i < in.readableBytes(); i++) {
out.add("1");
out.add("2");
out.add("3");
}
in.readerIndex(in.readableBytes());
}
}
}
| apache-2.0 |
kythe/kythe | kythe/javatests/com/google/devtools/kythe/analyzers/java/testdata/pkg/StaticMethods.java | 1073 | package pkg;
@SuppressWarnings("unused")
public class StaticMethods {
//- @member defines/binding PrivateMember
private int member;
//- @member defines/binding MemberFunc
public static int member() {
return 0;
}
//- @staticMember defines/binding PrivateStaticMember
private static int staticMember;
//- @staticMember defines/binding ProtectedStaticMemberFunc
protected static int staticMember(int x) {
return x;
}
//- @staticMember defines/binding PackageStaticMemberFunc
static int staticMember(boolean b) {
return b ? 1 : 0;
}
//- @staticMember defines/binding StaticMemberFunc
public static int staticMember() {
return 0;
}
//- @staticMethod defines/binding StaticBool
public static void staticMethod(boolean b) {}
//- @staticMethod defines/binding StaticInt
public static void staticMethod(int b) {}
}
//- MemberFunc.tag/static _
//- ProtectedStaticMemberFunc.tag/static _
//- PackageStaticMemberFunc.tag/static _
//- StaticMemberFunc.tag/static _
//- StaticBool.tag/static _
//- StaticInt.tag/static _
| apache-2.0 |
vanant/googleads-dfa-reporting-samples | java/v2.1/src/main/java/com/google/api/services/samples/dfareporting/floodlight/CreateFloodlightActivity.java | 2553 | // Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.services.samples.dfareporting.floodlight;
import com.google.api.services.dfareporting.Dfareporting;
import com.google.api.services.dfareporting.model.FloodlightActivity;
import com.google.api.services.samples.dfareporting.DfaReportingFactory;
/**
* This example creates a floodlight activity in a given activity group. To create an activity
* group, run CreateFloodlightActivityGroup.java.
*
* Tags: floodlightActivities.insert
*
* @author api.jimper@gmail.com (Jonathon Imperiosi)
*/
public class CreateFloodlightActivity {
private static final String USER_PROFILE_ID = "INSERT_USER_PROFILE_ID_HERE";
private static final String ACTIVITY_GROUP_ID = "INSERT_ACTIVITY_GROUP_ID_HERE";
private static final String ACTIVITY_NAME = "INSERT_ACTIVITY_NAME_HERE";
private static final String URL = "INSERT_EXPECTED_URL_HERE";
public static void runExample(Dfareporting reporting, long profileId, String activityName,
String url, long activityGroupId) throws Exception {
// Set floodlight activity structure.
FloodlightActivity activity = new FloodlightActivity();
activity.setCountingMethod("STANDARD_COUNTING");
activity.setName(activityName);
activity.setFloodlightActivityGroupId(activityGroupId);
activity.setExpectedUrl(url);
// Create the floodlight tag activity.
FloodlightActivity result =
reporting.floodlightActivities().insert(profileId, activity).execute();
// Display new floodlight activity ID.
if (result != null) {
System.out.printf("Floodlight activity with ID %d was created.%n", result.getId());
}
}
public static void main(String[] args) throws Exception {
Dfareporting reporting = DfaReportingFactory.getInstance();
long activityGroupId = Long.parseLong(ACTIVITY_GROUP_ID);
long profileId = Long.parseLong(USER_PROFILE_ID);
runExample(reporting, profileId, ACTIVITY_NAME, URL, activityGroupId);
}
}
| apache-2.0 |
jk1/intellij-community | python/src/com/jetbrains/python/console/PydevConsoleRunnerFactory.java | 10269 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.console;
import com.google.common.collect.Maps;
import com.intellij.execution.console.LanguageConsoleView;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.PathMapper;
import com.jetbrains.python.buildout.BuildoutFacet;
import com.jetbrains.python.run.PythonCommandLineState;
import com.jetbrains.python.run.PythonRunConfiguration;
import com.jetbrains.python.sdk.PythonEnvUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* @author traff
*/
public class PydevConsoleRunnerFactory extends PythonConsoleRunnerFactory {
protected static class ConsoleParameters {
@NotNull Project project;
@NotNull Sdk sdk;
@Nullable String workingDir;
@NotNull Map<String, String> envs;
@NotNull PyConsoleType consoleType;
@NotNull PyConsoleOptions.PyConsoleSettings settingsProvider;
@NotNull Consumer<String> rerunAction;
@NotNull String[] setupFragment;
public ConsoleParameters(@NotNull Project project,
@NotNull Sdk sdk,
@Nullable String workingDir,
@NotNull Map<String, String> envs,
@NotNull PyConsoleType consoleType,
@NotNull PyConsoleOptions.PyConsoleSettings settingsProvider,
@NotNull Consumer<String> rerunAction,
@NotNull String[] setupFragment) {
this.project = project;
this.sdk = sdk;
this.workingDir = workingDir;
this.envs = envs;
this.consoleType = consoleType;
this.settingsProvider = settingsProvider;
this.rerunAction = rerunAction;
this.setupFragment = setupFragment;
}
}
protected ConsoleParameters createConsoleParameters(@NotNull Project project,
@Nullable Module contextModule) {
Pair<Sdk, Module> sdkAndModule = PydevConsoleRunner.findPythonSdkAndModule(project, contextModule);
@Nullable Module module = sdkAndModule.second;
Sdk sdk = sdkAndModule.first;
assert sdk != null;
PyConsoleOptions.PyConsoleSettings settingsProvider = PyConsoleOptions.getInstance(project).getPythonConsoleSettings();
PathMapper pathMapper = PydevConsoleRunner.getPathMapper(project, sdk, settingsProvider);
String workingDir = getWorkingDir(project, module, pathMapper, settingsProvider);
String[] setupFragment = createSetupFragment(module, workingDir, pathMapper, settingsProvider);
Map<String, String> envs = Maps.newHashMap(settingsProvider.getEnvs());
putIPythonEnvFlag(project, envs);
Consumer<String> rerunAction = title -> {
PydevConsoleRunner runner = createConsoleRunner(project, module);
if (runner instanceof PydevConsoleRunnerImpl) {
((PydevConsoleRunnerImpl)runner).setConsoleTitle(title);
}
runner.run(true);
};
return new ConsoleParameters(project, sdk, workingDir, envs, PyConsoleType.PYTHON, settingsProvider, rerunAction, setupFragment);
}
@Override
@NotNull
public PydevConsoleRunner createConsoleRunner(@NotNull Project project,
@Nullable Module contextModule) {
final ConsoleParameters consoleParameters = createConsoleParameters(project, contextModule);
return createConsoleRunner(project, consoleParameters.sdk, consoleParameters.workingDir, consoleParameters.envs,
consoleParameters.consoleType,
consoleParameters.settingsProvider, consoleParameters.rerunAction, consoleParameters.setupFragment);
}
public static void putIPythonEnvFlag(@NotNull Project project, Map<String, String> envs) {
String ipythonEnabled = PyConsoleOptions.getInstance(project).isIpythonEnabled() ? "True" : "False";
envs.put(PythonEnvUtil.IPYTHONENABLE, ipythonEnabled);
}
@Nullable
public static String getWorkingDir(@NotNull Project project,
@Nullable Module module,
@Nullable PathMapper pathMapper,
PyConsoleOptions.PyConsoleSettings settingsProvider) {
String workingDir = settingsProvider.getWorkingDirectory();
if (StringUtil.isEmpty(workingDir)) {
if (module != null && ModuleRootManager.getInstance(module).getContentRoots().length > 0) {
workingDir = ModuleRootManager.getInstance(module).getContentRoots()[0].getPath();
}
else {
if (ModuleManager.getInstance(project).getModules().length > 0) {
VirtualFile[] roots = ModuleRootManager.getInstance(ModuleManager.getInstance(project).getModules()[0]).getContentRoots();
if (roots.length > 0) {
workingDir = roots[0].getPath();
}
}
}
}
if (pathMapper != null && workingDir != null) {
workingDir = pathMapper.convertToRemote(workingDir);
}
return workingDir;
}
public static String[] createSetupFragment(@Nullable Module module,
@Nullable String workingDir,
@Nullable PathMapper pathMapper,
PyConsoleOptions.PyConsoleSettings settingsProvider) {
String customStartScript = settingsProvider.getCustomStartScript();
if (customStartScript.trim().length() > 0) {
customStartScript = "\n" + customStartScript;
}
Collection<String> pythonPath = PythonCommandLineState.collectPythonPath(module, settingsProvider.shouldAddContentRoots(),
settingsProvider.shouldAddSourceRoots());
if (pathMapper != null) {
pythonPath = pathMapper.convertToRemote(pythonPath);
}
String selfPathAppend = PydevConsoleRunner.constructPyPathAndWorkingDirCommand(pythonPath, workingDir, customStartScript);
BuildoutFacet facet = null;
if (module != null) {
facet = BuildoutFacet.getInstance(module);
}
String[] setupFragment;
if (facet != null) {
List<String> path = facet.getAdditionalPythonPath();
if (pathMapper != null) {
path = pathMapper.convertToRemote(path);
}
String prependStatement = facet.getPathPrependStatement(path);
setupFragment = new String[]{prependStatement, selfPathAppend};
}
else {
setupFragment = new String[]{selfPathAppend};
}
return setupFragment;
}
@NotNull
protected PydevConsoleRunner createConsoleRunner(@NotNull Project project,
@NotNull Sdk sdk,
@Nullable String workingDir,
@NotNull Map<String, String> envs,
@NotNull PyConsoleType consoleType,
@NotNull PyConsoleOptions.PyConsoleSettings settingsProvider,
@NotNull Consumer<String> rerunAction,
@NotNull String... setupFragment) {
return new PydevConsoleRunnerImpl(project, sdk, consoleType, workingDir, envs, settingsProvider, rerunAction, setupFragment);
}
@NotNull
public PydevConsoleRunner createConsoleRunnerWithFile(@NotNull Project project,
@Nullable Module contextModule,
@Nullable String runFileText,
@NotNull PythonRunConfiguration config) {
final ConsoleParameters consoleParameters = createConsoleParameters(project, contextModule);
Consumer<String> rerunAction = title -> {
PydevConsoleRunner runner = createConsoleRunnerWithFile(project, contextModule, runFileText, config);
if (runner instanceof PydevConsoleRunnerImpl) {
((PydevConsoleRunnerImpl)runner).setConsoleTitle(title);
}
final PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(project);
runner.addConsoleListener(new PydevConsoleRunner.ConsoleListener() {
@Override
public void handleConsoleInitialized(LanguageConsoleView consoleView) {
if (consoleView instanceof PyCodeExecutor) {
((PyCodeExecutor)consoleView).executeCode(runFileText, null);
if (toolWindow != null) {
toolWindow.getToolWindow().show(null);
}
}
}
});
runner.run(true);
};
Sdk sdk = config.getSdk() != null ? config.getSdk() : consoleParameters.sdk;
String workingDir = config.getWorkingDirectory() != null ? config.getWorkingDirectory() : consoleParameters.workingDir;
return new PydevConsoleWithFileRunnerImpl(project, sdk, consoleParameters.consoleType, workingDir,
consoleParameters.envs, consoleParameters.settingsProvider, rerunAction, config,
consoleParameters.setupFragment);
}
}
| apache-2.0 |
bsa01/qbit | qbit/core/src/main/java/io/advantageous/qbit/service/impl/BaseServiceQueueImpl.java | 27914 | /**
* ****************************************************************************
* Copyright (c) 2015. Rick Hightower, Geoff Chandler
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
* __ __ _ _____ _ _
* \ \ / / | | / ____| | | | |
* \ \ /\ / /__| |__| (___ ___ ___| | _____| |_
* \ \/ \/ / _ \ '_ \\___ \ / _ \ / __| |/ / _ \ __|
* \ /\ / __/ |_) |___) | (_) | (__| < __/ |_
* \/ \/ \___|_.__/_____/ \___/ \___|_|\_\___|\__|
* _ _____ ____ _ _
* | |/ ____|/ __ \| \ | |
* | | (___ | | | | \| |
* _ | |\___ \| | | | . ` |
* | |__| |____) | |__| | |\ |
* \____/|_____/ \____/|_|_\_|_
* | __ \| ____|/ ____|__ __|
* | |__) | |__ | (___ | |
* | _ /| __| \___ \ | |
* | | \ \| |____ ____) | | |
* |_| \_\______|_____/ |_|___ _
* | \/ (_) / ____| (_)
* | \ / |_ ___ _ __ ___| (___ ___ _ ____ ___ ___ ___
* | |\/| | |/ __| '__/ _ \\___ \ / _ \ '__\ \ / / |/ __/ _ \
* | | | | | (__| | | (_) |___) | __/ | \ V /| | (_| __/
* |_| |_|_|\___|_| \___/_____/ \___|_| \_/ |_|\___\___|
* <p>
* QBit - The Microservice lib for Java : JSON, WebSocket, REST. Be The Web!
* http://rick-hightower.blogspot.com/2014/12/rise-of-machines-writing-high-speed.html
* http://rick-hightower.blogspot.com/2014/12/quick-guide-to-programming-services-in.html
* http://rick-hightower.blogspot.com/2015/01/quick-startClient-qbit-programming.html
* http://rick-hightower.blogspot.com/2015/01/high-speed-soa.html
* http://rick-hightower.blogspot.com/2015/02/qbit-event-bus.html
* ****************************************************************************
*/
package io.advantageous.qbit.service.impl;
import io.advantageous.boon.core.reflection.BeanUtils;
import io.advantageous.qbit.Factory;
import io.advantageous.qbit.GlobalConstants;
import io.advantageous.qbit.client.ClientProxy;
import io.advantageous.qbit.concurrent.PeriodicScheduler;
import io.advantageous.qbit.events.EventManager;
import io.advantageous.qbit.message.*;
import io.advantageous.qbit.queue.*;
import io.advantageous.qbit.reactive.Callback;
import io.advantageous.qbit.service.*;
import io.advantageous.qbit.system.QBitSystemManager;
import io.advantageous.qbit.transforms.NoOpResponseTransformer;
import io.advantageous.qbit.transforms.Transformer;
import io.advantageous.qbit.util.MultiMap;
import io.advantageous.qbit.util.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.advantageous.qbit.QBit.factory;
import static io.advantageous.qbit.service.ServiceContext.serviceContext;
/**
* @author rhightower on 2/18/15.
*/
public class BaseServiceQueueImpl implements ServiceQueue {
private static final ThreadLocal<ServiceQueue> serviceThreadLocal = new ThreadLocal<>();
protected final QBitSystemManager systemManager;
protected final Logger logger = LoggerFactory.getLogger(ServiceQueueImpl.class);
protected final boolean debug = GlobalConstants.DEBUG && logger.isDebugEnabled();
protected final Object service;
protected final Queue<Response<Object>> responseQueue;
protected final Queue<MethodCall<Object>> requestQueue;
protected final Queue<Event<Object>> eventQueue;
protected final QueueBuilder requestQueueBuilder;
protected final QueueBuilder responseQueueBuilder;
protected final boolean handleCallbacks;
private final Factory factory;
protected volatile long lastResponseFlushTime = Timer.timer().now();
protected final ServiceMethodHandler serviceMethodHandler;
protected final SendQueue<Response<Object>> responseSendQueue;
private final AtomicBoolean started = new AtomicBoolean(false);
private final BeforeMethodCall beforeMethodCall;
private final BeforeMethodCall beforeMethodCallAfterTransform;
private final AfterMethodCall afterMethodCall;
private final AfterMethodCall afterMethodCallAfterTransform;
private Transformer<Request, Object> requestObjectTransformer = ServiceConstants.NO_OP_ARG_TRANSFORM;
private Transformer<Response<Object>, Response> responseObjectTransformer = new NoOpResponseTransformer();
private final CallbackManager callbackManager;
private final QueueCallBackHandler queueCallBackHandler;
public BaseServiceQueueImpl(final String rootAddress,
final String serviceAddress,
final Object service,
final QueueBuilder requestQueueBuilder,
final QueueBuilder responseQueueBuilder,
final ServiceMethodHandler serviceMethodHandler,
final Queue<Response<Object>> responseQueue,
final boolean async,
final boolean handleCallbacks,
final QBitSystemManager systemManager,
final BeforeMethodCall beforeMethodCall,
final BeforeMethodCall beforeMethodCallAfterTransform,
final AfterMethodCall afterMethodCall,
final AfterMethodCall afterMethodCallAfterTransform,
final QueueCallBackHandler queueCallBackHandler,
final CallbackManager callbackManager) {
this.beforeMethodCall = beforeMethodCall;
this.beforeMethodCallAfterTransform = beforeMethodCallAfterTransform;
this.afterMethodCall = afterMethodCall;
this.afterMethodCallAfterTransform = afterMethodCallAfterTransform;
this.callbackManager = callbackManager;
if (queueCallBackHandler==null) {
this.queueCallBackHandler = new QueueCallBackHandler() {
@Override
public void queueLimit() {
}
@Override
public void queueEmpty() {
}
};
} else {
this.queueCallBackHandler = queueCallBackHandler;
}
if (requestQueueBuilder == null) {
this.requestQueueBuilder = new QueueBuilder();
} else {
this.requestQueueBuilder = BeanUtils.copy(requestQueueBuilder);
}
if (responseQueueBuilder == null) {
this.responseQueueBuilder = new QueueBuilder();
} else {
this.responseQueueBuilder = BeanUtils.copy(responseQueueBuilder);
}
if (responseQueue == null) {
logger.info("RESPONSE QUEUE WAS NULL CREATING ONE for service");
this.responseQueue = this.responseQueueBuilder.setName("Response Queue " + serviceMethodHandler.address()).build();
} else {
this.responseQueue = responseQueue;
}
this.responseSendQueue = this.responseQueue.sendQueueWithAutoFlush(100, TimeUnit.MILLISECONDS);
this.service = service;
this.serviceMethodHandler = serviceMethodHandler;
this.serviceMethodHandler.init(service, rootAddress, serviceAddress, responseSendQueue);
this.eventQueue = this.requestQueueBuilder.setName("Event Queue" + serviceMethodHandler.address()).build();
this.handleCallbacks = handleCallbacks;
this.requestQueue = initRequestQueue(serviceMethodHandler, async);
this.systemManager = systemManager;
this.factory = factory();
}
public static ServiceQueue currentService() {
return serviceThreadLocal.get();
}
@Override
public void start() {
start(serviceMethodHandler, true);
}
public ServiceQueue startServiceQueue() {
start(serviceMethodHandler, true);
return this;
}
public ServiceQueue start(boolean joinEventManager) {
start(serviceMethodHandler, joinEventManager);
return this;
}
@Override
public Queue<MethodCall<Object>> requestQueue() {
return this.requestQueue;
}
@Override
public Queue<Response<Object>> responseQueue() {
return this.responseQueue;
}
protected Queue<MethodCall<Object>> initRequestQueue(final ServiceMethodHandler serviceMethodHandler, boolean async) {
Queue<MethodCall<Object>> requestQueue;
if (async) {
requestQueue = this.requestQueueBuilder.setName("Send Queue " + serviceMethodHandler.address()).build();
} else {
requestQueue = new Queue<MethodCall<Object>>() {
@Override
public ReceiveQueue<MethodCall<Object>> receiveQueue() {
return null;
}
@Override
public SendQueue<MethodCall<Object>> sendQueue() {
return new SendQueue<MethodCall<Object>>() {
@Override
public boolean send(MethodCall<Object> item) {
return doHandleMethodCall(item, serviceMethodHandler);
}
@Override
public void sendAndFlush(MethodCall<Object> item) {
doHandleMethodCall(item, serviceMethodHandler);
}
@SafeVarargs
@Override
public final void sendMany(MethodCall<Object>... items) {
for (MethodCall<Object> item : items) {
doHandleMethodCall(item, serviceMethodHandler);
}
}
@Override
public void sendBatch(Collection<MethodCall<Object>> items) {
for (MethodCall<Object> item : items) {
doHandleMethodCall(item, serviceMethodHandler);
}
}
@Override
public void sendBatch(Iterable<MethodCall<Object>> items) {
for (MethodCall<Object> item : items) {
doHandleMethodCall(item, serviceMethodHandler);
}
}
@Override
public boolean shouldBatch() {
return false;
}
@Override
public void flushSends() {
}
@Override
public int size() {
return 0;
}
};
}
@Override
public void startListener(ReceiveQueueListener<MethodCall<Object>> listener) {
}
@Override
public void stop() {
}
@Override
public int size() {
return 0;
}
};
}
return requestQueue;
}
public ServiceQueue startCallBackHandler() {
if (!handleCallbacks) {
/** Need to make this configurable. */
callbackManager.startReturnHandlerProcessor(this.responseQueue);
return this;
} else {
throw new IllegalStateException("Unable to handle callbacks in a new thread when handleCallbacks is set");
}
}
public BaseServiceQueueImpl requestObjectTransformer(Transformer<Request, Object> requestObjectTransformer) {
this.requestObjectTransformer = requestObjectTransformer;
return this;
}
public BaseServiceQueueImpl responseObjectTransformer(Transformer<Response<Object>, Response> responseObjectTransformer) {
this.responseObjectTransformer = responseObjectTransformer;
return this;
}
/**
* This method is where all of the action is.
*
* @param methodCall methodCall
* @param serviceMethodHandler handler
*/
private boolean doHandleMethodCall(MethodCall<Object> methodCall,
final ServiceMethodHandler serviceMethodHandler) {
if (debug) {
logger.debug("ServiceImpl::doHandleMethodCall() METHOD CALL" + methodCall);
}
if (callbackManager != null) {
callbackManager.registerCallbacks(methodCall);
}
//inputQueueListener.receive(methodCall);
final boolean continueFlag[] = new boolean[1];
methodCall = beforeMethodProcessing(methodCall, continueFlag);
if (continueFlag[0]) {
if (debug) logger.debug("ServiceImpl::doHandleMethodCall() before handling stopped processing");
return false;
}
Response<Object> response = serviceMethodHandler.receiveMethodCall(methodCall);
// if (debug) {
// logger.debug("ServiceImpl::receive() \nRESPONSE\n" + response + "\nFROM CALL\n" + methodCall + " name " + methodCall.name() + "\n\n");
// }
if (response != ServiceConstants.VOID) {
if (!afterMethodCall.after(methodCall, response)) {
return false;
}
//noinspection unchecked
response = responseObjectTransformer.transform(response);
if (!afterMethodCallAfterTransform.after(methodCall, response)) {
return false;
}
if (!responseSendQueue.send(response)) {
logger.error("Unable to send response {} for method {} for object {}",
response,
methodCall.name(),
methodCall.objectName());
}
}
return false;
}
private void start(final ServiceMethodHandler serviceMethodHandler,
final boolean joinEventManager) {
if (started.get()) {
logger.warn("Service {} already started. It will not start twice.", name());
return;
}
logger.info("Starting service {}", name());
started.set(true);
final ReceiveQueue<Response<Object>> responseReceiveQueue =
this.handleCallbacks ?
responseQueue.receiveQueue() : null;
if (handleCallbacks) {
}
final ReceiveQueue<Event<Object>> eventReceiveQueue =
eventQueue.receiveQueue();
serviceThreadLocal.set(this);
if (!(service instanceof EventManager)) {
if (joinEventManager) {
serviceContext().joinEventManager();
}
}
serviceMethodHandler.queueInit();
flushEventManagerCalls();
serviceThreadLocal.set(null);
requestQueue.startListener(new ReceiveQueueListener<MethodCall<Object>>() {
@Override
public void init() {
serviceThreadLocal.set(BaseServiceQueueImpl.this);
queueCallBackHandler.queueInit();
serviceMethodHandler.init();
}
@Override
public void receive(MethodCall<Object> methodCall) {
queueCallBackHandler.beforeReceiveCalled();
doHandleMethodCall(methodCall, serviceMethodHandler);
queueCallBackHandler.afterReceiveCalled();
}
@Override
public void empty() {
serviceThreadLocal.set(BaseServiceQueueImpl.this);
handle();
serviceMethodHandler.empty();
queueCallBackHandler.queueEmpty();
}
@Override
public void startBatch() {
serviceThreadLocal.set(BaseServiceQueueImpl.this);
serviceMethodHandler.startBatch();
queueCallBackHandler.queueStartBatch();
}
@Override
public void limit() {
serviceThreadLocal.set(BaseServiceQueueImpl.this);
handle();
serviceMethodHandler.limit();
queueCallBackHandler.queueLimit();
}
@Override
public void shutdown() {
serviceThreadLocal.set(BaseServiceQueueImpl.this);
handle();
serviceMethodHandler.shutdown();
queueCallBackHandler.queueShutdown();
serviceThreadLocal.set(null);
}
@Override
public void idle() {
serviceThreadLocal.set(BaseServiceQueueImpl.this);
handle();
serviceMethodHandler.idle();
queueCallBackHandler.queueIdle();
if (callbackManager!=null) {
callbackManager.process(0);
}
serviceThreadLocal.set(null);
}
/** Such a small method with so much responsibility. */
public void handle() {
manageResponseQueue();
handleCallBacks(responseReceiveQueue);
handleEvents(eventReceiveQueue, serviceMethodHandler);
}
});
}
private void handleEvents(ReceiveQueue<Event<Object>> eventReceiveQueue, ServiceMethodHandler serviceMethodHandler) {
/* Handles the event processing. */
Event<Object> event = eventReceiveQueue.poll();
while (event != null) {
serviceMethodHandler.handleEvent(event);
event = eventReceiveQueue.poll();
}
flushEventManagerCalls();
}
private void handleCallBacks(ReceiveQueue<Response<Object>> responseReceiveQueue) {
/* Handles the CallBacks if you have configured the service
to handle its own callbacks.
Callbacks can be handled in a separate thread or the same
thread the manages the service.
*/
if (handleCallbacks) {
Response<Object> response = responseReceiveQueue.poll();
while (response != null) {
callbackManager.handleResponse(response);
response = responseReceiveQueue.poll();
}
}
}
private void flushEventManagerCalls() {
final EventManager eventManager = factory.eventManagerProxy();
if (eventManager != null) {
ServiceProxyUtils.flushServiceProxy(eventManager);
factory.clearEventManagerProxy();
}
}
private void manageResponseQueue() {
long now = Timer.timer().now();
if (now - lastResponseFlushTime > 50) {
lastResponseFlushTime = now;
responseSendQueue.flushSends();
}
}
private MethodCall<Object> beforeMethodProcessing(MethodCall<Object> methodCall, boolean[] continueFlag) {
if (!beforeMethodCall.before(methodCall)) {
continueFlag[0] = false;
}
if (requestObjectTransformer != null && requestObjectTransformer != ServiceConstants.NO_OP_ARG_TRANSFORM) {
final Object arg = requestObjectTransformer.transform(methodCall);
methodCall = MethodCallBuilder.transformed(methodCall, arg);
}
if (beforeMethodCallAfterTransform != null && beforeMethodCallAfterTransform != ServiceConstants.NO_OP_BEFORE_METHOD_CALL) {
if (!beforeMethodCallAfterTransform.before(methodCall)) {
continueFlag[0] = false;
}
}
return methodCall;
}
@Override
public SendQueue<MethodCall<Object>> requests() {
return requestQueue.sendQueue();
}
@Override
public SendQueue<MethodCall<Object>> requestsWithAutoFlush(int flushInterval, TimeUnit timeUnit) {
return requestQueue.sendQueueWithAutoFlush(flushInterval, timeUnit);
}
@Override
public ReceiveQueue<Response<Object>> responses() {
return responseQueue.receiveQueue();
}
@Override
public String name() {
return serviceMethodHandler.name();
}
@Override
public String address() {
return serviceMethodHandler.address();
}
@Override
public void stop() {
started.set(false);
try {
if (requestQueue != null) requestQueue.stop();
} catch (Exception ex) {
if (debug) logger.debug("Unable to stop request queue", ex);
}
try {
if (responseQueue != null) responseQueue.stop();
} catch (Exception ex) {
if (debug) logger.debug("Unable to stop response queues", ex);
}
if (systemManager != null) this.systemManager.serviceShutDown();
}
@Override
public Collection<String> addresses(String address) {
return this.serviceMethodHandler.addresses();
}
@Override
public void flush() {
lastResponseFlushTime = 0;
manageResponseQueue();
}
private AtomicBoolean failing = new AtomicBoolean();
@Override
public boolean failing() {
return failing.get();
}
@Override
public void setFailing() {
failing.set(true);
}
@Override
public void recover() {
failing.set(false);
}
public Object service() {
return service;
}
public <T> T createProxyWithAutoFlush(Class<T> serviceInterface, int interval, TimeUnit timeUnit) {
final SendQueue<MethodCall<Object>> methodCallSendQueue = requestQueue.sendQueueWithAutoFlush(interval, timeUnit);
methodCallSendQueue.start();
return proxy(serviceInterface, methodCallSendQueue);
}
public <T> T createProxyWithAutoFlush(final Class<T> serviceInterface,
final PeriodicScheduler periodicScheduler,
final int interval, final TimeUnit timeUnit) {
final SendQueue<MethodCall<Object>> methodCallSendQueue =
requestQueue.sendQueueWithAutoFlush(periodicScheduler, interval, timeUnit);
methodCallSendQueue.start();
return proxy(serviceInterface, methodCallSendQueue);
}
public <T> T createProxy(Class<T> serviceInterface) {
final SendQueue<MethodCall<Object>> methodCallSendQueue = requestQueue.sendQueue();
return proxy(serviceInterface, methodCallSendQueue);
}
private <T> T proxy(Class<T> serviceInterface, final SendQueue<MethodCall<Object>> methodCallSendQueue) {
final String uuid = serviceInterface.getName() + "::" + UUID.randomUUID().toString();
if (!started.get()) {
logger.info("ServiceQueue::create(...), A proxy is being asked for a service that is not started ", name());
}
InvocationHandler invocationHandler = new InvocationHandler() {
private long messageId = 0;
private long timestamp = Timer.timer().now();
private int times = 10;
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if (method.getName().equals("toString")) {
return "PROXY OBJECT " + address();
}
if (method.getName().equals("clientProxyFlush")) {
methodCallSendQueue.flushSends();
return null;
}
if (method.getName().equals("stop")) {
methodCallSendQueue.stop();
return null;
}
messageId++;
times--;
if (times == 0) {
timestamp = Timer.timer().now();
times = 10;
} else {
timestamp++;
}
final MethodCallLocal call = new MethodCallLocal(method.getName(), uuid, timestamp, messageId, args);
methodCallSendQueue.send(call);
return null;
}
};
final Object o = Proxy.newProxyInstance(serviceInterface.getClassLoader(),
new Class[]{serviceInterface, ClientProxy.class}, invocationHandler
);
//noinspection unchecked
return (T) o;
}
@Override
public SendQueue<Event<Object>> events() {
return this.eventQueue.sendQueueWithAutoFlush(50, TimeUnit.MILLISECONDS);
}
@Override
public String toString() {
return "ServiceQueue{" +
"service=" + service.getClass().getSimpleName() +
'}';
}
static class MethodCallLocal implements MethodCall<Object> {
private final String name;
private final long timestamp;
private final Object[] arguments;
private final String uuid;
private final long messageId;
private final boolean hasCallback;
@Override
public boolean hasCallback() {
return hasCallback;
}
public MethodCallLocal(final String name, final String uuid,
final long timestamp, final long messageId, final Object[] args) {
this.name = name;
this.timestamp = timestamp;
this.arguments = args;
this.uuid = uuid;
this.messageId = messageId;
this.hasCallback = detectCallback();
}
private boolean detectCallback() {
final Object[] args = arguments;
if (args == null) {
return false;
}
for (int index = 0; index < args.length; index++) {
if (args[index] instanceof Callback) {
return true;
}
}
return false;
}
@Override
public String name() {
return name;
}
@Override
public String address() {
return name;
}
@Override
public String returnAddress() {
return uuid;
}
@Override
public MultiMap<String, String> params() {
return null;
}
@Override
public MultiMap<String, String> headers() {
return null;
}
@Override
public boolean hasParams() {
return false;
}
@Override
public boolean hasHeaders() {
return false;
}
@Override
public long timestamp() {
return timestamp;
}
@Override
public boolean isHandled() {
return false;
}
@Override
public void handled() {
}
@Override
public String objectName() {
return "";
}
@Override
public Request<Object> originatingRequest() {
return null;
}
@Override
public long id() {
return messageId;
}
@Override
public Object body() {
return arguments;
}
@Override
public boolean isSingleton() {
return true;
}
}
}
| apache-2.0 |
deleidos/digitaledge-platform | webapp-proxy/src/main/java/com/deleidos/rtws/webapp/auth/registration/RegistrationUserDetailsService.java | 14025 | /**
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "{}"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright {yyyy} {name of copyright owner}
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.deleidos.rtws.webapp.auth.registration;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.deleidos.rtws.webapp.auth.TmsProxyUser;
import com.deleidos.rtws.webapp.client.RestClientException;
import com.deleidos.rtws.webapp.client.RestClientManager;
import com.deleidos.rtws.webapp.client.UUIDClient;
public class RegistrationUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if(StringUtils.isBlank(username)) {
throw new UsernameNotFoundException("No API Key Provided");
}
UUIDClient registrationClientService = RestClientManager.getUUIDClient();
boolean isValidRegistrationKey = false;
Throwable validationErrorCause = null;
try {
isValidRegistrationKey = registrationClientService.validate(username);
} catch (RestClientException rce) {
isValidRegistrationKey = false;
validationErrorCause = rce;
}
if(!isValidRegistrationKey) {
throw new BadCredentialsException("Invalid API Key", validationErrorCause);
}
String tenantId = null;
try {
tenantId = registrationClientService.getTenantId(username);
} catch (RestClientException rce) {
throw new AuthenticationServiceException("Failed to validate the API Key", rce);
}
// Note: The tenantId may be null at this point indicating that this UUID is known,
// but not yet associated with a tenantId. Downstream services should dictate if this is valid or not.
return new TmsProxyUser(username, AuthorityUtils.createAuthorityList(new String[]{TmsProxyUser.TENANT_PROXY_USER_ROLE_NAME}), tenantId);
}
}
| apache-2.0 |
porcelli-forks/kie-wb-common | kie-wb-common-services/kie-wb-common-datamodel/kie-wb-common-datamodel-backend/src/test/java/org/kie/workbench/common/services/datamodel/backend/server/builder/projects/JavaTypeSystemTranslatorTest.java | 1418 | package org.kie.workbench.common.services.datamodel.backend.server.builder.projects;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class JavaTypeSystemTranslatorTest {
private JavaTypeSystemTranslator translator;
@Parameterized.Parameters(name = "JavaClass={0}, TranslatedType={1}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{Integer.class, "Integer"},
{Boolean.class, "Boolean"},
{BigDecimal.class, "BigDecimal"},
{Date.class, "Date"},
{LocalDate.class, "LocalDate"},
{LocalDateTime.class, "Comparable"}
});
}
@Parameterized.Parameter(0)
public Class javaClass;
@Parameterized.Parameter(1)
public String translatedType;
@Before
public void setUp() throws Exception {
translator = new JavaTypeSystemTranslator();
}
@Test
public void testTranslateToGenericType() {
Assertions.assertThat(translator.translateClassToGenericType(javaClass)).isEqualTo(translatedType);
}
}
| apache-2.0 |
iotivity/iotivity | test/src/automation/robot/device_lib/src/org/iotivity/test/rfw/common/devicecontroller/datamodel/Coordinate.java | 1217 | /******************************************************************
*
* Copyright 2018 Samsung Electronics All Rights Reserved.
*
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
******************************************************************/
package org.iotivity.test.rfw.common.devicecontroller.datamodel;
public class Coordinate {
private float x;
private float y;
public Coordinate(float x, float y) {
this.x = x;
this.y = y;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
}
| apache-2.0 |
subutai-io/base | management/server/core/environment-manager/environment-manager-impl/src/test/java/io/subutai/core/environment/impl/workflow/creation/steps/SetupP2PStepTest.java | 1815 | package io.subutai.core.environment.impl.workflow.creation.steps;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.subutai.common.environment.Topology;
import io.subutai.common.peer.Peer;
import io.subutai.common.util.PeerUtil;
import io.subutai.core.environment.impl.TestHelper;
import io.subutai.core.environment.impl.entity.LocalEnvironment;
import io.subutai.core.peer.api.PeerManager;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith( MockitoJUnitRunner.class )
public class SetupP2PStepTest
{
SetupP2PStep step;
@Mock
Topology topology;
LocalEnvironment environment = TestHelper.ENVIRONMENT();
@Mock
PeerUtil<Object> peerUtil;
@Mock
PeerUtil.PeerTaskResults<Object> peerTaskResults;
@Mock
PeerUtil.PeerTaskResult peerTaskResult;
@Mock
PeerManager peerManager;
Peer peer = TestHelper.PEER();
@Before
public void setUp() throws Exception
{
step = new SetupP2PStep( topology, environment, TestHelper.TRACKER_OPERATION() );
step.peerUtil = peerUtil;
TestHelper.bind( environment, peer, peerUtil, peerTaskResults, peerTaskResult );
Map<String, Set<String>> peerRhIds = Maps.newHashMap();
peerRhIds.put( peer.getId(), Sets.newHashSet(TestHelper.RH_ID) );
doReturn(peerRhIds).when( topology ).getPeerRhIds();
}
@Test
public void testExecute() throws Exception
{
step.execute();
verify( peerUtil, times( 2 ) ).executeParallel();
}
}
| apache-2.0 |
apache/sqoop | src/test/org/apache/sqoop/hive/numerictypes/NumericTypesHiveImportTestBase.java | 2976 | /**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.sqoop.hive.numerictypes;
import org.apache.sqoop.hive.minicluster.HiveMiniCluster;
import org.apache.sqoop.importjob.configuration.HiveTestConfiguration;
import org.apache.sqoop.importjob.numerictypes.NumericTypesImportTestBase;
import org.apache.sqoop.testutil.ArgumentArrayBuilder;
import org.apache.sqoop.testutil.HiveServer2TestUtil;
import org.apache.sqoop.testutil.NumericTypesTestUtils;
import static java.util.Arrays.deepEquals;
import static org.junit.Assert.assertTrue;
public abstract class NumericTypesHiveImportTestBase<T extends HiveTestConfiguration> extends NumericTypesImportTestBase<T> {
public NumericTypesHiveImportTestBase(T configuration, boolean failWithoutExtraArgs, boolean failWithPaddingOnly,
HiveMiniCluster hiveMiniCluster, HiveServer2TestUtil hiveServer2TestUtil) {
super(configuration, failWithoutExtraArgs, failWithPaddingOnly);
this.hiveServer2TestUtil = hiveServer2TestUtil;
this.hiveMiniCluster = hiveMiniCluster;
}
private final HiveMiniCluster hiveMiniCluster;
private final HiveServer2TestUtil hiveServer2TestUtil;
@Override
public ArgumentArrayBuilder getArgsBuilder() {
ArgumentArrayBuilder builder = new ArgumentArrayBuilder()
.withCommonHadoopFlags()
.withProperty("parquetjob.configurator.implementation", "hadoop")
.withOption("connect", getAdapter().getConnectionString())
.withOption("table", getTableName())
.withOption("hive-import")
.withOption("hs2-url", hiveMiniCluster.getUrl())
.withOption("num-mappers", "1")
.withOption("as-parquetfile")
.withOption("delete-target-dir");
NumericTypesTestUtils.addEnableParquetDecimal(builder);
return builder;
}
@Override
public void verify() {
// The result contains a byte[] so we have to use Arrays.deepEquals() to assert.
Object[] firstRow = hiveServer2TestUtil.loadRawRowsFromTable(getTableName()).iterator().next().toArray();
Object[] expectedResultsForHive = getConfiguration().getExpectedResultsForHive();
assertTrue(deepEquals(expectedResultsForHive, firstRow));
}
}
| apache-2.0 |
whiskeysierra/riptide | riptide-spring-boot-autoconfigure/src/test/java/org/zalando/riptide/autoconfigure/HttpMessageConvertersTest.java | 1644 | package org.zalando.riptide.autoconfigure;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.core.IsCollectionContaining.hasItem;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
@SpringBootTest(classes = DefaultTestConfiguration.class, webEnvironment = NONE)
@Component
final class HttpMessageConvertersTest {
@Autowired
@Qualifier("example")
private ClientHttpMessageConverters unit;
@Test
void shouldRegisterOnlyRegisteredConverters() {
final List<HttpMessageConverter<?>> converters = unit.getConverters();
assertThat(converters, hasSize(3));
assertThat(converters, hasItem(instanceOf(StringHttpMessageConverter.class)));
assertThat(converters, hasItem(instanceOf(MappingJackson2HttpMessageConverter.class)));
assertThat(converters, hasItem(hasToString(containsString("StreamConverter"))));
}
}
| apache-2.0 |
OpenNTF/WorkflowForXPages | source/com.ibm.activiti/src/org/restlet/ext/servlet/internal/ServletCall.java | 13675 | /**
* Copyright 2005-2012 Restlet S.A.S.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL
* 1.0 (the "Licenses"). You can select the license that you prefer but you may
* not use this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the Apache 2.0 license at
* http://www.opensource.org/licenses/apache-2.0
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.restlet.com/products/restlet-framework
*
* Restlet is a registered trademark of Restlet S.A.S.
*/
package org.restlet.ext.servlet.internal;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Server;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Parameter;
import org.restlet.data.Protocol;
import org.restlet.data.Status;
import org.restlet.engine.http.ServerCall;
import org.restlet.engine.http.header.HeaderConstants;
import org.restlet.engine.http.header.LanguageReader;
import org.restlet.engine.http.io.UnclosableInputStream;
import org.restlet.engine.http.io.UnclosableOutputStream;
import org.restlet.ext.servlet.ServletUtils;
import org.restlet.representation.Representation;
import org.restlet.util.Series;
/**
* Call that is used by the Servlet HTTP server connector.
*
* @author Jerome Louvel
*/
public class ServletCall extends ServerCall {
/**
* Returns the Servlet request that was used to generate the given Restlet
* request.
*
* @param request
* The Restlet request.
* @return The Servlet request or null.
* @deprecated Use {@link ServletUtils#getRequest(Request)} instead.
*/
@Deprecated
public static HttpServletRequest getRequest(Request request) {
return ServletUtils.getRequest(request);
}
/** The HTTP Servlet request to wrap. */
private volatile HttpServletRequest request;
/** The request headers. */
private volatile Series<Parameter> requestHeaders;
/** The HTTP Servlet response to wrap. */
private volatile HttpServletResponse response;
/**
* Constructor.
*
* @param server
* The parent server.
* @param request
* The HTTP Servlet request to wrap.
* @param response
* The HTTP Servlet response to wrap.
*/
public ServletCall(Server server, HttpServletRequest request,
HttpServletResponse response) {
super(server);
this.request = request;
this.response = response;
}
/**
* Constructor.
*
* @param serverAddress
* The server IP address.
* @param serverPort
* The server port.
* @param request
* The Servlet request
* @param response
* The Servlet response.
*/
public ServletCall(String serverAddress, int serverPort,
HttpServletRequest request, HttpServletResponse response) {
super(serverAddress, serverPort);
this.request = request;
this.response = response;
}
/**
* Not supported. Always returns false.
*/
@Override
public boolean abort() {
return false;
}
@Override
public String getClientAddress() {
return getRequest().getRemoteAddr();
}
@Override
public int getClientPort() {
// return getRequest().getRemotePort();
return 0;
}
/**
* Returns the server domain name.
*
* @return The server domain name.
*/
@Override
public String getHostDomain() {
return getRequest().getServerName();
}
/**
* Returns the request method.
*
* @return The request method.
*/
@Override
public String getMethod() {
return getRequest().getMethod();
}
/**
* Returns the server protocol.
*
* @return The server protocol.
*/
@Override
public Protocol getProtocol() {
return Protocol.valueOf(getRequest().getScheme());
}
/**
* Returns the HTTP Servlet request.
*
* @return The HTTP Servlet request.
*/
public HttpServletRequest getRequest() {
return this.request;
}
@Override
public ReadableByteChannel getRequestEntityChannel(long size) {
// Can't do anything
return null;
}
@Override
public InputStream getRequestEntityStream(long size) {
try {
return new UnclosableInputStream(getRequest().getInputStream());
} catch (IOException e) {
return null;
}
}
@Override
public ReadableByteChannel getRequestHeadChannel() {
// Not available
return null;
}
/**
* Returns the list of request headers.
*
* @return The list of request headers.
*/
@Override
@SuppressWarnings("unchecked")
public Series<Parameter> getRequestHeaders() {
if (this.requestHeaders == null) {
this.requestHeaders = new Form();
// Copy the headers from the request object
String headerName;
String headerValue;
for (final Enumeration<String> names = getRequest()
.getHeaderNames(); names.hasMoreElements();) {
headerName = names.nextElement();
for (final Enumeration<String> values = getRequest()
.getHeaders(headerName); values.hasMoreElements();) {
headerValue = values.nextElement();
this.requestHeaders.add(new Parameter(headerName,
headerValue));
}
}
}
return this.requestHeaders;
}
@Override
public InputStream getRequestHeadStream() {
// Not available
return null;
}
/**
* Returns the full request URI.
*
* @return The full request URI.
*/
@Override
public String getRequestUri() {
final String queryString = getRequest().getQueryString();
if ((queryString == null) || (queryString.equals(""))) {
return getRequest().getRequestURI();
}
return getRequest().getRequestURI() + '?' + queryString;
}
/**
* Returns the HTTP Servlet response.
*
* @return The HTTP Servlet response.
*/
public HttpServletResponse getResponse() {
return this.response;
}
/**
* Returns the response channel if it exists, null otherwise.
*
* @return The response channel if it exists, null otherwise.
*/
@Override
public WritableByteChannel getResponseEntityChannel() {
// Can't do anything
return null;
}
/**
* Returns the response stream if it exists, null otherwise.
*
* @return The response stream if it exists, null otherwise.
*/
@Override
public OutputStream getResponseEntityStream() {
try {
return new UnclosableOutputStream(getResponse().getOutputStream());
} catch (IOException e) {
return null;
}
}
/**
* Returns the response address.<br>
* Corresponds to the IP address of the responding server.
*
* @return The response address.
*/
@Override
public String getServerAddress() {
return getRequest().getLocalAddr();
}
/**
* Returns the server port.
*
* @return The server port.
*/
@Override
public int getServerPort() {
return getRequest().getServerPort();
}
@Override
public String getSslCipherSuite() {
return (String) getRequest().getAttribute(
"javax.servlet.request.cipher_suite");
}
@Override
public List<Certificate> getSslClientCertificates() {
final Certificate[] certificateArray = (Certificate[]) getRequest()
.getAttribute("javax.servlet.request.X509Certificate");
if (certificateArray != null) {
return Arrays.asList(certificateArray);
}
return null;
}
@Override
public Integer getSslKeySize() {
Integer keySize = (Integer) getRequest().getAttribute(
"javax.servlet.request.key_size");
if (keySize == null) {
keySize = super.getSslKeySize();
}
return keySize;
}
@Override
public String getSslSessionId() {
Object sessionId = getRequest().getAttribute(
"javax.servlet.request.ssl_session_id");
if ((sessionId != null) && (sessionId instanceof String)) {
return (String) sessionId;
}
/*
* The following is for the non-standard, pre-Servlet 3 spec used by
* Tomcat/Coyote.
*/
sessionId = getRequest().getAttribute(
"javax.servlet.request.ssl_session");
if (sessionId instanceof String) {
return (String) sessionId;
}
return null;
}
@Override
public Principal getUserPrincipal() {
return getRequest().getUserPrincipal();
}
@Override
public String getVersion() {
String result = null;
final int index = getRequest().getProtocol().indexOf('/');
if (index != -1) {
result = getRequest().getProtocol().substring(index + 1);
}
return result;
}
/**
* Indicates if the request was made using a confidential mean.<br>
*
* @return True if the request was made using a confidential mean.<br>
*/
@Override
public boolean isConfidential() {
return getRequest().isSecure();
}
/**
* Sends the response back to the client. Commits the status, headers and
* optional entity and send them on the network.
*
* @param response
* The high-level response.
*/
@Override
public void sendResponse(Response response) throws IOException {
// Set the status code in the response. We do this after adding the
// headers because when we have to rely on the 'sendError' method,
// the Servlet containers are expected to commit their response.
if (Status.isError(getStatusCode()) && (response.getEntity() == null)) {
try {
// Add the response headers
Parameter header;
for (Iterator<Parameter> iter = getResponseHeaders().iterator(); iter
.hasNext();) {
header = iter.next();
// We don't need to set the content length, especially
// because it could send the response too early on some
// containers (ex: Tomcat 5.0).
if (!header.getName().equals(
HeaderConstants.HEADER_CONTENT_LENGTH)) {
getResponse().addHeader(header.getName(),
header.getValue());
}
}
getResponse().sendError(getStatusCode(), getReasonPhrase());
} catch (IOException ioe) {
getLogger().log(Level.WARNING,
"Unable to set the response error status", ioe);
}
} else {
// Send the response entity
getResponse().setStatus(getStatusCode());
// Add the response headers after setting the status because
// otherwise some containers (ex: Tomcat 5.0) immediately send
// the response if a "Content-Length: 0" header is found.
Parameter header;
Parameter contentLengthHeader = null;
for (Iterator<Parameter> iter = getResponseHeaders().iterator(); iter
.hasNext();) {
header = iter.next();
if (header.getName().equals(
HeaderConstants.HEADER_CONTENT_LENGTH)) {
contentLengthHeader = header;
} else {
getResponse()
.addHeader(header.getName(), header.getValue());
}
}
if (contentLengthHeader != null) {
getResponse().addHeader(contentLengthHeader.getName(),
contentLengthHeader.getValue());
}
super.sendResponse(response);
}
}
}
| apache-2.0 |
bbossgroups/bbossgroups-3.5 | bboss-websocket/src/org/frameworkset/web/socket/inf/SubProtocolCapable.java | 211 | package org.frameworkset.web.socket.inf;
import java.util.List;
public interface SubProtocolCapable {
/**
* Return the list of supported sub-protocols.
*/
List<String> getSubProtocols();
}
| apache-2.0 |
jonpasski/corvus-annotations | bundles/us.coastalhacking.corvus.annotations.ui.e3/src/us/coastalhacking/corvus/annotations/ui/e3/AbstractTextMarkerField.java | 724 | package us.coastalhacking.corvus.annotations.ui.e3;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.ui.views.markers.MarkerField;
import org.eclipse.ui.views.markers.MarkerItem;
import us.coastalhacking.corvus.annotations.Markers;
public abstract class AbstractTextMarkerField extends MarkerField {
protected String markerType;
protected String markerAttribute;
@Override
public EditingSupport getEditingSupport(ColumnViewer viewer) {
return new TextFieldEditingSupport(viewer, markerType, markerAttribute);
}
@Override
public String getValue(MarkerItem item) {
return item.getAttributeValue(markerAttribute, Markers.EMPTY_STRING);
}
}
| apache-2.0 |
derekhiggins/ovirt-engine | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/UserMessageController.java | 2396 | package org.ovirt.engine.core.bll;
import java.util.LinkedList;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.DbUser;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.MultiValueMapUtils;
public class UserMessageController {
private final static UserMessageController _instance = new UserMessageController();
private final java.util.HashMap<Guid, List<String>> mUsersMessages = new java.util.HashMap<Guid, List<String>>();
public static UserMessageController getInstance() {
return _instance;
}
public void AddUserMessage(Guid user, String userMessage) {
MultiValueMapUtils.addToMap(user, userMessage, mUsersMessages);
}
public void AddUserMessageByVds(Guid vdsId, String userMessage) {
List<Guid> users = new LinkedList<Guid>();
for (VmDynamic vm : DbFacade.getInstance().getVmDynamicDAO().getAllRunningForVds(vdsId)) {
AddVmUsersToList(users, vm.getId());
}
AddUsersMessages(users, userMessage);
}
public void AddUserMessageByVm(Guid vmId, String userMessage) {
List<Guid> users = new LinkedList<Guid>();
AddVmUsersToList(users, vmId);
AddUsersMessages(users, userMessage);
}
private static void AddVmUsersToList(List<Guid> input, Guid vmId) {
List<DbUser> users = DbFacade.getInstance().getDbUserDAO()
.getAllForVm(vmId);
if (users != null) {
for (DbUser user : users) {
if (!input.contains((user.getuser_id()))) {
input.add(user.getuser_id());
}
}
}
}
private void AddUsersMessages(Iterable<Guid> users, String message) {
for (Guid userId : users) {
AddUserMessage(userId, message);
}
}
public String GetUserMessage(Guid user) {
if (mUsersMessages.containsKey(user)) {
List<String> userMessages = mUsersMessages.get(user);
StringBuilder builder = new StringBuilder();
for (String message : userMessages) {
builder.append(message);
builder.append("\n");
}
mUsersMessages.remove(user);
}
return "";
}
}
| apache-2.0 |
jtulach/teavm | core/src/main/java/org/teavm/vm/spi/Before.java | 971 | /*
* Copyright 2015 Alexey Andreev.
*
* 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.teavm.vm.spi;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author Alexey Andreev
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Before {
Class<? extends TeaVMPlugin>[] value();
}
| apache-2.0 |
taochaoqiang/druid | processing/src/main/java/io/druid/query/aggregation/AggregateCombiner.java | 3784 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.query.aggregation;
import io.druid.query.monomorphicprocessing.RuntimeShapeInspector;
import io.druid.segment.ColumnValueSelector;
/**
* AggregateCombiner is used to fold rollup aggregation results from serveral "rows" of different indexes during index
* merging (see {@link io.druid.segment.IndexMerger}).
*
* The state of the implementations of this interface is an aggregation value (either a primitive or an object), that
* could be queried via {@link ColumnValueSelector}'s methods. Before {@link #reset} is ever called on an
* AggregateCombiner, it's state is undefined and {@link ColumnValueSelector}'s methods could return something random,
* or null, or throw an exception.
*
* This interface would probably better be called "AggregateFolder", but somebody may confuse it with "folder" as
* "directory" synonym.
*
* @see AggregatorFactory#makeAggregateCombiner()
* @see LongAggregateCombiner
* @see DoubleAggregateCombiner
* @see ObjectAggregateCombiner
*/
public interface AggregateCombiner<T> extends ColumnValueSelector<T>
{
/**
* Resets this AggregateCombiner's state value to the value of the given selector, e. g. after calling this method
* combiner.get*() should return the same value as selector.get*().
*
* If the selector is an {@link io.druid.segment.ObjectColumnSelector}, the object returned from {@link
* io.druid.segment.ObjectColumnSelector#getObject()} must not be modified, and must not become a subject for
* modification during subsequent {@link #fold} calls.
*/
@SuppressWarnings("unused") // Going to be used when https://github.com/druid-io/druid/projects/2 is complete
void reset(ColumnValueSelector selector);
/**
* Folds this AggregateCombiner's state value with the value of the given selector and saves it in this
* AggregateCombiner's state, e. g. after calling combiner.fold(selector), combiner.get*() should return the value
* that would be the result of {@link AggregatorFactory#combine
* aggregatorFactory.combine(combiner.get*(), selector.get*())} call.
*
* Unlike {@link AggregatorFactory#combine}, if the selector is an {@link io.druid.segment.ObjectColumnSelector}, the
* object returned from {@link io.druid.segment.ObjectColumnSelector#getObject()} must not be modified, and must not
* become a subject for modification during subsequent fold() calls.
*
* Since the state of AggregateCombiner is undefined before {@link #reset} is ever called on it, the effects of
* calling fold() are also undefined in this case.
*
* @see AggregatorFactory#combine
*/
@SuppressWarnings("unused") // Going to be used when https://github.com/druid-io/druid/projects/2 is complete
void fold(ColumnValueSelector selector);
@Override
default boolean isNull()
{
return false;
}
@Override
default void inspectRuntimeShape(RuntimeShapeInspector inspector)
{
// Usually AggregateCombiner has nothing to inspect
}
}
| apache-2.0 |
emergentone/10-dependencies | src/test/java/org/gradle/tests13/Test13_7.java | 163 | package org.gradle.tests13;
import org.junit.Test;
public class Test13_7 {
@Test
public void myTest() throws Exception {
Thread.sleep(5);
}
} | apache-2.0 |
redox/OrientDB | core/src/main/java/com/orientechnologies/orient/core/sql/functions/misc/OSQLFunctionFormat.java | 1628 | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.sql.functions.misc;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.sql.functions.OSQLFunctionAbstract;
/**
* Formats content.
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*
*/
public class OSQLFunctionFormat extends OSQLFunctionAbstract {
public static final String NAME = "format";
public OSQLFunctionFormat() {
super(NAME, 2, -1);
}
public Object execute(OIdentifiable iCurrentRecord, final Object[] iParameters, OCommandExecutor iRequester) {
final Object[] args = new Object[iParameters.length - 1];
for (int i = 0; i < args.length; ++i)
args[i] = iParameters[i + 1];
return String.format((String) iParameters[0], args);
}
public String getSyntax() {
return "Syntax error: format(<format>, <arg1> [,<argN>]*)";
}
}
| apache-2.0 |
apache/river | src/net/jini/jeri/BasicInvocationDispatcher.java | 53372 | /*
* 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 net.jini.jeri;
import com.sun.jini.action.GetBooleanAction;
import com.sun.jini.jeri.internal.runtime.Util;
import com.sun.jini.jeri.internal.runtime.WeakKey;
import com.sun.jini.logging.Levels;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.ref.ReferenceQueue;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.ServerError;
import java.rmi.ServerException;
import java.rmi.UnmarshalException;
import java.rmi.server.ExportException;
import java.rmi.server.ServerNotActiveException;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permission;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.security.auth.Subject;
import net.jini.core.constraint.Integrity;
import net.jini.core.constraint.InvocationConstraint;
import net.jini.core.constraint.InvocationConstraints;
import net.jini.core.constraint.MethodConstraints;
import net.jini.export.ServerContext;
import net.jini.io.MarshalInputStream;
import net.jini.io.MarshalOutputStream;
import net.jini.io.UnsupportedConstraintException;
import net.jini.io.context.ClientSubject;
import net.jini.security.AccessPermission;
import net.jini.security.proxytrust.ProxyTrust;
import net.jini.security.proxytrust.ProxyTrustVerifier;
import net.jini.security.proxytrust.ServerProxyTrust;
/**
* A basic implementation of the {@link InvocationDispatcher} interface,
* providing preinvocation access control for
* remote objects exported using {@link BasicJeriExporter}.
*
* <p>This invocation dispatcher handles incoming remote method invocations
* initiated by proxies using {@link BasicInvocationHandler}, and expects
* that a dispatched request, encapsulated in the {@link InboundRequest}
* object passed to the {@link #dispatch dispatch} method, was sent using
* the protocol implemented by <code>BasicInvocationHandler</code>.
*
* <p>A basic permission-based preinvocation access control mechanism is
* provided. A permission class can be specified when an invocation
* dispatcher is constructed; instances of that class are constructed using
* either a {@link Method} instance or a <code>String</code> representing
* the remote method being invoked. The class can have a constructor with a
* <code>Method</code> parameter to permit an arbitrary mapping to the
* actual permission target name and actions; otherwise, the class must
* have a constructor taking the fully qualified name of the remote method
* as a <code>String</code>. For each incoming call on a remote object, the
* client subject must be granted the associated permission for that remote
* method. (Access control for an individual remote method can effectively
* be disabled by granting the associated permission to all protection
* domains.) A simple subclass of {@link AccessPermission} is typically
* used as the permission class.
*
* <p>Other access control mechanisms can be implemented by subclassing this
* class and overriding the various protected methods.
*
* <p>This class is designed to support dispatching remote calls to the
* {@link ProxyTrust#getProxyVerifier ProxyTrust.getProxyVerifier} method
* to the local {@link ServerProxyTrust#getProxyVerifier
* ServerProxyTrust.getProxyVerifier} method of a remote object, to allow a
* remote object to be exported in such a way that its proxy can be
* directly trusted by clients as well as in such a way that its proxy can
* be trusted by clients using {@link ProxyTrustVerifier}.
*
* @author Sun Microsystems, Inc.
* @see BasicInvocationHandler
* @since 2.0
*
* @com.sun.jini.impl
*
* This implementation uses the following system property:
* <dl>
* <dt><code>com.sun.jini.jeri.server.suppressStackTrace</code>
* <dd>If <code>true</code>, removes server-side stack traces before
* marshalling an exception thrown as a result of a remote call. The
* default value is <code>false</code>.
* </dl>
*
* <p>This implementation uses the {@link Logger} named
* <code>net.jini.jeri.BasicInvocationDispatcher</code> to log
* information at the following levels:
*
* <table summary="Describes what is logged by BasicInvocationDispatcher at
* various logging levels" border=1 cellpadding=5>
*
* <tr> <th> Level <th> Description
*
* <tr> <td> {@link Levels#FAILED FAILED} <td> exception that caused a request
* to be aborted
*
* <tr> <td> {@link Levels#FAILED FAILED} <td> exceptional result of a
* remote call
*
* <tr> <td> {@link Level#FINE FINE} <td> incoming remote call
*
* <tr> <td> {@link Level#FINE FINE} <td> successful return of remote call
*
* <tr> <td> {@link Level#FINEST FINEST} <td> more detailed information on
* the above (for example, actual argument and return values)
*
* </table>
**/
public class BasicInvocationDispatcher implements InvocationDispatcher {
/** Marshal stream protocol version. */
static final byte VERSION = 0x0;
/** Marshal stream protocol version mismatch. */
static final byte MISMATCH = 0x0;
/** Normal return (with or without return value). */
static final byte RETURN = 0x01;
/** Exceptional return. */
static final byte THROW = 0x02;
/** The class loader used by createMarshalInputStream */
private final ClassLoader loader;
/** The server constraints. */
private final MethodConstraints serverConstraints;
/**
* Constructor for the Permission class, that has either one String
* or one Method parameter, or null.
*/
private final Constructor permConstructor;
/** True if permConstructor has a Method parameter. */
private final boolean permUsesMethod;
/** Map from Method to Permission. */
private final Map permissions;
/** Map from Long method hash to Method, for all remote methods. */
private final Map methods;
/** Map from WeakKey(Subject) to ProtectionDomain. */
private static final Map domains = new HashMap();
/** Reference queue for the weak keys in the domains map. */
private static final ReferenceQueue queue = new ReferenceQueue();
/** dispatch logger */
private static final Logger logger =
Logger.getLogger("net.jini.jeri.BasicInvocationDispatcher");
/**
* Flag to remove server-side stack traces before marshalling
* exceptions thrown by remote invocations to this VM
*/
private static final boolean suppressStackTraces =
((Boolean) AccessController.doPrivileged(new GetBooleanAction(
"com.sun.jini.jeri.server.suppressStackTraces")))
.booleanValue();
/** Empty codesource. */
private static final CodeSource emptyCS =
new CodeSource(null, (Certificate[]) null);
/** ProtectionDomain containing the empty codesource. */
private static final ProtectionDomain emptyPD =
new ProtectionDomain(emptyCS, null, null, null);
/** Cached getClassLoader permission */
private static final Permission getClassLoaderPermission =
new RuntimePermission("getClassLoader");
/**
* Creates an invocation dispatcher to receive incoming remote calls
* for the specified methods, for a server and transport with the
* specified capabilities, enforcing the specified constraints,
* performing preinvocation access control using the specified
* permission class (if any). The specified class loader is used by
* the {@link #createMarshalInputStream createMarshalInputStream}
* method.
*
* <p>For each combination of constraints that might need to be
* enforced (obtained by calling the {@link
* MethodConstraints#possibleConstraints possibleConstraints} method on
* the specified server constraints, or using an empty constraints
* instance if the specified server constraints instance is
* <code>null</code>), calling the {@link
* ServerCapabilities#checkConstraints checkConstraints} method of the
* specified capabilities object with those constraints must return
* constraints containing at most an {@link Integrity} constraint as a
* requirement, or an <code>ExportException</code> is thrown.
*
* @param methods a collection of {@link Method} instances for the
* remote methods
* @param serverCapabilities the transport capabilities of the server
* @param serverConstraints the server constraints, or <code>null</code>
* @param permissionClass the permission class, or <code>null</code>
* @param loader the class loader, or <code>null</code>
*
* @throws SecurityException if the permission class is not
* <code>null</code> and is in a named package and a
* security manager exists and invoking its
* <code>checkPackageAccess</code> method with the package
* name of the permission class throws a
* <code>SecurityException</code>
* @throws IllegalArgumentException if the permission class
* is abstract, is not <code>public</code>, is not a subclass
* of {@link Permission}, or does not have a public
* constructor that has either one <code>String</code>
* parameter or one {@link Method} parameter and has no
* declared exceptions, or if any element of
* <code>methods</code> is not a {@link Method} instance
* @throws NullPointerException if <code>methods</code> or
* <code>serverCapabilities</code> is <code>null</code>, or if
* <code>methods</code> contains a <code>null</code> element
* @throws ExportException if any of the possible server constraints
* cannot be satisfied according to the specified server
* capabilities
**/
public BasicInvocationDispatcher(Collection methods,
ServerCapabilities serverCapabilities,
MethodConstraints serverConstraints,
Class permissionClass,
ClassLoader loader)
throws ExportException
{
if (serverCapabilities == null) {
throw new NullPointerException();
}
this.methods = new HashMap();
this.loader = loader;
for (Iterator iter = methods.iterator(); iter.hasNext(); ) {
Object m = iter.next();
if (m == null) {
throw new NullPointerException("methods contains null");
} else if (!(m instanceof Method)) {
throw new IllegalArgumentException(
"methods must contain only Methods");
}
this.methods.put(new Long(Util.getMethodHash((Method) m)), m);
}
this.serverConstraints = serverConstraints;
if (permissionClass != null) {
Util.checkPackageAccess(permissionClass);
}
permConstructor = getConstructor(permissionClass);
permUsesMethod =
(permConstructor != null &&
permConstructor.getParameterTypes()[0] == Method.class);
permissions = (permConstructor == null ?
null :
new IdentityHashMap(methods.size() + 2));
try {
if (serverConstraints == null) {
checkConstraints(serverCapabilities,
InvocationConstraints.EMPTY);
} else {
Iterator iter = serverConstraints.possibleConstraints();
while (iter.hasNext()) {
checkConstraints(serverCapabilities,
(InvocationConstraints) iter.next());
}
}
} catch (UnsupportedConstraintException e) {
throw new ExportException(
"server does not support some constraints", e);
}
}
/**
* Check that the only unfulfilled requirement is Integrity.
*/
private static void checkConstraints(ServerCapabilities serverCapabilities,
InvocationConstraints constraints)
throws UnsupportedConstraintException
{
InvocationConstraints unfulfilled =
serverCapabilities.checkConstraints(constraints);
for (Iterator i = unfulfilled.requirements().iterator(); i.hasNext();)
{
InvocationConstraint c = (InvocationConstraint) i.next();
if (!(c instanceof Integrity)) {
throw new UnsupportedConstraintException(
"cannot satisfy unfulfilled constraint: " + c);
}
// REMIND: support ConstraintAlternatives containing Integrity?
}
}
/**
* Returns the class loader specified during construction.
*
* @return the class loader
*/
protected final ClassLoader getClassLoader() {
return loader;
}
/**
* Checks that the specified class is a valid permission class for use in
* preinvocation access control.
*
* @param permissionClass the permission class, or <code>null</code>
* @throws IllegalArgumentException if the permission class is abstract,
* is not a subclass of {@link Permission}, or does not have a public
* constructor that has either one <code>String</code> parameter or one
* {@link Method} parameter and has no declared exceptions
**/
public static void checkPermissionClass(Class permissionClass) {
getConstructor(permissionClass);
}
/**
* Checks that the specified class is a subclass of Permission, is
* public, is not abstract, and has the right one-parameter Method or
* String constructor, and returns that constructor, otherwise throws
* IllegalArgumentException.
**/
private static Constructor getConstructor(Class permissionClass) {
if (permissionClass == null) {
return null;
} else {
int mods = permissionClass.getModifiers();
if (!Permission.class.isAssignableFrom(permissionClass) ||
Modifier.isAbstract(mods) || !Modifier.isPublic(mods))
{
throw new IllegalArgumentException("bad permission class");
}
}
try {
Constructor permConstructor =
permissionClass.getConstructor(new Class[]{Method.class});
if (permConstructor.getExceptionTypes().length == 0) {
return permConstructor;
}
} catch (NoSuchMethodException e) {
}
try {
Constructor permConstructor =
permissionClass.getConstructor(new Class[]{String.class});
if (permConstructor.getExceptionTypes().length == 0) {
return permConstructor;
}
} catch (NoSuchMethodException ee) {
}
throw new IllegalArgumentException("bad permission class");
}
/**
* Dispatches the specified inbound request to the specified remote object.
* When used in conjunction with {@link BasicJeriExporter}, this
* method is called in a context that has the security context and
* context class loader specified by
* {@link BasicJeriExporter#export BasicJeriExporter.export}.
*
* <p><code>BasicInvocationDispatcher</code> implements this method to
* execute the following actions in order:
*
* <ul>
* <li>A byte specifying the marshal stream protocol version is read
* from the request input stream of the inbound request. If any
* exception is thrown when reading this byte, the inbound request is
* aborted and this method returns. If the byte is not
* <code>0x00</code>, two byte values of <code>0x00</code> (indicating
* a marshal stream protocol version mismatch) are written to the
* response output stream of the inbound request, the output stream is
* closed, and this method returns.
*
* <li>If the version byte is <code>0x00</code>, a second byte
* specifying object integrity is read from the same stream. If any
* exception is thrown when reading this byte, the inbound request is
* aborted and this method returns. Object integrity will be enforced
* if the value read is not <code>0x00</code>, but will not be enforced
* if the value is <code>0x00</code>. An {@link
* net.jini.io.context.IntegrityEnforcement} element is then added to
* the server context, reflecting whether or not object integrity is
* being enforced.
*
* <li>The {@link #createMarshalInputStream createMarshalInputStream}
* method of this invocation dispatcher is called, passing the remote
* object, the inbound request, a boolean indicating if object
* integrity is being enforced, and the server context, to create the
* marshal input stream for unmarshalling the request.
*
* <li>The {@link #unmarshalMethod unmarshalMethod} of this
* invocation dispatcher is called with the remote object, the marshal
* input stream, and the server context to obtain the remote method.
*
* <li> The {@link InboundRequest#checkConstraints checkConstraints}
* method of the inbound request is called with the constraints that
* must be enforced for that remote method, obtained by passing the
* remote method to the {@link MethodConstraints#getConstraints
* getConstraints} method of this invocation dispatcher's server
* constraints, and adding {@link Integrity#YES Integrity.YES} as a
* requirement if object integrity is being enforced. If the
* unfulfilled requirements returned by <code>checkConstraints</code>
* contains a constraint that is not an instance of {@link Integrity}
* or if integrity is not being enforced and the returned requirements
* contains the element <code>Integrity.YES</code>, an
* <code>UnsupportedConstraintException</code> is sent back to the
* caller as described further below. Otherwise, the {@link
* #checkAccess checkAccess} method of this invocation dispatcher is
* called with the remote object, the remote method, the enforced
* constraints, and the server context.
*
* <li>The method arguments are obtained by calling the {@link
* #unmarshalArguments unmarshalArguments} method of this invocation
* dispatcher with the remote object, the remote method, the marshal
* input stream, and the server context.
*
* <li>If any exception is thrown during this unmarshalling, that exception
* is sent back to the caller as described further below; however, if the
* exception is a checked exception ({@link IOException},
* {@link ClassNotFoundException}, or {@link NoSuchMethodException}), the
* exception is first wrapped in an {@link UnmarshalException} and the
* wrapped exception is sent back.
*
* <li>Otherwise, if unmarshalling is successful, the {@link #invoke
* invoke} method of this invocation dispatcher is then called with the
* remote object, the remote method, the arguments returned by
* <code>unmarshalArguments</code>, and the server context. If
* <code>invoke</code> throws an exception, that exception is sent back
* to the caller as described further below.
*
* <li>The input stream is closed whether or not an exception was
* thrown unmarshalling the arguments or invoking the method.
*
* <li>If <code>invoke</code> returns normally, a byte value of
* <code>0x01</code> is written to the response output stream of the
* inbound request. Then the {@link #createMarshalOutputStream
* createMarshalOutputStream} method of this invocation dispatcher is
* called, passing the remote object, the remote method, the inbound
* request, and the server context, to create the marshal output stream
* for marshalling the response. Then the {@link #marshalReturn
* marshalReturn} method of this invocation dispatcher is called with
* the remote object, the remote method, the value returned by
* <code>invoke</code>, the marshal output stream, and the server
* context. Then the marshal output stream is closed. Any exception
* thrown during this marshalling is ignored.
*
* <li>When an exception is sent back to the caller, a byte value of
* <code>0x02</code> is written to the response output stream of the
* inbound request. Then a marshal output stream is created by calling
* the <code>createMarshalOutputStream</code> method as described above
* (but with a <code>null</code> remote method if one was not
* successfully unmarshalled). Then the {@link #marshalThrow
* marshalThrow} method of this invocation dispatcher is called with
* the remote object, the remote method (or <code>null</code> if one
* was not successfully unmarshalled), the exception, the marshal
* output stream, and the server context. Then the marshal output
* stream is closed. Any exception thrown during this marshalling is
* ignored. If the exception being sent back is a
* <code>RemoteException</code>, it is wrapped in a {@link
* ServerException} and the wrapped exception is passed to
* <code>marshalThrow</code>. If the exception being sent back is an
* <code>Error</code>, it is wrapped in a {@link ServerError} and the
* wrapped exception is passed to <code>marshalThrow</code>. If the
* exception being sent back occurred before or during the call to
* <code>unmarshalMethod</code>, then the remote method passed to
* <code>marshalThrow</code> is <code>null</code>.
* </ul>
*
* @throws NullPointerException {@inheritDoc}
**/
public void dispatch(Remote impl,
InboundRequest request,
Collection context)
{
if (impl == null || context == null) {
throw new NullPointerException();
}
/*
* Read (and check) version number and integrity flag.
*/
InputStream rin = null;
boolean integrity;
try {
rin = request.getRequestInputStream();
switch (rin.read()) {
case VERSION:
break;
case -1:
throw new EOFException();
default:
rin.close();
OutputStream ros = request.getResponseOutputStream();
ros.write(MISMATCH);
ros.write(VERSION);
ros.close();
return;
}
switch (rin.read()) {
case 0:
integrity = false;
break;
case -1:
throw new EOFException();
default:
integrity = true;
}
} catch (Throwable t) {
if (logger.isLoggable(Levels.FAILED)) {
logThrow(impl, t);
}
request.abort();
return;
}
Method method = null;
Object returnValue= null;
Throwable t = null;
boolean fromImpl = false;
Util.populateContext(context, integrity);
ObjectInputStream in = null;
try {
/*
* Unmarshal method and check security constraints.
*/
in = createMarshalInputStream(impl, request, integrity, context);
method = unmarshalMethod(impl, in, context);
InvocationConstraints sc =
(serverConstraints == null ?
InvocationConstraints.EMPTY :
serverConstraints.getConstraints(method));
if (integrity && !sc.requirements().contains(Integrity.YES)) {
Collection requirements = new ArrayList(sc.requirements());
requirements.add(Integrity.YES);
sc = new InvocationConstraints(requirements, sc.preferences());
}
InvocationConstraints unfulfilled = request.checkConstraints(sc);
for (Iterator i = unfulfilled.requirements().iterator();
i.hasNext();)
{
InvocationConstraint c = (InvocationConstraint) i.next();
if (!(c instanceof Integrity) ||
(!integrity && c == Integrity.YES))
{
throw new UnsupportedConstraintException(
"cannot satisfy unfulfilled constraint: " + c);
}
// REMIND: support ConstraintAlternatives containing Integrity?
}
checkAccess(impl, method, sc, context);
/*
* Unmarshal arguments.
*/
Object[] args = unmarshalArguments(impl, method, in, context);
if (logger.isLoggable(Level.FINE)) {
logCall(impl, method, args);
}
/*
* Invoke method on remote object.
*/
try {
returnValue = invoke(impl, method, args, context);
if (logger.isLoggable(Level.FINE)) {
logReturn(impl, method, returnValue);
}
} catch (Throwable tt) {
t = tt;
fromImpl = true;
}
} catch (RuntimeException e) {
t = e;
} catch (Exception e) {
t = new UnmarshalException("unmarshalling method/arguments", e);
} catch (Throwable tt) {
t = tt;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignore) {
}
}
}
/*
* Marshal return value or exception.
*/
try {
request.getResponseOutputStream().write(t == null ?
RETURN : THROW);
ObjectOutputStream out =
createMarshalOutputStream(impl, method, request, context);
if (t != null) {
if (logger.isLoggable(Levels.FAILED)) {
logThrow(impl, method, t, fromImpl);
}
if (t instanceof RemoteException) {
t = new ServerException("RemoteException in server thread",
(Exception) t);
} else if (t instanceof Error) {
t = new ServerError("Error in server thread", (Error) t);
}
if (suppressStackTraces) {
Util.clearStackTraces(t);
}
marshalThrow(impl, method, t, out, context);
} else {
marshalReturn(impl, method, returnValue, out, context);
}
out.close();
} catch (Throwable tt) {
/*
* All exceptions are fatal at this point. There is no
* recovery if a problem occurs writing the result, so
* abort the call and return. But first try to close the
* response output stream, in case the IOException was
* able to be serialized for the client successfully.
*/
try {
request.getResponseOutputStream().close();
} catch (IOException ignore) {
}
request.abort();
if (logger.isLoggable(Levels.FAILED)) {
logThrow(impl, tt);
}
}
}
/**
* Returns a new marshal input stream to use to read objects from the
* request input stream obtained by invoking the {@link
* InboundRequest#getRequestInputStream getRequestInputStream} method
* on the given <code>request</code>.
*
* <p><code>BasicInvocationDispatcher</code> implements this method as
* follows:
*
* <p>First, a class loader is selected to use as the
* <code>defaultLoader</code> and the <code>verifierLoader</code> for
* the marshal input stream instance. If the class loader specified at
* construction is not <code>null</code>, the selected loader is that
* loader. Otherwise, if a security manager exists, its {@link
* SecurityManager#checkPermission checkPermission} method is invoked
* with the permission <code>{@link
* RuntimePermission}("getClassLoader")</code>; this invocation may
* throw a <code>SecurityException</code>. If the above security check
* succeeds, the selected loader is the class loader of
* <code>impl</code>'s class.
*
* <p>This method returns a new {@link MarshalInputStream} instance
* constructed with the input stream (obtained from the
* <code>request</code> as specified above) for the input stream
* <code>in</code>, the selected loader for <code>defaultLoader</code>
* and <code>verifierLoader</code>, the boolean <code>integrity</code>
* for <code>verifyCodebaseIntegrity</code>, and an unmodifiable view
* of <code>context</code> for the <code>context</code> collection.
* The {@link MarshalInputStream#useCodebaseAnnotations
* useCodebaseAnnotations} method is invoked on the created stream
* before it is returned.
*
* <p>A subclass can override this method to control how the marshal input
* stream is created or implemented.
*
* @param impl the remote object
* @param request the inbound request
* @param integrity <code>true</code> if object integrity is being
* enforced for the remote call, and <code>false</code> otherwise
* @param context the server context
* @return a new marshal input stream for unmarshalling a call request
* @throws IOException if an I/O exception occurs
* @throws NullPointerException if any argument is <code>null</code>
**/
protected ObjectInputStream
createMarshalInputStream(Object impl,
InboundRequest request,
boolean integrity,
Collection context)
throws IOException
{
ClassLoader streamLoader;
if (loader != null) {
streamLoader = getClassLoader();
} else {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(getClassLoaderPermission);
}
streamLoader = impl.getClass().getClassLoader();
}
Collection unmodContext = Collections.unmodifiableCollection(context);
MarshalInputStream in =
new MarshalInputStream(request.getRequestInputStream(),
streamLoader, integrity,
streamLoader, unmodContext);
in.useCodebaseAnnotations();
return in;
}
/**
* Returns a new marshal output stream to use to write objects to the
* response output stream obtained by invoking the {@link
* InboundRequest#getResponseOutputStream getResponseOutputStream}
* method on the given <code>request</code>.
*
* <p>This method will be called with a <code>null</code>
* <code>method</code> argument if an <code>IOException</code> occurred
* when reading method information from the incoming call stream.
*
* <p><code>BasicInvocationDispatcher</code> implements this method to
* return a new {@link MarshalOutputStream} instance constructed with
* the output stream obtained from the <code>request</code> as
* specified above and an unmodifiable view of the given
* <code>context</code> collection.
*
* <p>A subclass can override this method to control how the marshal output
* stream is created or implemented.
*
* @param impl the remote object
* @param method the possibly-<code>null</code> <code>Method</code>
* instance corresponding to the interface method invoked on
* the remote object
* @param request the inbound request
* @param context the server context
* @return a new marshal output stream for marshalling a call response
* @throws IOException if an I/O exception occurs
* @throws NullPointerException if <code>impl</code>,
* <code>request</code>, or <code>context</code> is
* <code>null</code>
**/
protected ObjectOutputStream
createMarshalOutputStream(Object impl,
Method method,
InboundRequest request,
Collection context)
throws IOException
{
if (impl == null) {
throw new NullPointerException();
}
OutputStream out = request.getResponseOutputStream();
Collection unmodContext = Collections.unmodifiableCollection(context);
return new MarshalOutputStream(out, unmodContext);
}
/**
* Checks that the client has permission to invoke the specified method on
* the specified remote object.
*
* <p><code>BasicInvocationDispatcher</code> implements this method as
* follows:
*
* <p>If a permission class was specified when this invocation
* dispatcher was constructed, {@link #checkClientPermission
* checkClientPermission} is called with a permission constructed from
* the permission class. If the permission class has a constructor with
* a <code>Method</code> parameter, the permission is constructed by
* passing the specified method to that constructor. Otherwise the
* permission is constructed by passing the fully qualified name of the
* method to the constructor with a <code>String</code> parameter,
* where the argument is formed by concatenating the name of the
* declaring class of the specified method and the name of the method,
* separated by ".".
*
* <p>A subclass can override this method to implement other preinvocation
* access control mechanisms.
*
* @param impl the remote object
* @param method the remote method
* @param constraints the enforced constraints for the specified
* method, or <code>null</code>
* @param context the server context
* @throws SecurityException if the current client subject does not
* have permission to invoke the method
* @throws IllegalStateException if the current thread is not executing an
* incoming remote call for a remote object
* @throws NullPointerException if <code>impl</code>,
* <code>method</code>, or <code>context</code> is
* <code>null</code>
**/
protected void checkAccess(Remote impl,
Method method,
InvocationConstraints constraints,
Collection context)
{
if (impl == null || method == null || context == null) {
throw new NullPointerException();
}
if (permConstructor == null) {
return;
}
Permission perm;
synchronized (permissions) {
perm = (Permission) permissions.get(method);
}
if (perm == null) {
try {
perm = (Permission) permConstructor.newInstance(new Object[]{
permUsesMethod ?
(Object) method :
method.getDeclaringClass().getName() + "." +
method.getName()});
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof Error) {
throw (Error) t;
}
throw (RuntimeException) t;
} catch (Exception e) {
throw new RuntimeException("unexpected exception", e);
}
synchronized (permissions) {
permissions.put(method, perm);
}
}
checkClientPermission(perm);
}
/**
* Checks that the client subject for the current remote call has the
* specified permission. The client subject is obtained by calling {@link
* ServerContext#getServerContextElement
* ServerContext.getServerContextElement}, passing the class {@link
* ClientSubject}, and then calling the {@link
* ClientSubject#getClientSubject getClientSubject} method of the returned
* element (if any). If a security manager is installed, a {@link
* ProtectionDomain} is constructed with an empty {@link CodeSource}
* (<code>null</code> location and certificates), <code>null</code>
* permissions, <code>null</code> class loader, and the principals from
* the client subject (if any), and the <code>implies</code> method of
* that protection domain is invoked with the specified permission. If
* <code>true</code> is returned, this method returns normally, otherwise
* a <code>SecurityException</code> is thrown. If no security
* manager is installed, this method returns normally.
*
* <p>Note that the permission grant required to satisfy this check must
* be to the client's principals alone (or a subset thereof); it cannot be
* qualified by what code is being executed. At the point in a remote call
* where this method is intended to be used, the useful "call stack" only
* exists at the other end of the remote call (on the client side), and so
* cannot meaningfully enter into the access control decision.
*
* @param permission the requested permission
* @throws SecurityException if the current client subject has not
* been granted the specified permission
* @throws IllegalStateException if the current thread is not executing
* an incoming remote method for a remote object
* @throws NullPointerException if <code>permission</code> is
* <code>null</code>
**/
public static void checkClientPermission(final Permission permission) {
if (permission == null) {
throw new NullPointerException();
}
Subject client =
(Subject) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
return Util.getClientSubject();
} catch (ServerNotActiveException e) {
throw new IllegalStateException("server not active");
}
}
});
if (System.getSecurityManager() == null) {
return;
}
ProtectionDomain pd;
if (client == null) {
pd = emptyPD;
} else {
synchronized (domains) {
WeakKey k;
while ((k = (WeakKey) queue.poll()) != null) {
domains.remove(k);
}
pd = (ProtectionDomain) domains.get(new WeakKey(client));
if (pd == null) {
Set set = client.getPrincipals();
Principal[] prins =
(Principal[]) set.toArray(new Principal[set.size()]);
pd = new ProtectionDomain(emptyCS, null, null, prins);
domains.put(new WeakKey(client, queue), pd);
}
}
}
boolean ok = pd.implies(permission);
// XXX what about logging
if (!ok) {
throw new AccessControlException("access denied " + permission);
}
}
/**
* Unmarshals a method representation from the marshal input stream,
* <code>in</code>, and returns the <code>Method</code> object
* corresponding to that representation. For each remote call, the
* <code>dispatch</code> method calls this method to unmarshal the
* method representation.
*
* <p><code>BasicInvocationDispatcher</code> implements this method to
* call the <code>readLong</code> method on the marshal input stream to
* read the method's representation encoded as a JRMP method hash
* (defined in section 8.3 of the Java(TM) Remote Method Invocation
* (Java RMI) specification) and return its
* corresponding <code>Method</code> object chosen from the collection
* of methods passed to the constructor of this invocation dispatcher.
* If more than one method has the same hash, it is arbitrary as to
* which one is returned.
*
* <p>A subclass can override this method to control how the remote
* method is unmarshalled.
*
* @param impl the remote object
* @param in the marshal input stream for the remote call
* @param context the server context passed to the {@link #dispatch
* dispatch} method for the remote call being processed
* @return a <code>Method</code> object corresponding to the method
* representation
* @throws IOException if an I/O exception occurs
* @throws NoSuchMethodException if the method representation does not
* correspond to a valid method
* @throws ClassNotFoundException if a class could not be found during
* unmarshalling
* @throws NullPointerException if any argument is <code>null</code>
**/
protected Method unmarshalMethod(Remote impl,
ObjectInputStream in,
Collection context)
throws IOException, NoSuchMethodException, ClassNotFoundException
{
if (impl == null || context == null) {
throw new NullPointerException();
}
long hash = in.readLong();
Method method = (Method) methods.get(new Long(hash));
if (method == null) {
throw new NoSuchMethodException(
"unrecognized method hash: method not supported by remote object");
}
return method;
}
/**
* Unmarshals the arguments for the specified remote <code>method</code>
* from the specified marshal input stream, <code>in</code>, and returns an
* <code>Object</code> array containing the arguments read. For each
* remote call, the <code>dispatch</code> method calls this method to
* unmarshal arguments.
*
* <p><code>BasicInvocationDispatcher</code> implements this method to
* unmarshal each argument as follows:
*
* <p>If the corresponding declared parameter type is primitive, then
* the primitive value is read from the stream using the
* corresponding <code>read</code> method for that primitive type (for
* example, if the type is <code>int.class</code>, then the primitive
* <code>int</code> value is read to the stream using the
* <code>readInt</code> method) and the value is wrapped in the
* corresponding primitive wrapper class for that type (e.g.,
* <code>Integer</code> for <code>int</code>, etc.). Otherwise, the
* argument is read from the stream using the <code>readObject</code>
* method and returned as is.
*
* <p>A subclass can override this method to unmarshal the arguments in an
* alternative context, perform post-processing on the arguments,
* unmarshal additional implicit data, or otherwise control how the
* arguments are unmarshalled. In general, the context used should mirror
* the context in which the arguments are manipulated in the
* implementation of the remote object.
*
* @param impl the remote object
* @param method the <code>Method</code> instance corresponding
* to the interface method invoked on the remote object
* @param in the incoming request stream for the remote call
* @param context the server context passed to the {@link #dispatch
* dispatch} method for the remote call being processed
* @return an <code>Object</code> array containing
* the unmarshalled arguments. If an argument's corresponding
* declared parameter type is primitive, then its value is
* represented with an instance of the corresponding primitive
* wrapper class; otherwise, the value for that argument is an
* object of a class assignable to the declared parameter type.
* @throws IOException if an I/O exception occurs
* @throws ClassNotFoundException if a class could not be found during
* unmarshalling
* @throws NullPointerException if any argument is <code>null</code>
**/
protected Object[] unmarshalArguments(Remote impl,
Method method,
ObjectInputStream in,
Collection context)
throws IOException, ClassNotFoundException
{
if (impl == null || in == null || context == null) {
throw new NullPointerException();
}
Class[] types = method.getParameterTypes();
Object[] args = new Object[types.length];
for (int i = 0; i < types.length; i++) {
args[i] = Util.unmarshalValue(types[i], in);
}
return args;
}
/**
* Invokes the specified <code>method</code> on the specified remote
* object <code>impl</code>, with the specified arguments.
* If the invocation completes normally, the return value will be
* returned by this method. If the invocation throws an exception,
* this method will throw the same exception.
*
* <p><code>BasicInvocationDispatcher</code> implements this method as
* follows:
*
* <p>If the specified method is not set accessible or is not a
* <code>public</code> method of a <code>public</code> class an
* <code>IllegalArgumentException</code> is thrown.
*
* <p>If the specified method is {@link ProxyTrust#getProxyVerifier
* ProxyTrust.getProxyVerifier} and the remote object is an instance of
* {@link ServerProxyTrust}, the {@link ServerProxyTrust#getProxyVerifier
* getProxyVerifier} method of the remote object is called and the result
* is returned.
*
* <p>Otherwise, the specified method's <code>invoke</code> method is
* called with the specified remote object and the specified arguments,
* and the result is returned. If <code>invoke</code> throws an {@link
* InvocationTargetException}, that exception is caught and the target
* exception inside it is thrown to the caller. Any other exception
* thrown during any of this computation is thrown to the caller.
*
* <p>A subclass can override this method to invoke the method in an
* alternative context, perform pre- or post-processing, or otherwise
* control how the method is invoked.
*
* @param impl the remote object
* @param method the <code>Method</code> instance corresponding
* to the interface method invoked on the remote object
* @param args the method arguments
* @param context the server context passed to the {@link #dispatch
* dispatch} method for the remote call being processed
* @return the result of the method invocation on <code>impl</code>
* @throws NullPointerException if any argument is <code>null</code>
* @throws Throwable the exception thrown from the method invocation
* on <code>impl</code>
**/
protected Object invoke(Remote impl,
Method method,
Object[] args,
Collection context)
throws Throwable
{
if (impl == null || args == null || context == null) {
throw new NullPointerException();
}
if (!method.isAccessible() &&
!(Modifier.isPublic(method.getDeclaringClass().getModifiers()) &&
Modifier.isPublic(method.getModifiers())))
{
throw new IllegalArgumentException(
"method not public or set accessible");
}
Class decl = method.getDeclaringClass();
if (decl == ProxyTrust.class &&
method.getName().equals("getProxyVerifier") &&
impl instanceof ServerProxyTrust)
{
if (args.length != 0) {
throw new IllegalArgumentException("incorrect arguments");
}
return ((ServerProxyTrust) impl).getProxyVerifier();
}
try {
return method.invoke(impl, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
/**
* Marshals the specified return value for the specified remote method
* to the marshal output stream, <code>out</code>. After invoking
* the method on the remote object <code>impl</code>, the
* <code>dispatch</code> method calls this method to marshal the value
* returned from the invocation on that remote object.
*
* <p><code>BasicInvocationDispatcher</code> implements this method as
* follows:
*
* <p>If the declared return type of the method is void, then no return
* value is written to the stream. If the return type is a primitive
* type, then the primitive value is written to the stream (for
* example, if the type is <code>int.class</code>, then the primitive
* <code>int</code> value is written to the stream using the
* <code>writeInt</code> method). Otherwise, the return value is
* written to the stream using the <code>writeObject</code> method.
*
* <p>A subclass can override this method to marshal the return value in an
* alternative context, perform pre- or post-processing on the return
* value, marshal additional implicit data, or otherwise control how the
* return value is marshalled. In general, the context used should mirror
* the context in which the result is computed in the implementation of
* the remote object.
*
* @param impl the remote object
* @param method the <code>Method</code> instance corresponding
* to the interface method invoked on the remote object
* @param returnValue the return value to marshal to the stream
* @param out the marshal output stream
* @param context the server context passed to the {@link #dispatch
* dispatch} method for the remote call being processed
* @throws IOException if an I/O exception occurs
* @throws NullPointerException if <code>impl</code>,
* <code>method</code>, <code>out</code>, or
* <code>context</code> is <code>null</code>
**/
protected void marshalReturn(Remote impl,
Method method,
Object returnValue,
ObjectOutputStream out,
Collection context)
throws IOException
{
if (impl == null || out == null || context == null) {
throw new NullPointerException();
}
Class returnType = method.getReturnType();
if (returnType != void.class) {
Util.marshalValue(returnType, returnValue, out);
}
}
/**
* Marshals the <code>throwable</code> for the specified remote method
* to the marshal output stream, <code>out</code>. For each method
* invocation on <code>impl</code> that throws an exception, this
* method is called to marshal the throwable. This method is also
* called if an exception occurs reading the method information from
* the incoming call stream, as a result of calling {@link
* #unmarshalMethod unmarshalMethod}; in this case, the
* <code>Method</code> instance will be <code>null</code>.
*
* <p><code>BasicInvocationDispatcher</code> implements this method to
* marshal the throwable to the stream using the
* <code>writeObject</code> method.
*
* <p>A subclass can override this method to marshal the throwable in an
* alternative context, perform pre- or post-processing on the throwable,
* marshal additional implicit data, or otherwise control how the throwable
* is marshalled. In general, the context used should mirror the context
* in which the exception is generated in the implementation of the
* remote object.
*
* @param impl the remote object
* @param method the possibly-<code>null</code> <code>Method</code>
* instance corresponding to the interface method invoked on
* the remote object
* @param throwable a throwable to marshal to the stream
* @param out the marshal output stream
* @param context the server context
* @throws IOException if an I/O exception occurs
* @throws NullPointerException if <code>impl</code>,
* <code>throwable</code>, <code>out</code>, or
* <code>context</code> is <code>null</code>
**/
protected void marshalThrow(Remote impl,
Method method,
Throwable throwable,
ObjectOutputStream out,
Collection context)
throws IOException
{
if (impl == null || throwable == null || context == null) {
throw new NullPointerException();
}
out.writeObject(throwable);
}
/**
* Log the start of a remote call.
*/
private void logCall(Remote impl, Method method, Object[] args) {
String msg = "inbound call {0}.{1} to {2} from {3}\nclient {4}";
if (logger.isLoggable(Level.FINEST)) {
msg = "inbound call {0}.{1} to {2} from {3}\nargs {5}\nclient {4}";
}
Subject client = getClientSubject();
Set prins = (client != null) ? client.getPrincipals() : null;
String host = null;
try {
host = Util.getClientHostString();
} catch (ServerNotActiveException e) {
}
logger.log(Level.FINE, msg,
new Object[]{method.getDeclaringClass().getName(),
method.getName(), impl, host,
prins, Arrays.asList(args)});
}
/**
* Log the return of an inbound call.
*/
private void logReturn(Remote impl, Method method, Object res) {
String msg = "inbound call {0}.{1} to {2} returns";
if (logger.isLoggable(Level.FINEST) &&
method.getReturnType() != void.class)
{
msg = "inbound call {0}.{1} to {2} returns {3}";
}
logger.logp(Level.FINE, this.getClass().getName(), "dispatch", msg,
new Object[]{method.getDeclaringClass().getName(),
method.getName(), impl, res});
}
/**
* Log the remote throw of an inbound call.
*/
private void logThrow(Remote impl,
Method method,
Throwable t,
boolean fromImpl)
{
LogRecord lr = new LogRecord(
Levels.FAILED,
fromImpl ?
"inbound call {0}.{1} to {2} remotely throws" :
(logger.isLoggable(Level.FINEST) ?
"inbound call {0}.{1} to {2} dispatch remotely throws\nclient {3}" :
"inbound call {0}.{1} to {2} dispatch remotely throws"));
lr.setLoggerName(logger.getName());
lr.setSourceClassName(this.getClass().getName());
lr.setSourceMethodName("dispatch");
lr.setParameters(new Object[]{(method == null ?
"<unknown>" :
method.getDeclaringClass().getName()),
(method == null ?
"<unknown>" : method.getName()),
impl, getClientSubject()});
lr.setThrown(t);
logger.log(lr);
}
/**
* Log the local throw of an inbound call.
*/
private void logThrow(Remote impl, Throwable t) {
LogRecord lr = new LogRecord(Levels.FAILED,
logger.isLoggable(Level.FINEST) ?
"{0} locally throws\nclient {1}" :
"{0} locally throws");
lr.setLoggerName(logger.getName());
lr.setSourceClassName(this.getClass().getName());
lr.setSourceMethodName("dispatch");
lr.setParameters(new Object[]{impl, getClientSubject()});
lr.setThrown(t);
logger.log(lr);
}
/**
* Return the current client subject or <code>null</code> if not
* currently executing a remote call.
*/
private static Subject getClientSubject() {
return (Subject) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
return Util.getClientSubject();
} catch (ServerNotActiveException e) {
return null;
}
}
});
}
}
| apache-2.0 |
jinhyukchang/gobblin | gobblin-cluster/src/main/java/org/apache/gobblin/cluster/StreamingJobConfigurationManager.java | 6715 | /*
* 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.gobblin.cluster;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.Service;
import com.typesafe.config.Config;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.gobblin.annotation.Alpha;
import org.apache.gobblin.runtime.api.JobSpec;
import org.apache.gobblin.runtime.api.MutableJobCatalog;
import org.apache.gobblin.runtime.api.Spec;
import org.apache.gobblin.runtime.api.SpecExecutor;
import org.apache.gobblin.util.ClassAliasResolver;
import org.apache.gobblin.util.ConfigUtils;
import org.apache.gobblin.util.ExecutorsUtils;
import org.apache.gobblin.util.reflection.GobblinConstructorUtils;
import org.apache.gobblin.runtime.api.SpecConsumer;
/**
* A {@link JobConfigurationManager} that fetches job specs from a {@link SpecConsumer} in a loop
* without
*/
@Alpha
public class StreamingJobConfigurationManager extends JobConfigurationManager {
private static final Logger LOGGER = LoggerFactory.getLogger(StreamingJobConfigurationManager.class);
private final ExecutorService fetchJobSpecExecutor;
private final SpecConsumer specConsumer;
private final long stopTimeoutSeconds;
public StreamingJobConfigurationManager(EventBus eventBus, Config config, MutableJobCatalog jobCatalog) {
super(eventBus, config);
this.stopTimeoutSeconds = ConfigUtils.getLong(config, GobblinClusterConfigurationKeys.STOP_TIMEOUT_SECONDS,
GobblinClusterConfigurationKeys.DEFAULT_STOP_TIMEOUT_SECONDS);
this.fetchJobSpecExecutor = Executors.newSingleThreadExecutor(
ExecutorsUtils.newThreadFactory(Optional.of(LOGGER), Optional.of("FetchJobSpecExecutor")));
String specExecutorInstanceConsumerClassName =
ConfigUtils.getString(config, GobblinClusterConfigurationKeys.SPEC_CONSUMER_CLASS_KEY,
GobblinClusterConfigurationKeys.DEFAULT_STREAMING_SPEC_CONSUMER_CLASS);
LOGGER.info("Using SpecConsumer ClassNameclass name/alias " +
specExecutorInstanceConsumerClassName);
try {
ClassAliasResolver<SpecConsumer> aliasResolver =
new ClassAliasResolver<>(SpecConsumer.class);
this.specConsumer = (SpecConsumer) GobblinConstructorUtils.invokeFirstConstructor(
Class.forName(aliasResolver.resolve(specExecutorInstanceConsumerClassName)),
ImmutableList.<Object>of(config, jobCatalog),
ImmutableList.<Object>of(config));
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
| ClassNotFoundException e) {
throw new RuntimeException("Could not construct SpecConsumer " +
specExecutorInstanceConsumerClassName, e);
}
}
@Override
protected void startUp() throws Exception {
LOGGER.info("Starting the " + StreamingJobConfigurationManager.class.getSimpleName());
// submit command to fetch job specs
this.fetchJobSpecExecutor.execute(new Runnable() {
@Override
public void run() {
try {
while(true) {
fetchJobSpecs();
}
} catch (InterruptedException e) {
LOGGER.info("Fetch thread interrupted... will exit");
} catch (ExecutionException e) {
LOGGER.error("Failed to fetch job specs", e);
throw new RuntimeException("Failed to fetch specs", e);
}
}
});
// if the instance consumer is a service then need to start it to consume job specs
// IMPORTANT: StreamingKafkaSpecConsumer needs to be launched after a fetching thread is created.
// This is because StreamingKafkaSpecConsumer will invoke addListener(new JobSpecListener()) during startup,
// which will push job specs into a blocking queue _jobSpecQueue. A fetching thread will help to consume the
// blocking queue to prevent a hanging issue.
if (this.specConsumer instanceof Service) {
((Service) this.specConsumer).startAsync().awaitRunning();
}
}
private void fetchJobSpecs() throws ExecutionException, InterruptedException {
List<Pair<SpecExecutor.Verb, Spec>> changesSpecs =
(List<Pair<SpecExecutor.Verb, Spec>>) this.specConsumer.changedSpecs().get();
// propagate thread interruption so that caller will exit from loop
if (Thread.interrupted()) {
throw new InterruptedException();
}
for (Pair<SpecExecutor.Verb, Spec> entry : changesSpecs) {
SpecExecutor.Verb verb = entry.getKey();
if (verb.equals(SpecExecutor.Verb.ADD)) {
// Handle addition
JobSpec jobSpec = (JobSpec) entry.getValue();
postNewJobConfigArrival(jobSpec.getUri().toString(), jobSpec.getConfigAsProperties());
} else if (verb.equals(SpecExecutor.Verb.UPDATE)) {
// Handle update
JobSpec jobSpec = (JobSpec) entry.getValue();
postUpdateJobConfigArrival(jobSpec.getUri().toString(), jobSpec.getConfigAsProperties());
} else if (verb.equals(SpecExecutor.Verb.DELETE)) {
// Handle delete
Spec anonymousSpec = (Spec) entry.getValue();
postDeleteJobConfigArrival(anonymousSpec.getUri().toString(), new Properties());
}
}
}
@Override
protected void shutDown() throws Exception {
if (this.specConsumer instanceof Service) {
((Service) this.specConsumer).stopAsync().awaitTerminated(this.stopTimeoutSeconds,
TimeUnit.SECONDS);
}
ExecutorsUtils.shutdownExecutorService(this.fetchJobSpecExecutor, Optional.of(LOGGER));
}
} | apache-2.0 |
Aulust/async-http-client | client/src/test/java/org/asynchttpclient/ErrorResponseTest.java | 2612 | /*
* Copyright 2010 Ning, Inc.
*
* Ning 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.asynchttpclient;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.asynchttpclient.Dsl.*;
import static org.testng.Assert.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.testng.annotations.Test;
/**
* Tests to reproduce issues with handling of error responses
*
* @author Tatu Saloranta
*/
public class ErrorResponseTest extends AbstractBasicTest {
final static String BAD_REQUEST_STR = "Very Bad Request! No cookies.";
private static class ErrorHandler extends AbstractHandler {
public void handle(String s, Request r, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
try {
Thread.sleep(210L);
} catch (InterruptedException e) {
}
response.setContentType("text/plain");
response.setStatus(400);
OutputStream out = response.getOutputStream();
out.write(BAD_REQUEST_STR.getBytes(UTF_8));
out.flush();
}
}
@Override
public AbstractHandler configureHandler() throws Exception {
return new ErrorHandler();
}
@Test(groups = "standalone")
public void testQueryParameters() throws Exception {
try (AsyncHttpClient client = asyncHttpClient()) {
Future<Response> f = client.prepareGet("http://localhost:" + port1 + "/foo").addHeader("Accepts", "*/*").execute();
Response resp = f.get(3, TimeUnit.SECONDS);
assertNotNull(resp);
assertEquals(resp.getStatusCode(), 400);
assertEquals(resp.getResponseBody(), BAD_REQUEST_STR);
}
}
}
| apache-2.0 |
0359xiaodong/picasso | picasso/src/test/java/com/squareup/picasso/TestUtils.java | 7615 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso;
import android.app.Notification;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.NetworkInfo;
import android.net.Uri;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RemoteViews;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static android.content.ContentResolver.SCHEME_ANDROID_RESOURCE;
import static android.provider.ContactsContract.Contacts.CONTENT_URI;
import static android.provider.ContactsContract.Contacts.Photo.CONTENT_DIRECTORY;
import static com.squareup.picasso.Utils.createKey;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class TestUtils {
static final Answer<Object> TRANSFORM_REQUEST_ANSWER = new Answer<Object>() {
@Override public Object answer(InvocationOnMock invocation) throws Throwable {
return invocation.getArguments()[0];
}
};
static final Uri URI_1 = Uri.parse("http://example.com/1.png");
static final Uri URI_2 = Uri.parse("http://example.com/2.png");
static final String URI_KEY_1 = createKey(new Request.Builder(URI_1).build());
static final String URI_KEY_2 = createKey(new Request.Builder(URI_2).build());
static final Bitmap VIDEO_THUMBNAIL_1 = Bitmap.createBitmap(10, 10, null);
static final Bitmap IMAGE_THUMBNAIL_1 = Bitmap.createBitmap(20, 20, null);
static final Bitmap BITMAP_1 = Bitmap.createBitmap(10, 10, null);
static final Bitmap BITMAP_2 = Bitmap.createBitmap(15, 15, null);
static final Bitmap BITMAP_3 = Bitmap.createBitmap(20, 20, null);
static final File FILE_1 = new File("C:\\windows\\system32\\logo.exe");
static final String FILE_KEY_1 = createKey(new Request.Builder(Uri.fromFile(FILE_1)).build());
static final Uri FILE_1_URL = Uri.parse("file:///" + FILE_1.getPath());
static final Uri FILE_1_URL_NO_AUTHORITY = Uri.parse("file:/" + FILE_1.getParent());
static final Uri MEDIA_STORE_CONTENT_1_URL = Uri.parse("content://media/external/images/media/1");
static final String MEDIA_STORE_CONTENT_KEY_1 =
createKey(new Request.Builder(MEDIA_STORE_CONTENT_1_URL).build());
static final Uri CONTENT_1_URL = Uri.parse("content://zip/zap/zoop.jpg");
static final String CONTENT_KEY_1 = createKey(new Request.Builder(CONTENT_1_URL).build());
static final Uri CONTACT_URI_1 = CONTENT_URI.buildUpon().path("1234").build();
static final String CONTACT_KEY_1 = createKey(new Request.Builder(CONTACT_URI_1).build());
static final Uri CONTACT_PHOTO_URI_1 =
CONTENT_URI.buildUpon().path("1234").path(CONTENT_DIRECTORY).build();
static final String CONTACT_PHOTO_KEY_1 =
createKey(new Request.Builder(CONTACT_PHOTO_URI_1).build());
static final int RESOURCE_ID_1 = 1;
static final String RESOURCE_ID_KEY_1 = createKey(new Request.Builder(RESOURCE_ID_1).build());
static final Uri ASSET_URI_1 = Uri.parse("file:///android_asset/foo/bar.png");
static final String ASSET_KEY_1 = createKey(new Request.Builder(ASSET_URI_1).build());
static final String RESOURCE_PACKAGE = "com.squareup.picasso";
static final String RESOURCE_TYPE = "drawable";
static final String RESOURCE_NAME = "foo";
static final Uri RESOURCE_ID_URI = new Uri.Builder().scheme(SCHEME_ANDROID_RESOURCE)
.authority(RESOURCE_PACKAGE)
.appendPath(Integer.toString(RESOURCE_ID_1))
.build();
static final String RESOURCE_ID_URI_KEY = createKey(new Request.Builder(RESOURCE_ID_URI).build());
static final Uri RESOURCE_TYPE_URI = new Uri.Builder().scheme(SCHEME_ANDROID_RESOURCE)
.authority(RESOURCE_PACKAGE)
.appendPath(RESOURCE_TYPE)
.appendPath(RESOURCE_NAME)
.build();
static final String RESOURCE_TYPE_URI_KEY =
createKey(new Request.Builder(RESOURCE_TYPE_URI).build());
static Context mockPackageResourceContext() {
Context context = mock(Context.class);
PackageManager pm = mock(PackageManager.class);
Resources res = mock(Resources.class);
doReturn(pm).when(context).getPackageManager();
try {
doReturn(res).when(pm).getResourcesForApplication(RESOURCE_PACKAGE);
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
doReturn(RESOURCE_ID_1).when(res).getIdentifier(RESOURCE_NAME, RESOURCE_TYPE, RESOURCE_PACKAGE);
return context;
}
static Action mockAction(String key, Uri uri) {
return mockAction(key, uri, null, 0);
}
static Action mockAction(String key, Uri uri, Object target) {
return mockAction(key, uri, target, 0);
}
static Action mockAction(String key, Uri uri, Object target, int resourceId) {
Request request = new Request.Builder(uri, resourceId).build();
return mockAction(key, request, target);
}
static Action mockAction(String key, Request request) {
return mockAction(key, request, null);
}
static Action mockAction(String key, Request request, Object target) {
Action action = mock(Action.class);
when(action.getKey()).thenReturn(key);
when(action.getData()).thenReturn(request);
when(action.getTarget()).thenReturn(target);
when(action.getPicasso()).thenReturn(mock(Picasso.class));
return action;
}
static Action mockCanceledAction() {
Action action = mock(Action.class);
action.cancelled = true;
when(action.isCancelled()).thenReturn(true);
return action;
}
static ImageView mockImageViewTarget() {
return mock(ImageView.class);
}
static RemoteViews mockRemoteViews() {
return mock(RemoteViews.class);
}
static Notification mockNotification() {
return mock(Notification.class);
}
static ImageView mockFitImageViewTarget(boolean alive) {
ViewTreeObserver observer = mock(ViewTreeObserver.class);
when(observer.isAlive()).thenReturn(alive);
ImageView mock = mock(ImageView.class);
when(mock.getViewTreeObserver()).thenReturn(observer);
return mock;
}
static Target mockTarget() {
return mock(Target.class);
}
static Callback mockCallback() {
return mock(Callback.class);
}
static DeferredRequestCreator mockDeferredRequestCreator() {
return mock(DeferredRequestCreator.class);
}
static NetworkInfo mockNetworkInfo() {
return mock(NetworkInfo.class);
}
static InputStream mockInputStream() throws IOException {
return mock(InputStream.class);
}
static BitmapHunter mockHunter(String key, Bitmap result, boolean skipCache) {
Request data = new Request.Builder(URI_1).build();
BitmapHunter hunter = mock(BitmapHunter.class);
when(hunter.getKey()).thenReturn(key);
when(hunter.getResult()).thenReturn(result);
when(hunter.getData()).thenReturn(data);
when(hunter.shouldSkipMemoryCache()).thenReturn(skipCache);
return hunter;
}
private TestUtils() {
}
}
| apache-2.0 |
msebire/intellij-community | plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/ParenthesesUtils.java | 15723 | /*
* Copyright 2003-2018 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ig.psiutils;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiPrecedenceUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ParenthesesUtils {
public static final int METHOD_CALL_PRECEDENCE = PsiPrecedenceUtil.METHOD_CALL_PRECEDENCE;
public static final int POSTFIX_PRECEDENCE = PsiPrecedenceUtil.POSTFIX_PRECEDENCE;
public static final int PREFIX_PRECEDENCE = PsiPrecedenceUtil.PREFIX_PRECEDENCE;
public static final int TYPE_CAST_PRECEDENCE = PsiPrecedenceUtil.TYPE_CAST_PRECEDENCE;
public static final int MULTIPLICATIVE_PRECEDENCE = PsiPrecedenceUtil.MULTIPLICATIVE_PRECEDENCE;
public static final int ADDITIVE_PRECEDENCE = PsiPrecedenceUtil.ADDITIVE_PRECEDENCE;
public static final int SHIFT_PRECEDENCE = PsiPrecedenceUtil.SHIFT_PRECEDENCE;
public static final int EQUALITY_PRECEDENCE = PsiPrecedenceUtil.EQUALITY_PRECEDENCE;
public static final int BINARY_AND_PRECEDENCE = PsiPrecedenceUtil.BINARY_AND_PRECEDENCE;
public static final int BINARY_OR_PRECEDENCE = PsiPrecedenceUtil.BINARY_OR_PRECEDENCE;
public static final int AND_PRECEDENCE = PsiPrecedenceUtil.AND_PRECEDENCE;
public static final int OR_PRECEDENCE = PsiPrecedenceUtil.OR_PRECEDENCE;
public static final int CONDITIONAL_PRECEDENCE = PsiPrecedenceUtil.CONDITIONAL_PRECEDENCE;
public static final int ASSIGNMENT_PRECEDENCE = PsiPrecedenceUtil.ASSIGNMENT_PRECEDENCE;
public static final int NUM_PRECEDENCES = PsiPrecedenceUtil.NUM_PRECEDENCES;
private ParenthesesUtils() {}
public static boolean isCommutativeOperator(@NotNull IElementType token) {
return PsiPrecedenceUtil.isCommutativeOperator(token);
}
public static boolean isCommutativeOperation(PsiPolyadicExpression expression) {
return PsiPrecedenceUtil.isCommutativeOperation(expression);
}
public static boolean isAssociativeOperation(PsiPolyadicExpression expression) {
return PsiPrecedenceUtil.isAssociativeOperation(expression);
}
public static int getPrecedence(PsiExpression expression) {
return PsiPrecedenceUtil.getPrecedence(expression);
}
public static int getPrecedenceForOperator(@NotNull IElementType operator) {
return PsiPrecedenceUtil.getPrecedenceForOperator(operator);
}
public static boolean areParenthesesNeeded(PsiParenthesizedExpression expression, boolean ignoreClarifyingParentheses) {
return PsiPrecedenceUtil.areParenthesesNeeded(expression, ignoreClarifyingParentheses);
}
public static boolean areParenthesesNeeded(PsiExpression expression,
PsiExpression parentExpression,
boolean ignoreClarifyingParentheses) {
return PsiPrecedenceUtil.areParenthesesNeeded(expression, parentExpression, ignoreClarifyingParentheses);
}
public static boolean areParenthesesNeeded(PsiJavaToken compoundAssignmentToken, PsiExpression rhs) {
return PsiPrecedenceUtil.areParenthesesNeeded(compoundAssignmentToken, rhs);
}
public static String getText(@NotNull PsiExpression expression, int precedence) {
if (getPrecedence(expression) >= precedence) {
return '(' + expression.getText() + ')';
}
return expression.getText();
}
@Nullable public static PsiElement getParentSkipParentheses(PsiElement element) {
PsiElement parent = element.getParent();
while (parent instanceof PsiParenthesizedExpression || parent instanceof PsiTypeCastExpression) {
parent = parent.getParent();
}
return parent;
}
@Contract("null -> null")
@Nullable
public static PsiExpression stripParentheses(@Nullable PsiExpression expression) {
while (expression instanceof PsiParenthesizedExpression) {
final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression)expression;
expression = parenthesizedExpression.getExpression();
}
return expression;
}
public static void removeParentheses(@NotNull PsiExpression expression, boolean ignoreClarifyingParentheses) {
if (expression instanceof PsiMethodCallExpression) {
final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)expression;
removeParensFromMethodCallExpression(methodCall, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiReferenceExpression) {
final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)expression;
removeParensFromReferenceExpression(referenceExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiNewExpression) {
final PsiNewExpression newExpression = (PsiNewExpression)expression;
removeParensFromNewExpression(newExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiAssignmentExpression) {
final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)expression;
removeParensFromAssignmentExpression(assignmentExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiArrayInitializerExpression) {
final PsiArrayInitializerExpression arrayInitializerExpression = (PsiArrayInitializerExpression)expression;
removeParensFromArrayInitializerExpression(arrayInitializerExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiTypeCastExpression) {
final PsiTypeCastExpression typeCastExpression = (PsiTypeCastExpression)expression;
removeParensFromTypeCastExpression(typeCastExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiArrayAccessExpression) {
final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression)expression;
removeParensFromArrayAccessExpression(arrayAccessExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiPrefixExpression) {
final PsiPrefixExpression prefixExpression = (PsiPrefixExpression)expression;
removeParensFromPrefixExpression(prefixExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiPostfixExpression) {
final PsiPostfixExpression postfixExpression = (PsiPostfixExpression)expression;
removeParensFromPostfixExpression(postfixExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
removeParensFromPolyadicExpression(polyadicExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiInstanceOfExpression) {
final PsiInstanceOfExpression instanceofExpression = (PsiInstanceOfExpression)expression;
removeParensFromInstanceOfExpression(instanceofExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiConditionalExpression) {
final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)expression;
removeParensFromConditionalExpression(conditionalExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiParenthesizedExpression) {
final PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression)expression;
removeParensFromParenthesizedExpression(parenthesizedExpression, ignoreClarifyingParentheses);
}
else if (expression instanceof PsiLambdaExpression) {
final PsiLambdaExpression lambdaExpression = (PsiLambdaExpression)expression;
removeParensFromLambdaExpression(lambdaExpression, ignoreClarifyingParentheses);
}
}
private static void removeParensFromLambdaExpression(PsiLambdaExpression lambdaExpression, boolean ignoreClarifyingParentheses) {
final PsiElement body = lambdaExpression.getBody();
if (body instanceof PsiExpression) {
removeParentheses((PsiExpression)body, ignoreClarifyingParentheses);
}
}
private static void removeParensFromReferenceExpression(@NotNull PsiReferenceExpression referenceExpression,
boolean ignoreClarifyingParentheses) {
final PsiExpression qualifier = referenceExpression.getQualifierExpression();
if (qualifier != null) {
removeParentheses(qualifier, ignoreClarifyingParentheses);
}
}
private static void removeParensFromParenthesizedExpression(@NotNull PsiParenthesizedExpression parenthesizedExpression,
boolean ignoreClarifyingParentheses) {
final PsiExpression body = parenthesizedExpression.getExpression();
if (body == null) {
new CommentTracker().deleteAndRestoreComments(parenthesizedExpression);
return;
}
final PsiElement parent = parenthesizedExpression.getParent();
if (!(parent instanceof PsiExpression) || !areParenthesesNeeded(body, (PsiExpression)parent, ignoreClarifyingParentheses)) {
PsiExpression newExpression = ExpressionUtils.replacePolyadicWithParent(parenthesizedExpression, body);
if (newExpression == null){
CommentTracker commentTracker = new CommentTracker();
commentTracker.markUnchanged(body);
newExpression = (PsiExpression)commentTracker.replaceAndRestoreComments(parenthesizedExpression, body);
}
removeParentheses(newExpression, ignoreClarifyingParentheses);
}
else {
removeParentheses(body, ignoreClarifyingParentheses);
}
}
private static void removeParensFromConditionalExpression(@NotNull PsiConditionalExpression conditionalExpression,
boolean ignoreClarifyingParentheses) {
final PsiExpression condition = conditionalExpression.getCondition();
removeParentheses(condition, ignoreClarifyingParentheses);
final PsiExpression thenBranch = conditionalExpression.getThenExpression();
if (thenBranch != null) {
removeParentheses(thenBranch, ignoreClarifyingParentheses);
}
final PsiExpression elseBranch = conditionalExpression.getElseExpression();
if (elseBranch != null) {
removeParentheses(elseBranch, ignoreClarifyingParentheses);
}
}
private static void removeParensFromInstanceOfExpression(@NotNull PsiInstanceOfExpression instanceofExpression,
boolean ignoreClarifyingParentheses) {
final PsiExpression operand = instanceofExpression.getOperand();
removeParentheses(operand, ignoreClarifyingParentheses);
}
private static void removeParensFromPolyadicExpression(@NotNull PsiPolyadicExpression polyadicExpression,
boolean ignoreClarifyingParentheses) {
for (PsiExpression operand : polyadicExpression.getOperands()) {
removeParentheses(operand, ignoreClarifyingParentheses);
}
}
private static void removeParensFromPostfixExpression(@NotNull PsiPostfixExpression postfixExpression,
boolean ignoreClarifyingParentheses) {
final PsiExpression operand = postfixExpression.getOperand();
removeParentheses(operand, ignoreClarifyingParentheses);
}
private static void removeParensFromPrefixExpression(@NotNull PsiPrefixExpression prefixExpression, boolean ignoreClarifyingParentheses) {
final PsiExpression operand = prefixExpression.getOperand();
if (operand != null) {
removeParentheses(operand, ignoreClarifyingParentheses);
}
}
private static void removeParensFromArrayAccessExpression(@NotNull PsiArrayAccessExpression arrayAccessExpression,
boolean ignoreClarifyingParentheses) {
final PsiExpression arrayExpression = arrayAccessExpression.getArrayExpression();
removeParentheses(arrayExpression, ignoreClarifyingParentheses);
final PsiExpression indexExpression = arrayAccessExpression.getIndexExpression();
if (indexExpression != null) {
removeParentheses(indexExpression, ignoreClarifyingParentheses);
}
}
private static void removeParensFromTypeCastExpression(@NotNull PsiTypeCastExpression typeCastExpression,
boolean ignoreClarifyingParentheses) {
final PsiExpression operand = typeCastExpression.getOperand();
if (operand != null) {
removeParentheses(operand, ignoreClarifyingParentheses);
}
}
private static void removeParensFromArrayInitializerExpression(@NotNull PsiArrayInitializerExpression arrayInitializerExpression,
boolean ignoreClarifyingParentheses) {
final PsiExpression[] initializers = arrayInitializerExpression.getInitializers();
for (final PsiExpression initializer : initializers) {
removeParentheses(initializer, ignoreClarifyingParentheses);
}
}
private static void removeParensFromAssignmentExpression(@NotNull PsiAssignmentExpression assignment,
boolean ignoreClarifyingParentheses) {
final PsiExpression lhs = assignment.getLExpression();
final PsiExpression rhs = assignment.getRExpression();
removeParentheses(lhs, ignoreClarifyingParentheses);
if (rhs != null) {
removeParentheses(rhs, ignoreClarifyingParentheses);
}
}
private static void removeParensFromNewExpression(@NotNull PsiNewExpression newExpression, boolean ignoreClarifyingParentheses) {
final PsiExpression[] dimensions = newExpression.getArrayDimensions();
for (PsiExpression dimension : dimensions) {
removeParentheses(dimension, ignoreClarifyingParentheses);
}
final PsiExpression qualifier = newExpression.getQualifier();
if (qualifier != null) {
removeParentheses(qualifier, ignoreClarifyingParentheses);
}
final PsiExpression arrayInitializer = newExpression.getArrayInitializer();
if (arrayInitializer != null) {
removeParentheses(arrayInitializer, ignoreClarifyingParentheses);
}
final PsiExpressionList argumentList = newExpression.getArgumentList();
if (argumentList != null) {
final PsiExpression[] arguments = argumentList.getExpressions();
for (PsiExpression argument : arguments) {
removeParentheses(argument, ignoreClarifyingParentheses);
}
}
}
private static void removeParensFromMethodCallExpression(@NotNull PsiMethodCallExpression methodCallExpression,
boolean ignoreClarifyingParentheses) {
final PsiReferenceExpression target = methodCallExpression.getMethodExpression();
final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
final PsiExpression[] arguments = argumentList.getExpressions();
removeParentheses(target, ignoreClarifyingParentheses);
for (final PsiExpression argument : arguments) {
removeParentheses(argument, ignoreClarifyingParentheses);
}
}
}
| apache-2.0 |
medicayun/medicayundicom | dcm4jboss-cdw/trunk/src/java/org/dcm4chex/cdw/mbean/SpoolDirService.java | 19161 | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), available at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* TIANI Medgraph AG.
* Portions created by the Initial Developer are Copyright (C) 2003-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gunter Zeilinger <gunter.zeilinger@tiani.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chex.cdw.mbean;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import org.dcm4che.util.MD5Utils;
import org.jboss.system.ServiceMBeanSupport;
import org.jboss.system.server.ServerConfigLocator;
/**
* @author gunter.zeilinter@tiani.com
* @version $Revision: 18290 $ $Date: 2014-05-06 20:27:53 +0800 (周二, 06 5月 2014) $
* @since 22.06.2004
*
*/
public class SpoolDirService extends ServiceMBeanSupport
implements NotificationListener {
static final long MIN_HWM = 10000000L;
static final long MS_PER_MINUTE = 60000L;
static final long MS_PER_HOUR = MS_PER_MINUTE * 60;
static final long MS_PER_DAY = MS_PER_HOUR * 24;
private String archiveDirPath;
private String emulateRequestDirPath;
private String filesetDirPath;
private String requestDirPath;
private String labelDirPath;
private File archiveDir;
private File emulateRequestDir;
private File filesetDir;
private File requestDir;
private File labelDir;
private long archiveDiskUsage = 0L;
private long archiveHighWaterMark = MIN_HWM;
private long aduRefreshTime;
private long aduRefreshInterval = MS_PER_HOUR;
private long filesetDiskUsage = 0L;
private long filesetHighWaterMark = MIN_HWM;
private long fsduRefreshTime;
private long fsduRefreshInterval = MS_PER_HOUR;
private long purgeLabelDirAfter = MS_PER_DAY;
private long purgeMediaCreationRequestsAfter = MS_PER_DAY;
private long purgeArchiveDirAfter = MS_PER_DAY;
private long purgeFilesetDirAfter = MS_PER_HOUR;
private int numberOfArchiveBuckets = 37;
private long purgeInterval = MS_PER_MINUTE;
private Integer schedulerID;
private final SchedulerDelegate scheduler = new SchedulerDelegate(this);
public ObjectName getSchedulerServiceName() {
return scheduler.getSchedulerServiceName();
}
public void setSchedulerServiceName(ObjectName schedulerServiceName) {
scheduler.setSchedulerServiceName(schedulerServiceName);
}
public final String getArchiveDirPath() {
return archiveDirPath;
}
public void setArchiveDirPath(String path) {
File dir = resolve(new File(path));
checkDir(dir);
this.archiveDirPath = path;
this.archiveDir = dir;
aduRefreshTime = 0L;
}
public final String getEmulateRequestDirPath() {
return emulateRequestDirPath;
}
public void setEmulateRequestDirPath(String path) {
File dir = resolve(new File(path));
checkDir(dir);
this.emulateRequestDirPath = path;
this.emulateRequestDir = dir;
}
private File resolve(File dir) {
if (dir.isAbsolute()) return dir;
File dataDir = ServerConfigLocator.locate().getServerDataDir();
return new File(dataDir, dir.getPath());
}
private void checkDir(File dir) {
if (dir.mkdirs()) log.debug("M-WRITE " + dir);
if (!dir.isDirectory() || !dir.canWrite())
throw new IllegalArgumentException(dir
+ " is not a writable directory!");
}
public final String getFilesetDirPath() {
return filesetDirPath;
}
public void setFilesetDirPath(String path) {
File dir = resolve(new File(path));
checkDir(dir);
this.filesetDirPath = path;
this.filesetDir = dir;
fsduRefreshTime = 0L;
}
public final String getRequestDirPath() {
return requestDirPath;
}
public void setRequestDirPath(String path) {
File dir = resolve(new File(path));
checkDir(dir);
this.requestDirPath = path;
this.requestDir = dir;
}
public final String getLabelDirPath() {
return labelDirPath;
}
public final void setLabelDirPath(String path) {
File dir = resolve(new File(path));
checkDir(dir);
this.labelDirPath = path;
this.labelDir = dir;
}
public final boolean isArchiveHighWater() {
return archiveDiskUsage > archiveHighWaterMark;
}
public final String getArchiveHighWaterMark() {
return MD5Utils.formatSize(archiveHighWaterMark);
}
public final void setArchiveHighWaterMark(String str) {
this.archiveHighWaterMark = MD5Utils.parseSize(str, MIN_HWM);
}
public final String getArchiveDiskUsage() {
return MD5Utils.formatSize(archiveDiskUsage);
}
public final boolean isFilesetHighWater() {
return filesetDiskUsage > filesetHighWaterMark;
}
public final String getFilesetHighWaterMark() {
return MD5Utils.formatSize(filesetHighWaterMark);
}
public final void setFilesetHighWaterMark(String str) {
this.filesetHighWaterMark = MD5Utils.parseSize(str, MIN_HWM);
}
public final String getFilesetDiskUsage() {
return MD5Utils.formatSize(filesetDiskUsage);
}
public String refreshArchiveDiskUsage() {
log.info("Start Calculating Archive Disk Usage");
archiveDiskUsage = 0L;
register(archiveDir);
log.info("Finished Calculating Archive Disk Usage: " + getArchiveDiskUsage());
aduRefreshTime = System.currentTimeMillis();
return getArchiveDiskUsage();
}
public String refreshFilesetDiskUsage() {
log.info("Start Calculating Fileset Disk Usage");
filesetDiskUsage = 0L;
register(filesetDir);
log.info("Finished Calculating Fileset Disk Usage: " + getFilesetDiskUsage());
fsduRefreshTime = System.currentTimeMillis();
return getFilesetDiskUsage();
}
public void register(File f) {
if (!f.exists()) return;
if (f.isDirectory()) {
String[] ss = f.list();
for (int i = 0; i < ss.length; i++)
register(new File(f, ss[i]));
} else {
final String fpath = f.getPath();
if (fpath.startsWith(archiveDir.getPath()))
archiveDiskUsage += f.length();
else if (fpath.startsWith(filesetDir.getPath()))
filesetDiskUsage += f.length();
}
}
public final int getNumberOfArchiveBuckets() {
return numberOfArchiveBuckets;
}
public final void setNumberOfArchiveBuckets(int numberOfArchiveBuckets) {
if (numberOfArchiveBuckets < 1 || numberOfArchiveBuckets > 1000)
throw new IllegalArgumentException("numberOfArchiveBuckets:"
+ numberOfArchiveBuckets + " is not between 1 and 1000");
this.numberOfArchiveBuckets = numberOfArchiveBuckets;
}
public final String getArchiveDiskUsageRefreshInterval() {
return timeAsString(aduRefreshInterval);
}
public final void setArchiveDiskUsageRefreshInterval(String refreshInterval) {
this.aduRefreshInterval = timeFromString(refreshInterval);
}
public final String getFilesetDiskUsageRefreshInterval() {
return timeAsString(fsduRefreshInterval);
}
public final void setFilesetDiskUsageRefreshInterval(String refreshInterval) {
this.fsduRefreshInterval = timeFromString(refreshInterval);
}
public final String getPurgeArchiveDirAfter() {
return timeAsString(purgeArchiveDirAfter);
}
public final void setPurgeArchiveDirAfter(String s) {
this.purgeArchiveDirAfter = timeFromString(s);
}
public final String getPurgeMediaCreationRequestsAfter() {
return timeAsString(purgeMediaCreationRequestsAfter);
}
public final void setPurgeMediaCreationRequestsAfter(String s) {
this.purgeMediaCreationRequestsAfter = timeFromString(s);
}
public final String getPurgeFilesetDirAfter() {
return timeAsString(purgeFilesetDirAfter);
}
public final void setPurgeFilesetDirAfter(String s) {
this.purgeFilesetDirAfter = timeFromString(s);
}
public final String getPurgeLabelDirAfter() {
return timeAsString(purgeLabelDirAfter);
}
public final void setPurgeLabelDirAfter(String s) {
this.purgeLabelDirAfter = timeFromString(s);
}
public final String getPurgeInterval() {
return timeAsString(purgeInterval);
}
public void setPurgeInterval(String interval) throws Exception {
this.purgeInterval = timeFromString(interval);
if (getState() == STARTED) {
scheduler.stopScheduler("PurgeSpoolDir", schedulerID, this);
schedulerID = scheduler.startScheduler("PurgeSpoolDir",
purgeInterval, this);
}
}
protected void startService() throws Exception {
schedulerID = scheduler.startScheduler("PurgeSpoolDir",
purgeInterval, this);
}
protected void stopService() throws Exception {
scheduler.stopScheduler("PurgeSpoolDir", schedulerID, this);
}
public File getInstanceFile(String iuid) {
final int i = (iuid.hashCode() & 0x7FFFFFFF) % numberOfArchiveBuckets;
File bucket = new File(archiveDir, String.valueOf(i));
if (bucket.mkdirs()) log.debug("Success: M-WRITE " + bucket);
return new File(bucket, iuid);
}
public File getMediaCreationRequestFile(String iuid) {
return new File(requestDir, iuid);
}
public File getLabelFile(String iuid, String ext) {
return new File(labelDir, iuid + '.' + ext);
}
public File getMediaFilesetRootDir(String iuid) {
return new File(filesetDir, iuid);
}
public File getEmulateRequestFile(String aet,String pattern) {
try {
return new File(new File(emulateRequestDir, aet),
URLEncoder.encode(
pattern,
"US-ASCII"));
} catch (UnsupportedEncodingException e) {
// should never happen
throw new RuntimeException(e);
}
}
public File[] getEmulateRequestFiles(String aet,
final long lastModifiedBefore) {
File dir = new File(emulateRequestDir, aet);
return maskNull(dir.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.lastModified() < lastModifiedBefore;
}}));
}
private static File[] NO_FILES = {};
private static File[] maskNull(File[] files) {
return files == null ? NO_FILES : files;
}
public void purge() {
purgeExpiredMediaCreationRequests();
purgeArchiveDir();
purgeFilesetDir();
purgeLabelDir();
final long now = System.currentTimeMillis();
if (now > aduRefreshTime + aduRefreshInterval)
refreshArchiveDiskUsage();
if (now > fsduRefreshTime + fsduRefreshInterval)
refreshFilesetDiskUsage();
}
public void purgeExpiredMediaCreationRequests() {
if (purgeArchiveDirAfter == 0) return;
deleteFilesModifiedBefore(requestDir, System.currentTimeMillis()
- purgeMediaCreationRequestsAfter);
}
public void purgeLabelDir() {
if (purgeLabelDirAfter == 0) return;
deleteFilesModifiedBefore(labelDir, System.currentTimeMillis()
- purgeLabelDirAfter);
}
public void purgeArchiveDir() {
if (purgeArchiveDirAfter == 0) return;
String[] ss = archiveDir.list();
if (ss == null) return;
final long modifiedBefore = System.currentTimeMillis()
- purgeArchiveDirAfter;
for (int i = 0; i < ss.length; i++) {
deleteFilesModifiedBefore(new File(archiveDir, ss[i]),
modifiedBefore);
}
}
public void purgeFilesetDir() {
if (purgeArchiveDirAfter == 0) return;
deleteFilesModifiedBefore(filesetDir, System.currentTimeMillis()
- purgeFilesetDirAfter);
}
private void deleteFilesModifiedBefore(File subdir, long modifiedBefore) {
String[] ss = subdir.list();
if (ss == null) return;
for (int i = 0, n = ss.length; i < n; i++) {
File f = new File(subdir, ss[i]);
if (f.lastModified() <= modifiedBefore) {
delete(f);
}
}
}
public boolean deleteInstanceFile(String iuid) {
return delete(getInstanceFile(iuid));
}
public boolean delete(File f) {
if (!f.exists()) return false;
long length = 0L;
if (f.isDirectory()) {
String[] ss = f.list();
for (int i = 0; i < ss.length; i++)
delete(new File(f, ss[i]));
} else {
length = f.length();
}
log.debug("Success: M-DELETE " + f);
boolean success = f.delete();
if (success) {
unregister(f, length);
} else
log.warn("Failed: M-DELETE " + f);
return success;
}
private void unregister(File f, long length) {
String fpath = f.getPath();
if (fpath.startsWith(archiveDir.getPath())) {
if ((archiveDiskUsage -= length) < 0L) {
log.info("Correct negative ArchiveDiskUsage: "
+ archiveDiskUsage);
archiveDiskUsage = 0L;
}
} else if (fpath.startsWith(filesetDir.getPath())) {
if ((filesetDiskUsage -= length) < 0L) {
log.info("Correct negative FilesetDiskUsage: "
+ filesetDiskUsage);
filesetDiskUsage = 0L;
}
}
}
public boolean copy(File src, File dest, byte[] b) {
if (src.isDirectory()) {
String[] ss = src.list();
for (int i = 0; i < ss.length; i++)
if (!copy(new File(src, ss[i]), new File(dest, ss[i]), b))
return false;
return true;
}
delete(dest);
dest.getParentFile().mkdirs();
try {
FileInputStream fis = new FileInputStream(src);
try {
FileOutputStream fos = new FileOutputStream(dest);
try {
int read;
while ((read = fis.read(b)) != -1)
fos.write(b, 0, read);
} finally {
try {
fos.close();
} catch (IOException ignore) {
}
register(dest);
}
} finally {
fis.close();
}
if (log.isDebugEnabled())
log.debug("Success: M-COPY " + src + " -> " + dest);
return true;
} catch (IOException e) {
log.error("Failed: M-COPY " + src + " -> " + dest, e);
return false;
}
}
public boolean move(File src, File dest) {
if (!src.exists()) return false;
if (src.isDirectory()) {
String[] ss = src.list();
for (int i = 0; i < ss.length; i++)
if (!move(new File(src, ss[i]), new File(dest, ss[i])))
return false;
return true;
}
delete(dest);
dest.getParentFile().mkdirs();
if (src.renameTo(dest)) {
unregister(src, dest.length());
register(dest);
if (log.isDebugEnabled())
log.debug("Success: M-MOVE " + src + " -> " + dest);
return true;
}
log.error("Failed: M-MOVE " + src + " -> " + dest);
return false;
}
static String timeAsString(long ms) {
if (ms == 0) return "0";
if (ms % MS_PER_DAY == 0) return "" + (ms / MS_PER_DAY) + 'd';
if (ms % MS_PER_HOUR == 0) return "" + (ms / MS_PER_HOUR) + 'h';
if (ms % MS_PER_MINUTE == 0) return "" + (ms / MS_PER_MINUTE) + 'm';
if (ms % 1000 == 0) return "" + (ms / 1000) + 's';
return "" + ms + "ms";
}
static long timeFromString(String str) {
String s = str.trim().toLowerCase();
try {
if (s.endsWith("d"))
return Long.parseLong(s.substring(0, s.length() - 1))
* MS_PER_DAY;
if (s.endsWith("h"))
return Long.parseLong(s.substring(0, s.length() - 1))
* MS_PER_HOUR;
if (s.endsWith("m"))
return Long.parseLong(s.substring(0, s.length() - 1))
* MS_PER_MINUTE;
if (s.endsWith("s"))
return Long.parseLong(s.substring(0, s.length() - 1)) * 1000;
if (s.endsWith("ms"))
return Long.parseLong(s.substring(0, s.length() - 2));
if (Long.parseLong(s) == 0L) return 0L;
} catch (NumberFormatException e) {
}
throw new IllegalArgumentException(str);
}
public void handleNotification(Notification notif, Object handback) {
purge();
}
} | apache-2.0 |
AndiHappy/solo | src/test/java/org/b3log/solo/processor/console/CategoryConsoleTestCase.java | 6191 | /*
* Copyright (c) 2010-2017, b3log.org & hacpai.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.solo.processor.console;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.model.User;
import org.b3log.solo.AbstractTestCase;
import org.b3log.solo.model.Category;
import org.b3log.solo.processor.MockDispatcherServlet;
import org.b3log.solo.service.InitService;
import org.b3log.solo.service.UserQueryService;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* {@link CategoryConsole} test case.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.0, Apr 22, 2017
* @since 2.1.0
*/
@Test(suiteName = "processor")
public class CategoryConsoleTestCase extends AbstractTestCase {
/**
* Init.
*
* @throws Exception exception
*/
@Test
public void init() throws Exception {
final InitService initService = getInitService();
final JSONObject requestJSONObject = new JSONObject();
requestJSONObject.put(User.USER_EMAIL, "test@gmail.com");
requestJSONObject.put(User.USER_NAME, "Admin");
requestJSONObject.put(User.USER_PASSWORD, "pass");
initService.init(requestJSONObject);
final UserQueryService userQueryService = getUserQueryService();
Assert.assertNotNull(userQueryService.getUserByEmail("test@gmail.com"));
}
/**
* addCategory.
*
* @throws Exception exception
*/
@Test(dependsOnMethods = "init")
public void addCategory() throws Exception {
final HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getServletContext()).thenReturn(mock(ServletContext.class));
when(request.getRequestURI()).thenReturn("/console/category/");
when(request.getMethod()).thenReturn("POST");
final JSONObject adminUser = getUserQueryService().getAdmin();
final HttpSession httpSession = mock(HttpSession.class);
when(httpSession.getAttribute(User.USER)).thenReturn(adminUser);
when(request.getSession(false)).thenReturn(httpSession);
final JSONObject requestJSON = new JSONObject();
requestJSON.put(Category.CATEGORY_T_TAGS, "Solo");
requestJSON.put(Category.CATEGORY_TITLE, "分类1");
requestJSON.put(Category.CATEGORY_URI, "cate1");
final BufferedReader reader = new BufferedReader(new StringReader(requestJSON.toString()));
when(request.getReader()).thenReturn(reader);
final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
dispatcherServlet.init();
final StringWriter stringWriter = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringWriter);
final HttpServletResponse response = mock(HttpServletResponse.class);
when(response.getWriter()).thenReturn(printWriter);
dispatcherServlet.service(request, response);
final String content = stringWriter.toString();
Assert.assertTrue(StringUtils.contains(content, "sc\":true"));
}
/**
* updateCategory.
*
* @throws Exception exception
*/
@Test(dependsOnMethods = "addCategory")
public void updateCategory() throws Exception {
final HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getServletContext()).thenReturn(mock(ServletContext.class));
when(request.getRequestURI()).thenReturn("/console/category/");
when(request.getMethod()).thenReturn("PUT");
final JSONObject adminUser = getUserQueryService().getAdmin();
final HttpSession httpSession = mock(HttpSession.class);
when(httpSession.getAttribute(User.USER)).thenReturn(adminUser);
when(request.getSession(false)).thenReturn(httpSession);
JSONObject category = getCategoryQueryService().getByTitle("分类1");
final JSONObject requestJSON = new JSONObject();
requestJSON.put(Category.CATEGORY_T_TAGS, "Solo");
requestJSON.put(Keys.OBJECT_ID, category.optString(Keys.OBJECT_ID));
requestJSON.put(Category.CATEGORY_TITLE, "新的分类1");
final BufferedReader reader = new BufferedReader(new StringReader(requestJSON.toString()));
when(request.getReader()).thenReturn(reader);
final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
dispatcherServlet.init();
final StringWriter stringWriter = new StringWriter();
final PrintWriter printWriter = new PrintWriter(stringWriter);
final HttpServletResponse response = mock(HttpServletResponse.class);
when(response.getWriter()).thenReturn(printWriter);
dispatcherServlet.service(request, response);
final String content = stringWriter.toString();
Assert.assertTrue(StringUtils.contains(content, "sc\":true"));
category = getCategoryQueryService().getByTitle("分类1");
Assert.assertNull(category);
category = getCategoryQueryService().getByTitle("新的分类1");
Assert.assertNotNull(category);
Assert.assertEquals(category.optInt(Category.CATEGORY_TAG_CNT), 1); // https://github.com/b3log/solo/issues/12274
}
}
| apache-2.0 |
daniyar-artykov/j2ee | upwork-jax-ws-client/src/main/java/com/accenture/nes/webservices/IVRTicketManagementService.java | 2870 |
package com.accenture.nes.webservices;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.1.6 in JDK 6
* Generated source version: 2.1
*
*/
@WebServiceClient(name = "IVRTicketManagementService", targetNamespace = "http://webservices.nes.accenture.com", wsdlLocation = "file:/home/abhayk/workspaces/jar/Solexjar/IVRTicketManagementService.wsdl")
public class IVRTicketManagementService
extends Service
{
private final static URL IVRTICKETMANAGEMENTSERVICE_WSDL_LOCATION;
private final static Logger logger = Logger.getLogger(com.accenture.nes.webservices.IVRTicketManagementService.class.getName());
static {
URL url = null;
try {
URL baseUrl;
baseUrl = com.accenture.nes.webservices.IVRTicketManagementService.class.getResource(".");
url = new URL(baseUrl, "file:/home/abhayk/workspaces/jar/Solexjar/IVRTicketManagementService.wsdl");
} catch (MalformedURLException e) {
logger.warning("Failed to create URL for the wsdl Location: 'file:/home/abhayk/workspaces/jar/Solexjar/IVRTicketManagementService.wsdl', retrying as a local file");
logger.warning(e.getMessage());
}
IVRTICKETMANAGEMENTSERVICE_WSDL_LOCATION = url;
}
public IVRTicketManagementService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public IVRTicketManagementService() {
super(IVRTICKETMANAGEMENTSERVICE_WSDL_LOCATION, new QName("http://webservices.nes.accenture.com", "IVRTicketManagementService"));
}
/**
*
* @return
* returns IIVRTicketManagementService
*/
@WebEndpoint(name = "IVRTicketManagementServiceImplPort")
public IIVRTicketManagementService getIVRTicketManagementServiceImplPort() {
return super.getPort(new QName("http://webservices.nes.accenture.com", "IVRTicketManagementServiceImplPort"), IIVRTicketManagementService.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns IIVRTicketManagementService
*/
@WebEndpoint(name = "IVRTicketManagementServiceImplPort")
public IIVRTicketManagementService getIVRTicketManagementServiceImplPort(WebServiceFeature... features) {
return super.getPort(new QName("http://webservices.nes.accenture.com", "IVRTicketManagementServiceImplPort"), IIVRTicketManagementService.class, features);
}
}
| apache-2.0 |
yanzhijun/jclouds-aliyun | apis/cloudstack/src/main/java/org/jclouds/cloudstack/util/ApiKeyPairs.java | 3447 | /*
* 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.jclouds.cloudstack.util;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import org.jclouds.Constants;
import org.jclouds.ContextBuilder;
import org.jclouds.cloudstack.CloudStackApiMetadata;
import org.jclouds.cloudstack.CloudStackApi;
import org.jclouds.cloudstack.CloudStackContext;
import org.jclouds.cloudstack.domain.Account;
import org.jclouds.cloudstack.domain.ApiKeyPair;
import org.jclouds.cloudstack.domain.User;
public class ApiKeyPairs {
/**
* Retrieve the API key pair for a given CloudStack user
*
* @param endpoint
* CloudStack API endpoint (e.g. http://72.52.126.25/client/api/)
* @param username
* User account name
* @param password
* User password
* @param domain
* Domain name. If empty defaults to ROOT
* @throws NoSuchElementException, AuthorizationException
* @return
*/
public static ApiKeyPair loginToEndpointAsUsernameInDomainWithPasswordAndReturnApiKeyPair(
URI endpoint, String username, String password, String domain) {
CloudStackContext context = null;
try {
Properties overrides = new Properties();
overrides.put(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
overrides.put(Constants.PROPERTY_RELAX_HOSTNAME, "true");
overrides.put("jclouds.cloudstack.credential-type", "passwordCredentials");
context = ContextBuilder.newBuilder(new CloudStackApiMetadata())
.endpoint(checkNotNull(endpoint, "endpoint").toASCIIString())
.credentials(String.format("%s/%s", checkNotNull(domain, "domain"), checkNotNull(username, "username")), password)
.overrides(overrides).build(CloudStackContext.class);
CloudStackApi client = context.getApi();
Set<Account> listOfAccounts = client.getAccountApi().listAccounts();
domain = (domain.equals("") || domain.equals("/")) ? "ROOT" : domain;
for (Account account : listOfAccounts) {
for (User user : account.getUsers()) {
if (user.getName().equals(username) && user.getDomain().equals(domain)) {
return ApiKeyPair.builder().apiKey(user.getApiKey())
.secretKey(user.getSecretKey()).build();
}
}
}
throw new NoSuchElementException("Unable to find API keypair for user " + username);
} finally {
if (context != null)
context.close();
}
}
}
| apache-2.0 |
TeachingKidsProgramming/TeachingKidsProgramming.Source.Java | src/main/java/org/teachingextensions/approvals/lite/util/JUnitUtils.java | 319 | package org.teachingextensions.approvals.lite.util;
import static org.junit.Assume.assumeFalse;
import java.awt.GraphicsEnvironment;
public class JUnitUtils {
public static void assumeNotHeadless() {
boolean headless_check = GraphicsEnvironment.isHeadless();
assumeFalse(headless_check);
}
}
| apache-2.0 |
renmeng8875/projects | Hibernate-source/源代码及重要说明/Hibernate相关资料/hibernate-3.2.0.ga/hibernate-3.2/src/org/hibernate/tuple/component/ComponentTuplizer.java | 1757 | //$Id: ComponentTuplizer.java 7451 2005-07-11 21:49:08Z steveebersole $
package org.hibernate.tuple.component;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.tuple.Tuplizer;
/**
* Defines further responsibilities reagarding tuplization based on
* a mapped components.
* </p>
* ComponentTuplizer implementations should have the following constructor signature:
* (org.hibernate.mapping.Component)
*
* @author Gavin King
* @author Steve Ebersole
*/
public interface ComponentTuplizer extends Tuplizer, Serializable {
/**
* Retreive the current value of the parent property.
*
* @param component The component instance from which to extract the parent
* property value.
* @return The current value of the parent property.
*/
public Object getParent(Object component);
/**
* Set the value of the parent property.
*
* @param component The component instance on which to set the parent.
* @param parent The parent to be set on the comonent.
* @param factory The current session factory.
*/
public void setParent(Object component, Object parent, SessionFactoryImplementor factory);
/**
* Does the component managed by this tuuplizer contain a parent property?
*
* @return True if the component does contain a parent property; false otherwise.
*/
public boolean hasParentProperty();
/**
* Is the given method available via the managed component as a property getter?
*
* @param method The method which to check against the managed component.
* @return True if the managed component is available from the managed component; else false.
*/
public boolean isMethodOf(Method method);
}
| apache-2.0 |
chenjianping99/CradCool | src/com/jiubang/goscreenlock/theme/cjpcardcool/util/ImageUtils.java | 26006 | package com.jiubang.goscreenlock.theme.cjpcardcool.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.View;
/**
*
* <br>类描述:图片操作工具包
* <br>功能详细描述:
*
* @author June Kwok
* @date [2013-7-23]
*/
//CHECKSTYLE:OFF
public class ImageUtils {
public final static String SDCARD_MNT = "/mnt/sdcard";
public final static String SDCARD = "/sdcard";
/** 请求相册 */
public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
/** 请求相机 */
public static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
/** 请求裁剪 */
public static final int REQUEST_CODE_GETIMAGE_BYCROP = 2;
/** 应用图标的长和宽 **/
public static final int APP_ICON_WIDTH = 72;
public static final int APP_ICON_HEIGHT = 72;
/** 图标圆角的size**/
public static final int ICON_ARROUND_SIZE = 40;
/**
* <br>功能简述:写图片文件 在Android系统中,文件保存在 /data/data/PACKAGE_NAME/files 目录下
* <br>功能详细描述:
* <br>注意:
* @param context
* @param fileName
* @param bitmap
* @throws IOException
*/
public static void saveImage(Context context, String fileName, Bitmap bitmap) throws IOException {
saveImage(context, fileName, bitmap, 100);
}
public static void saveImage(Context context, String fileName, Bitmap bitmap, int quality) throws IOException {
if (bitmap == null || fileName == null || context == null) {
return;
}
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, stream);
byte[] bytes = stream.toByteArray();
fos.write(bytes);
fos.close();
}
/**
* <br>功能简述:写图片文件到SD卡
* <br>功能详细描述:
* <br>注意:
* @param filePath
* @param bitmap
* @param quality
* @throws IOException
*/
public static void saveImageToSD(String filePath, Bitmap bitmap, int quality) throws IOException {
if (bitmap != null) {
FileOutputStream fos = new FileOutputStream(filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, stream);
byte[] bytes = stream.toByteArray();
fos.write(bytes);
fos.close();
}
}
/**
* <br>功能简述:获取bitmap
* <br>功能详细描述:
* <br>注意:
* @param context
* @param fileName
* @return
*/
public static Bitmap getBitmap(Context context, String fileName) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
fis = context.openFileInput(fileName);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return bitmap;
}
/**
* <br>功能简述:获取bitmap
* <br>功能详细描述:
* <br>注意:
* @param filePath
* @return
*/
public static Bitmap getBitmapByPath(String filePath) {
return getBitmapByPath(filePath, null);
}
public static Bitmap getBitmapByPath(String filePath, BitmapFactory.Options opts) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
File file = new File(filePath);
fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis, null, opts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return bitmap;
}
/**
* <br>功能简述:获取bitmap
* <br>功能详细描述:
* <br>注意:
* @param file
* @return
*/
public static Bitmap getBitmapByFile(File file) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return bitmap;
}
/**
* <br>功能简述:使用当前时间戳拼接一个唯一的文件名
* <br>功能详细描述:
* <br>注意:
* @return
*/
public static String getTempFileName() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS");
String fileName = format.format(new Timestamp(System.currentTimeMillis()));
return fileName;
}
/**
* <br>功能简述:获取照相机使用的目录
* <br>功能详细描述:
* <br>注意:
* @return
*/
public static String getCamerPath() {
return Environment.getExternalStorageDirectory() + File.separator + "FounderNews" + File.separator;
}
/**
* <br>功能简述:判断当前Url是否标准的content://样式,如果不是,则返回绝对路径
* <br>功能详细描述:
* <br>注意:
* @param mUri
* @return
*/
public static String getAbsolutePathFromNoStandardUri(Uri mUri) {
String filePath = null;
String mUriString = mUri.toString();
mUriString = Uri.decode(mUriString);
String pre1 = "file://" + SDCARD + File.separator;
String pre2 = "file://" + SDCARD_MNT + File.separator;
if (mUriString.startsWith(pre1)) {
filePath = Environment.getExternalStorageDirectory().getPath() + File.separator + mUriString.substring(pre1.length());
} else if (mUriString.startsWith(pre2)) {
filePath = Environment.getExternalStorageDirectory().getPath() + File.separator + mUriString.substring(pre2.length());
}
return filePath;
}
/**
* <br>功能简述:通过uri获取文件的绝对路径
* <br>功能详细描述:
* <br>注意:
* @param context
* @param uri
* @return
*/
@SuppressWarnings("deprecation")
public static String getAbsoluteImagePath(Activity context, Uri uri) {
String imagePath = "";
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.managedQuery(uri, proj, // Which columns to
// return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.getCount() > 0 && cursor.moveToFirst()) {
imagePath = cursor.getString(column_index);
}
}
return imagePath;
}
/**
* <br>功能简述:获取图片缩略图 只有Android2.1以上版本支持
* <br>功能详细描述:
* <br>注意:
* @param context
* @param imgName
* @param kind
* @return
*/
@SuppressWarnings("deprecation")
public static Bitmap loadImgThumbnail(Activity context, String imgName, int kind) {
Bitmap bitmap = null;
String[] proj = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME };
Cursor cursor = context.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, MediaStore.Images.Media.DISPLAY_NAME + "='" + imgName + "'", null, null);
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
//ContentResolver crThumb = context.getContentResolver();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
//bitmap = MethodsCompat.getThumbnail(crThumb, cursor.getInt(0),
//kind, options);
}
return bitmap;
}
/**
* <br>功能简述:获取缩略图
* <br>功能详细描述:
* <br>注意:
* @param filePath
* @param w
* @param h
* @return
*/
public static Bitmap loadImgThumbnail(String filePath, int w, int h) {
Bitmap bitmap = getBitmapByPath(filePath);
return zoomBitmap(bitmap, w, h);
}
/**
* <br>功能简述:获取SD卡中最新图片路径
* <br>功能详细描述:
* <br>注意:
* @param context
* @return
*/
@SuppressWarnings("deprecation")
public static String getLatestImage(Activity context) {
String latestImage = null;
String[] items = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
Cursor cursor = context.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items, null, null, MediaStore.Images.Media._ID + " desc");
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
latestImage = cursor.getString(1);
break;
}
}
return latestImage;
}
/**
* <br>功能简述:计算缩放图片的size
* <br>功能详细描述:
* <br>注意:
* @param img_size
* @param square_size
* @return
*/
public static int[] scaleImageSize(int[] img_size, int square_size) {
if (img_size[0] <= square_size && img_size[1] <= square_size)
return img_size;
double ratio = square_size / (double) Math.max(img_size[0], img_size[1]);
return new int[] { (int) (img_size[0] * ratio), (int) (img_size[1] * ratio) };
}
/**
* <br>功能简述:创建缩略图
* <br>功能详细描述:
* <br>注意:
* @param context
* @param largeImagePath
* @param thumbfilePath
* @param square_size
* @param quality
* @throws IOException
*/
public static void createImageThumbnail(Context context, String largeImagePath, String thumbfilePath, int square_size, int quality) throws IOException {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 1;
// 原始图片bitmap
Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts);
if (cur_bitmap == null)
return;
// 原始图片的高宽
int[] cur_img_size = new int[] { cur_bitmap.getWidth(), cur_bitmap.getHeight() };
// 计算原始图片缩放后的宽高
int[] new_img_size = scaleImageSize(cur_img_size, square_size);
// 生成缩放后的bitmap
Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0], new_img_size[1]);
// 生成缩放后的图片文件
saveImageToSD(thumbfilePath, thb_bitmap, quality);
}
/**
* <br>功能简述:放大缩小图片
* <br>功能详细描述:
* <br>注意:
* @param bitmap
* @param w
* @param h
* @return
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
Bitmap newbmp = null;
if (bitmap != null) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidht = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidht, scaleHeight);
newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}
return newbmp;
}
/**
* <br>功能简述:把图片转换成指定大小
* <br>功能详细描述:
* <br>注意:
* @param bitmap
* @param w
* @param h
* @return
*/
public static Bitmap scaleBitmap(Bitmap bitmap, int w, int h) {
if (bitmap != null) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = w;
int newHeight = h;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 旋转图片 动作
// matrix.postRotate(45);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
return resizedBitmap;
}
return null;
}
/**
* <br>功能简述:把图片转换成指定大小
* <br>功能详细描述:
* <br>注意:
* @param bitmap
* @return
*/
public static Bitmap scaleBitmap(Bitmap bitmap) {
return scaleBitmap(bitmap, APP_ICON_WIDTH, APP_ICON_HEIGHT);
}
/**
* <br>功能简述:(缩放)重绘图片
* <br>功能详细描述:
* <br>注意:
* @param context
* @param bitmap
* @return
*/
public static Bitmap reDrawBitMap(Activity context, Bitmap bitmap) {
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int rHeight = dm.heightPixels;
int rWidth = dm.widthPixels;
// float rHeight=dm.heightPixels/dm.density+0.5f;
// float rWidth=dm.widthPixels/dm.density+0.5f;
// int height=bitmap.getScaledHeight(dm);
// int width = bitmap.getScaledWidth(dm);
int height = bitmap.getHeight();
int width = bitmap.getWidth();
float zoomScale;
/** 方式1 **/
// if(rWidth/rHeight>width/height){//以高为准
// zoomScale=((float) rHeight) / height;
// }else{
// //if(rWidth/rHeight<width/height)//以宽为准
// zoomScale=((float) rWidth) / width;
// }
/** 方式2 **/
// if(width*1.5 >= height) {//以宽为准
// if(width >= rWidth)
// zoomScale = ((float) rWidth) / width;
// else
// zoomScale = 1.0f;
// }else {//以高为准
// if(height >= rHeight)
// zoomScale = ((float) rHeight) / height;
// else
// zoomScale = 1.0f;
// }
/** 方式3 **/
if (width >= rWidth)
zoomScale = ((float) rWidth) / width;
else
zoomScale = 1.0f;
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 缩放图片动作
matrix.postScale(zoomScale, zoomScale);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
/**
* <br>功能简述:将Drawable转化为Bitmap
* <br>功能详细描述:
* <br>注意:
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable != null) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);
return bitmap;
}
return null;
}
/**
* <br>功能简述:获得圆角图片的方法
* <br>功能详细描述:
* <br>注意:
* @param bitmap
* @param roundPx
* @return
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xFFFFFFFF;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* <br>功能简述:获得圆角为固定size图片的方法
* <br>功能详细描述:
* <br>注意:
* @param bitmap
* @return
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
return getRoundedCornerBitmap(bitmap, ICON_ARROUND_SIZE);
}
/**
* <br>功能简述:此方法获取应用图标标准样式Bitmap
* <br>功能详细描述:
* <br>注意:
* @param bitmap
* @return
*/
public static Bitmap getAppStyleBitmap(Bitmap bitmap, Bitmap b) {
return scaleBitmap(bitmap, b.getWidth(), b.getHeight());
}
/**
* <br>功能简述:获得带倒影的图片方法
* <br>功能详细描述:
* <br>注意:
* @param bitmap
* @return
*/
public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
final int reflectionGap = 4;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint deafalutPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);
return bitmapWithReflection;
}
/**
* <br>功能简述:将bitmap转化为drawable
* <br>功能详细描述:
* <br>注意:
* @param bitmap
* @return
*/
public static Drawable bitmapToDrawable(Bitmap bitmap) {
Drawable drawable = new BitmapDrawable(bitmap);
return drawable;
}
/**
* <br>功能简述:获取图片类型
* <br>功能详细描述:
* <br>注意:
* @param file
* @return
*/
public static String getImageType(File file) {
if (file == null || !file.exists()) {
return null;
}
InputStream in = null;
try {
in = new FileInputStream(file);
String type = getImageType(in);
return type;
} catch (IOException e) {
return null;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
}
/**
* detect bytes's image type by inputstream
*
* @param in
* @return
* @see #getImageType(byte[])
*/
public static String getImageType(InputStream in) {
if (in == null) {
return null;
}
try {
byte[] bytes = new byte[8];
in.read(bytes);
return getImageType(bytes);
} catch (IOException e) {
return null;
}
}
/**
* detect bytes's image type
*
* @param bytes
* 2~8 byte at beginning of the image file
* @return image mimetype or null if the file is not image
*/
public static String getImageType(byte[] bytes) {
if (isJPEG(bytes)) {
return "image/jpeg";
}
if (isGIF(bytes)) {
return "image/gif";
}
if (isPNG(bytes)) {
return "image/png";
}
if (isBMP(bytes)) {
return "application/x-bmp";
}
return null;
}
private static boolean isJPEG(byte[] b) {
if (b.length < 2) {
return false;
}
return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8);
}
private static boolean isGIF(byte[] b) {
if (b.length < 6) {
return false;
}
return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8' && (b[4] == '7' || b[4] == '9') && b[5] == 'a';
}
private static boolean isPNG(byte[] b) {
if (b.length < 8) {
return false;
}
return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78 && b[3] == (byte) 71 && b[4] == (byte) 13 && b[5] == (byte) 10 && b[6] == (byte) 26 && b[7] == (byte) 10);
}
private static boolean isBMP(byte[] b) {
if (b.length < 2) {
return false;
}
return (b[0] == 0x42) && (b[1] == 0x4d);
}
/**
* 图片转灰
*
* @param bmSrc
* @return
*/
public static Bitmap bitmap2Gray(Bitmap bmSrc) {
int width, height;
height = bmSrc.getHeight();
width = bmSrc.getWidth();
Bitmap bmpGray = null;
bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGray);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmSrc, 0, 0, paint);
return bmpGray;
}
/**
*
* @param bm
* @param left
* @param top
* @param right
* @param bottom
* @param width
* @param height
* @return
*/
public static Bitmap cutBitmap(View vw, int left, int top, int right, int bottom, int width, int height) {
Bitmap bmpGray = null;
bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGray);
c.translate(-left, -top);
vw.draw(c);
// c.drawColor(0xCCFFFFFF);
// c.drawBitmap(bm, -left, -top, null);
return bmpGray;
}
/**
* 按照参数截图
* @param bm 被截取的图
* @param left
* @param top
* @param right
* @param bottom
* @param width
* @param height
* @return
*/
public static Bitmap cutBitmap(Bitmap bm, int left, int top, int right, int bottom, int width, int height) {
Bitmap bmpGray = null;
bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGray);
c.drawBitmap(bm, -left, -top, null);
return bmpGray;
}
/**
* 覆盖一层均衡颜色的图
* @param bm 被覆盖的图
* @return
*/
public static Bitmap coverBitmap(Bitmap bm) {
int height = bm.getHeight();
int width = bm.getWidth();
Bitmap bmpGray = null;
bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGray);
c.drawBitmap(bm, 0, 0, null);
c.drawColor(0x33FFFFFF);
return bmpGray;
}
/**
* 高斯模糊图片
* @param sentBitmap 被模糊的图
* @param radius 模糊半径
* @return
*/
public static Bitmap getGaussina(Bitmap sentBitmap, int radius) {
Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
if (radius < 1) {
return null;
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int[] pix = new int[w * h];
bitmap.getPixels(pix, 0, w, 0, 0, w, h);
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
int r[] = new int[wh];
int g[] = new int[wh];
int b[] = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int vmin[] = new int[Math.max(w, h)];
int divsum = (div + 1) >> 1;
divsum *= divsum;
int dv[] = new int[256 * divsum];
for (i = 0; i < 256 * divsum; i++) {
dv[i] = i / divsum;
}
yw = yi = 0;
int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = p & 0x0000ff;
rbs = r1 - Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = p & 0x0000ff;
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = Math.max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = Math.min(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
bitmap.setPixels(pix, 0, w, 0, 0, w, h);
return bitmap;
}
}
| apache-2.0 |
mdunker/usergrid | stack/corepersistence/common/src/main/java/org/apache/usergrid/persistence/core/migration/schema/MigrationManager.java | 1313 | /*
* 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.usergrid.persistence.core.migration.schema;
/**
* A manager that will perform any migrations necessary. Setup code should invoke the implementation of this interface
*
* @author tnine
*/
public interface MigrationManager {
/**
* Perform any migration necessary in the application. Will only create keyspaces and column families if they do
* not exist
* @param forceCheckSchema
*/
void migrate(boolean forceCheckSchema) throws MigrationException;
}
| apache-2.0 |
lenguyenthanh/mosby | mvi/src/main/java/com/hannesdorfmann/mosby3/FragmentMviDelegateImpl.java | 9754 | /*
* Copyright 2016 Hannes Dorfmann.
*
* 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.hannesdorfmann.mosby3;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.BackstackAccessor;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hannesdorfmann.mosby3.mvi.MviPresenter;
import com.hannesdorfmann.mosby3.mvp.MvpView;
import java.util.UUID;
/**
* The default implementation of {@link FragmentMviDelegate}
* <p>
* The View is attached to the Presenter in {@link Fragment#onStart()}.
* So you better instantiate all your UI widgets before that lifecycle callback (typically in
* {@link
* Fragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}. The View is detached from Presenter in
* {@link Fragment#onStop()}
* </p>
*
* @param <V> The type of {@link MvpView}
* @param <P> The type of {@link MviPresenter}
* @author Hannes Dorfmann
* @see FragmentMviDelegate
* @since 3.0.0
*/
public class FragmentMviDelegateImpl<V extends MvpView, P extends MviPresenter<V, ?>>
implements FragmentMviDelegate<V, P> {
public static boolean DEBUG = false;
private static final String DEBUG_TAG = "FragmentMviDelegateImpl";
private static final String KEY_MOSBY_VIEW_ID = "com.hannesdorfmann.mosby3.fragment.mvi.id";
private String mosbyViewId = null;
private MviDelegateCallback<V, P> delegateCallback;
private Fragment fragment;
private boolean onViewCreatedCalled = false;
private final boolean keepPresenterDuringScreenOrientationChange;
private final boolean keepPresenterOnBackstack;
private P presenter;
public FragmentMviDelegateImpl(@NonNull MviDelegateCallback<V, P> delegateCallback,
@NonNull Fragment fragment) {
this(delegateCallback, fragment, true, true);
}
public FragmentMviDelegateImpl(@NonNull MviDelegateCallback<V, P> delegateCallback,
@NonNull Fragment fragment, boolean keepPresenterDuringScreenOrientationChange,
boolean keepPresenterOnBackstack) {
if (delegateCallback == null) {
throw new NullPointerException("delegateCallback == null");
}
if (fragment == null) {
throw new NullPointerException("fragment == null");
}
if (!keepPresenterDuringScreenOrientationChange && keepPresenterOnBackstack) {
throw new IllegalArgumentException("It is not possible to keep the presenter on backstack, "
+ "but NOT keep presenter through screen orientation changes. Keep presenter on backstack also "
+ "requires keep presenter through screen orientation changes to be enabled");
}
this.delegateCallback = delegateCallback;
this.fragment = fragment;
this.keepPresenterDuringScreenOrientationChange = keepPresenterDuringScreenOrientationChange;
this.keepPresenterOnBackstack = keepPresenterOnBackstack;
}
@Override public void onViewCreated(View v, @Nullable Bundle savedInstanceState) {
onViewCreatedCalled = true;
}
@Override public void onStart() {
boolean viewStateWillBeRestored = false;
if (mosbyViewId == null) {
// No presenter available,
// Activity is starting for the first time (or keepPresenterDuringScreenOrientationChange == false)
presenter = createViewIdAndCreatePresenter();
if (DEBUG) {
Log.d(DEBUG_TAG, "new Presenter instance created: " + presenter);
}
} else {
presenter = PresenterManager.getPresenter(getActivity(), mosbyViewId);
if (presenter == null) {
// Process death,
// hence no presenter with the given viewState id stored, although we have a viewState id
presenter = createViewIdAndCreatePresenter();
if (DEBUG) {
Log.d(DEBUG_TAG,
"No Presenter instance found in cache, although MosbyView ID present. This was caused by process death, therefore new Presenter instance created: "
+ presenter);
}
} else {
viewStateWillBeRestored = true;
if (DEBUG) {
Log.d(DEBUG_TAG, "Presenter instance reused from internal cache: " + presenter);
}
}
}
// presenter is ready, so attach viewState
V view = delegateCallback.getMvpView();
if (view == null) {
throw new NullPointerException(
"MvpView returned from getMvpView() is null. Returned by " + fragment);
}
if (presenter == null) {
throw new IllegalStateException(
"Oops, Presenter is null. This seems to be a Mosby internal bug. Please report this issue here: https://github.com/sockeqwe/mosby/issues");
}
if (viewStateWillBeRestored) {
delegateCallback.setRestoringViewState(true);
}
presenter.attachView(view);
if (viewStateWillBeRestored) {
delegateCallback.setRestoringViewState(false);
}
if (DEBUG) {
Log.d(DEBUG_TAG,
"MvpView attached to Presenter. MvpView: " + view + " Presenter: " + presenter);
}
}
@Override public void onActivityCreated(Bundle savedInstanceState) {
if (!onViewCreatedCalled) {
throw new IllegalStateException(
"It seems that onCreateView() has never been called (or has returned null). This means that your fragment is headless (no UI). That is not allowed because it doesn't make sense to use Mosby with a Fragment without View.");
}
}
private boolean retainPresenterInstance(boolean keepPresenterOnBackstack, Activity activity,
Fragment fragment) {
if (activity.isChangingConfigurations()) {
if (keepPresenterDuringScreenOrientationChange) {
return true;
}
return false;
}
if (activity.isFinishing()) {
return false;
}
if (keepPresenterOnBackstack && BackstackAccessor.isFragmentOnBackStack(fragment)) {
return true;
}
return !fragment.isRemoving();
}
@Override public void onDestroyView() {
onViewCreatedCalled = false;
}
@Override public void onStop() {
Activity activity = getActivity();
boolean retainPresenterInstance =
retainPresenterInstance(keepPresenterOnBackstack, activity, fragment);
presenter.detachView(retainPresenterInstance);
if (!retainPresenterInstance
&& mosbyViewId
!= null) { // mosbyViewId == null if keepPresenterDuringScreenOrientationChange == false
PresenterManager.remove(activity, mosbyViewId);
}
if (DEBUG) {
Log.d(DEBUG_TAG, "detached MvpView from Presenter. MvpView "
+ delegateCallback.getMvpView()
+ " Presenter: "
+ presenter);
Log.d(DEBUG_TAG, "Retaining presenter instance: "
+ Boolean.toString(retainPresenterInstance)
+ " "
+ presenter);
}
}
@Override public void onCreate(@Nullable Bundle bundle) {
if ((keepPresenterDuringScreenOrientationChange || keepPresenterOnBackstack)
&& bundle != null) {
mosbyViewId = bundle.getString(KEY_MOSBY_VIEW_ID);
}
if (DEBUG) {
Log.d(DEBUG_TAG,
"MosbyView ID = " + mosbyViewId + " for MvpView: " + delegateCallback.getMvpView());
}
}
@Override public void onDestroy() {
presenter = null;
delegateCallback = null;
fragment = null;
}
@Override public void onPause() {
}
@Override public void onResume() {
}
@NonNull private Activity getActivity() {
Activity activity = fragment.getActivity();
if (activity == null) {
throw new NullPointerException(
"Activity returned by Fragment.getActivity() is null. Fragment is " + fragment);
}
return activity;
}
/**
* Generates the unique (mosby internal) viewState id and calls {@link
* MviDelegateCallback#createPresenter()}
* to create a new presenter instance
*
* @return The new created presenter instance
*/
private P createViewIdAndCreatePresenter() {
P presenter = delegateCallback.createPresenter();
if (presenter == null) {
throw new NullPointerException(
"Presenter returned from createPresenter() is null. Fragment is " + fragment);
}
if (keepPresenterDuringScreenOrientationChange || keepPresenterOnBackstack) {
Activity activity = getActivity();
mosbyViewId = UUID.randomUUID().toString();
PresenterManager.putPresenter(activity, mosbyViewId, presenter);
}
return presenter;
}
@Override public void onSaveInstanceState(Bundle outState) {
if ((keepPresenterDuringScreenOrientationChange || keepPresenterOnBackstack)
&& outState != null) {
outState.putString(KEY_MOSBY_VIEW_ID, mosbyViewId);
if (DEBUG) {
Log.d(DEBUG_TAG, "Saving MosbyViewId into Bundle. ViewId: " + mosbyViewId);
}
}
}
@Override public void onAttach(Activity activity) {
}
@Override public void onDetach() {
}
@Override public void onAttach(Context context) {
}
@Override public void onAttachFragment(Fragment childFragment) {
}
@Override public void onConfigurationChanged(Configuration newConfig) {
}
}
| apache-2.0 |
mmayorivera/jsimpledb | src/test/org/jsimpledb/util/XMLObjectSerializerTest.java | 6702 |
/*
* Copyright (C) 2014 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.jsimpledb.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jsimpledb.TestSupport;
import org.jsimpledb.core.Database;
import org.jsimpledb.core.ObjId;
import org.jsimpledb.core.Transaction;
import org.jsimpledb.kv.KVPair;
import org.jsimpledb.kv.simple.SimpleKVDatabase;
import org.jsimpledb.schema.SchemaModel;
import org.testng.Assert;
import org.testng.annotations.Test;
public class XMLObjectSerializerTest extends TestSupport {
@Test
@SuppressWarnings("unchecked")
public void testXMLObjectSerializer() throws Exception {
final SimpleKVDatabase kvstore = new SimpleKVDatabase();
final Database db = new Database(kvstore);
final SchemaModel schema1 = SchemaModel.fromXML(new ByteArrayInputStream((
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<Schema formatVersion=\"1\">\n"
+ " <ObjectType name=\"Foo\" storageId=\"1\">\n"
+ " <SimpleField name=\"i\" type=\"int\" storageId=\"2\"/>\n"
+ " <SimpleField name=\"z\" type=\"boolean\" storageId=\"3\"/>\n"
+ " <SimpleField name=\"b\" type=\"byte\" storageId=\"4\"/>\n"
+ " <SimpleField name=\"c\" type=\"char\" storageId=\"5\"/>\n"
+ " <SimpleField name=\"s\" type=\"short\" storageId=\"6\"/>\n"
+ " <SimpleField name=\"f\" type=\"float\" storageId=\"7\"/>\n"
+ " <SimpleField name=\"j\" type=\"long\" storageId=\"8\"/>\n"
+ " <SimpleField name=\"d\" type=\"double\" storageId=\"9\"/>\n"
+ " <SimpleField name=\"str\" type=\"java.lang.String\" storageId=\"10\"/>\n"
+ " <ReferenceField name=\"r\" storageId=\"11\"/>\n"
+ " <SimpleField name=\"v\" type=\"java.lang.Void\" storageId=\"12\"/>\n"
+ " <SimpleField name=\"date\" type=\"java.util.Date\" storageId=\"13\"/>\n"
+ " <ReferenceField name=\"r2\" storageId=\"14\"/>\n"
+ " </ObjectType>\n"
+ "</Schema>\n"
).getBytes("UTF-8")));
Transaction tx = db.createTransaction(schema1, 1, true);
ObjId id1 = new ObjId("0100000000000001");
tx.create(id1, 1);
tx.writeSimpleField(id1, 2, 123, false);
tx.writeSimpleField(id1, 3, true, false);
tx.writeSimpleField(id1, 4, (byte)-7, false);
tx.writeSimpleField(id1, 5, '\n', false);
tx.writeSimpleField(id1, 6, (short)0, false); // default value
tx.writeSimpleField(id1, 7, 123.45f, false);
tx.writeSimpleField(id1, 8, 99999999999L, false);
tx.writeSimpleField(id1, 9, 123.45e37, false);
tx.writeSimpleField(id1, 10, "hello dolly", false);
tx.writeSimpleField(id1, 11, id1, false);
tx.writeSimpleField(id1, 12, null, false); // default value
tx.writeSimpleField(id1, 13, new Date(1399604568000L), false);
tx.writeSimpleField(id1, 14, null, false);
XMLObjectSerializer s1 = new XMLObjectSerializer(tx);
final ByteArrayOutputStream buf = new ByteArrayOutputStream();
s1.write(buf, false, true);
this.compareResult(tx, buf.toByteArray(), "test1.xml");
buf.reset();
s1.write(buf, true, true);
this.compareResult(tx, buf.toByteArray(), "test2.xml");
tx.commit();
final SchemaModel schema2 = SchemaModel.fromXML(new ByteArrayInputStream((
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<Schema formatVersion=\"1\">\n"
+ " <ObjectType name=\"Foo\" storageId=\"20\">\n"
+ " <SetField name=\"set\" storageId=\"21\">\n"
+ " <SimpleField type=\"int\" storageId=\"22\"/>\n"
+ " </SetField>"
+ " <ListField name=\"list\" storageId=\"23\">\n"
+ " <SimpleField type=\"java.lang.Integer\" storageId=\"24\"/>\n"
+ " </ListField>"
+ " <MapField name=\"map\" storageId=\"25\">\n"
+ " <SimpleField type=\"int\" storageId=\"26\"/>\n"
+ " <SimpleField type=\"java.lang.String\" storageId=\"27\" indexed=\"true\"/>\n"
+ " </MapField>"
+ " <ListField name=\"list2\" storageId=\"28\">\n"
+ " <ReferenceField storageId=\"29\"/>\n"
+ " </ListField>"
+ " </ObjectType>\n"
+ "</Schema>\n"
).getBytes("UTF-8")));
tx = db.createTransaction(schema2, 2, true);
ObjId id2 = new ObjId("1400000000000001");
tx.create(id2, 2);
Set<Integer> set = (Set<Integer>)tx.readSetField(id2, 21, false);
set.add(123);
set.add(456);
List<Integer> list = (List<Integer>)tx.readListField(id2, 23, false);
list.add(789);
list.add(null);
list.add(101112);
Map<Integer, String> map = (Map<Integer, String>)tx.readMapField(id2, 25, false);
map.put(55, "fifty\nfive");
map.put(73, "seventy three");
map.put(99, null);
XMLObjectSerializer s2 = new XMLObjectSerializer(tx);
buf.reset();
s2.write(buf, false, true);
this.compareResult(tx, buf.toByteArray(), "test3.xml");
buf.reset();
s2.write(buf, true, true);
this.compareResult(tx, buf.toByteArray(), "test4.xml");
tx.commit();
}
private void compareResult(Transaction tx, byte[] buf, String resource) throws Exception {
// Read file
String text = this.readResource(this.getClass().getResource(resource)).trim();
// Compare generated XML to expected
this.log.info("verifying XML output with \"" + resource + "\"");
Assert.assertEquals(new String(buf, "UTF-8"), text);
// Parse XML back into a snapshot transaction
final Transaction stx = tx.createSnapshotTransaction();
XMLObjectSerializer s = new XMLObjectSerializer(stx);
s.read(new ByteArrayInputStream(text.getBytes("UTF-8")));
// Compare transaction KV stores
final Iterator<KVPair> i1 = tx.getKVTransaction().getRange(null, null, false);
final Iterator<KVPair> i2 = stx.getKVTransaction().getRange(null, null, false);
while (i1.hasNext() && i2.hasNext()) {
final KVPair p1 = i1.next();
final KVPair p2 = i2.next();
Assert.assertEquals(p1.toString(), p2.toString());
}
Assert.assertTrue(!i1.hasNext());
Assert.assertTrue(!i2.hasNext());
}
}
| apache-2.0 |
apache/velocity-tools | velocity-tools-generic/src/main/java/org/apache/velocity/tools/generic/ContextTool.java | 6309 | package org.apache.velocity.tools.generic;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.velocity.context.AbstractContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.ToolContext;
import org.apache.velocity.tools.config.DefaultKey;
import org.apache.velocity.tools.config.InvalidScope;
import org.apache.velocity.tools.generic.ValueParser;
/**
* <p>Tool for convenient access to {@link Context} data and
* meta-data.</p>
* <p>Template example(s):</p>
* <pre>
* #foreach( $key in $context.keys )
* $key = $context.get($key)
* #end
*
* Toolbox configuration:
* <tools>
* <toolbox scope="request">
* <tool class="org.apache.velocity.tools.generic.ContextTool"/>
* </toolbox>
* </tools>
* </pre>
*
* <p>This class is only designed for use as a request-scope tool.</p>
*
* @author Nathan Bubna
* @since VelocityTools 2.0
* @version $Id: ContextTool.java 385122 2006-03-11 18:37:42Z nbubna $
*/
@DefaultKey("context")
@InvalidScope({Scope.APPLICATION,Scope.SESSION})
public class ContextTool extends SafeConfig implements Serializable
{
private static final long serialVersionUID = 2214413657621101511L;
protected Context context;
protected Map<String,Object> toolbox;
/**
* Initializes this instance for the current request.
* Also looks for a safe-mode configuration setting. By default,
* safeMode is true and thus keys with '.' in them are hidden.
*/
protected void configure(ValueParser parser)
{
this.context = (Context)parser.getValue(ToolContext.CONTEXT_KEY);
}
/**
* Returns the context being analyzed by this tool.
* @return analyzed context
*/
public Context getThis()
{
return this.context;
}
/**
* <p>Returns a read-only view of the toolbox {@link Map}
* for this context.</p>
* @return a map of all available tools for this request
* or {@code null} if such a map is not available
*/
public Map<String,Object> getToolbox()
{
if (this.toolbox == null && this.context instanceof ToolContext)
{
this.toolbox = ((ToolContext)context).getToolbox();
}
return this.toolbox;
}
/**
* <p>Return a {@link Set} of the available reference keys in the current
* context.</p>
* @return keys set
*/
public Set getKeys()
{
Set keys = new HashSet();
// fill the keyset in extendable method
fillKeyset(keys);
// if we're in safe mode, remove keys that contain '.'
if (isSafeMode())
{
for (Iterator i = keys.iterator(); i.hasNext(); )
{
String key = String.valueOf(i.next());
if (key.indexOf('.') >= 0)
{
i.remove();
}
}
}
// return the key set
return keys;
}
/**
* Actually do the work of filling in the set of keys
* for {@link #getKeys} here so subclasses can add keys too.
* @param keys set to fill with keys
*/
protected void fillKeyset(Set keys)
{
//NOTE: we don't need to manually add the toolbox keys here
// because retrieval of those depends on the context being
// a ToolContext which would already give tool keys below
// recurse down the velocity context collecting keys
Context velctx = this.context;
while (velctx != null)
{
Object[] ctxKeys = velctx.getKeys();
keys.addAll(Arrays.asList(ctxKeys));
if (velctx instanceof AbstractContext)
{
velctx = ((AbstractContext)velctx).getChainedContext();
}
else
{
velctx = null;
}
}
}
/**
* <p>Return a {@link Set} of the available values in the current
* context.</p>
* @return values set
*/
public Set getValues()
{
//TODO: this could be a lot more efficient
Set keys = getKeys();
Set values = new HashSet(keys.size());
for (Iterator i = keys.iterator(); i.hasNext(); )
{
String key = String.valueOf(i.next());
values.add(this.context.get(key));
}
return values;
}
/**
* <p>Returns {@code true} if the context contains a value for the specified
* reference name (aka context key).</p>
* @param refName context key
* @return <code>true</code> if key is present in the context
*/
public boolean contains(Object refName)
{
return (get(refName) != null);
}
/**
* Retrieves the value for the specified reference name (aka context key).
* @param refName context key
* @return found value, or null
*/
public Object get(Object refName)
{
String key = String.valueOf(refName);
if (isSafeMode() && key.indexOf('.') >= 0)
{
return null;
}
return this.context.get(key);
}
}
| apache-2.0 |
zhuyuanyan/PCCredit_TY | src/java/com/cardpay/pccredit/customer/filter/MaintenanceFilter.java | 3045 | /**
*
*/
package com.cardpay.pccredit.customer.filter;
import java.util.List;
import com.cardpay.pccredit.manager.web.AccountManagerParameterForm;
import com.wicresoft.jrad.base.web.filter.BaseQueryFilter;
/**
* @author shaoming
*
* 2014年11月11日 下午3:03:58
*/
public class MaintenanceFilter extends BaseQueryFilter{
private String id;
private String customerId;
private String customerManagerId;
private List<AccountManagerParameterForm> customerManagerIds;
private String maintenanceGoal;
private String maintenanceWay;
private String maintenanceDay;
private String createWay;
private String endResult;
private String remarksCreateReason;
private String cardId;
private String customerName;
private String productId;
private String appId;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCustomerManagerId() {
return customerManagerId;
}
public void setCustomerManagerId(String customerManagerId) {
this.customerManagerId = customerManagerId;
}
public String getMaintenanceGoal() {
return maintenanceGoal;
}
public void setMaintenanceGoal(String maintenanceGoal) {
this.maintenanceGoal = maintenanceGoal;
}
public String getMaintenanceWay() {
return maintenanceWay;
}
public void setMaintenanceWay(String maintenanceWay) {
this.maintenanceWay = maintenanceWay;
}
public String getMaintenanceDay() {
return maintenanceDay;
}
public void setMaintenanceDay(String maintenanceDay) {
this.maintenanceDay = maintenanceDay;
}
public String getCreateWay() {
return createWay;
}
public void setCreateWay(String createWay) {
this.createWay = createWay;
}
public String getEndResult() {
return endResult;
}
public void setEndResult(String endResult) {
this.endResult = endResult;
}
public String getRemarksCreateReason() {
return remarksCreateReason;
}
public void setRemarksCreateReason(String remarksCreateReason) {
this.remarksCreateReason = remarksCreateReason;
}
public List<AccountManagerParameterForm> getCustomerManagerIds() {
return customerManagerIds;
}
public void setCustomerManagerIds(
List<AccountManagerParameterForm> customerManagerIds) {
this.customerManagerIds = customerManagerIds;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
}
| apache-2.0 |
apache/clerezza | jaxrs.rdf.providers/src/main/java/org/apache/clerezza/jaxrs/sparql/providers/ResultSetJsonMessageBodyWriter.java | 5903 | /*
* 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.clerezza.jaxrs.sparql.providers;
import org.apache.clerezza.*;
import org.apache.clerezza.sparql.ResultSet;
import org.apache.clerezza.sparql.SolutionMapping;
import org.apache.clerezza.sparql.query.Variable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;
/**
* MessageBodyWirter for <code>ResultSet</code>.
* Resulting output conforms to:
* http://www.w3.org/TR/2007/NOTE-rdf-sparql-json-res-20070618/
*
* @author misl
*/
@Component(service = Object.class, property = {"javax.ws.rs=true"})
@Produces({"application/json", "application/sparql-results+json"})
@Provider
@SuppressWarnings("unchecked")
public class ResultSetJsonMessageBodyWriter implements MessageBodyWriter<ResultSet> {
final Logger logger = LoggerFactory.getLogger(ResultSetJsonMessageBodyWriter.class);
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType) {
return ResultSet.class.isAssignableFrom(type);
}
@Override
public long getSize(ResultSet t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(ResultSet resultSet, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType, MultivaluedMap<String,
Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
JSONObject json = toJsonSource(resultSet);
entityStream.write(json.toJSONString().getBytes("UTF-8"));
}
/**
* Helper: transforms a {@link ResultSet} or a {@link Boolean} to a
* json object.
*
* @param queryResult
*/
private JSONObject toJsonSource(ResultSet queryResult) {
JSONObject root = new JSONObject();
JSONObject head = new JSONObject();
root.put("head", head);
createVariables(queryResult.getResultVars(), head);
JSONObject results = new JSONObject();
root.put("results", results);
JSONArray bindings = null;
while (queryResult.hasNext()) {
if (bindings == null) {
bindings = new JSONArray();
results.put("bindings", bindings);
}
bindings.add(createResult(queryResult.next()));
}
return root;
}
/**
* Helper: creates value element from {@link RDFTerm} depending on its
* class
*/
private JSONObject createResultElement(RDFTerm resource) {
JSONObject element = new JSONObject();
if (resource instanceof IRI) {
element.put("type", "uri");
element.put("value", IRI.class.cast(resource).getUnicodeString());
} else if (resource instanceof Literal) {
element.put("type", "literal");
element.put("value", Literal.class.cast(resource).getLexicalForm());
Language lang = Literal.class.cast(resource).getLanguage();
if (lang != null) {
element.put("xml:lang", lang.toString());
}
} else if (resource instanceof Literal) {
element.put("type", "typed-literal");
element.put("datatype", Literal.class.cast(resource).getDataType().getUnicodeString());
element.put("value", Literal.class.cast(resource).getLexicalForm());
} else if (resource instanceof BlankNode) {
element.put("type", "bnode");
element.put("value", "/");
} else {
element = null;
}
return element;
}
/**
* Helper: creates results element from ResultSet
*/
private JSONObject createResult(SolutionMapping solutionMap) {
JSONObject result = new JSONObject();
Set<Variable> keys = solutionMap.keySet();
for (Variable key : keys) {
result.put(key.getName(), createResultElement((RDFTerm) solutionMap.get(key)));
}
return result;
}
private void createVariables(List<String> variables, JSONObject head) {
JSONArray vars = null;
for (String variable : variables) {
if (vars == null) {
vars = new JSONArray();
head.put("vars", vars);
}
vars.add(variable);
}
}
}
| apache-2.0 |
xiaoyuQi/JavaProject | dubbo-admin/src/main/java/com/alibaba/dubbo/registry/common/util/Entities.java | 41909 | /*
* 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.alibaba.dubbo.registry.common.util;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* <p>
* Provides HTML and XML entity utilities.
* </p>
*
* @see <a href="http://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a>
* @see <a href="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a>
* @see <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a>
* @see <a href="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a>
* @see <a href="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a>
*
* @author <a href="mailto:alex@purpletech.com">Alexander Day Chaffee</a>
* @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
* @since 2.0
* @version $Id: Entities.java 181192 2012-06-21 05:05:47Z tony.chenl $
*/
class Entities {
private static final String[][] BASIC_ARRAY = {{"quot", "34"}, // " - double-quote
{"amp", "38"}, // & - ampersand
{"lt", "60"}, // < - less-than
{"gt", "62"}, // > - greater-than
};
private static final String[][] APOS_ARRAY = {{"apos", "39"}, // XML apostrophe
};
// package scoped for testing
static final String[][] ISO8859_1_ARRAY = {{"nbsp", "160"}, // non-breaking space
{"iexcl", "161"}, // inverted exclamation mark
{"cent", "162"}, // cent sign
{"pound", "163"}, // pound sign
{"curren", "164"}, // currency sign
{"yen", "165"}, // yen sign = yuan sign
{"brvbar", "166"}, // broken bar = broken vertical bar
{"sect", "167"}, // section sign
{"uml", "168"}, // diaeresis = spacing diaeresis
{"copy", "169"}, // � - copyright sign
{"ordf", "170"}, // feminine ordinal indicator
{"laquo", "171"}, // left-pointing double angle quotation mark = left pointing guillemet
{"not", "172"}, // not sign
{"shy", "173"}, // soft hyphen = discretionary hyphen
{"reg", "174"}, // � - registered trademark sign
{"macr", "175"}, // macron = spacing macron = overline = APL overbar
{"deg", "176"}, // degree sign
{"plusmn", "177"}, // plus-minus sign = plus-or-minus sign
{"sup2", "178"}, // superscript two = superscript digit two = squared
{"sup3", "179"}, // superscript three = superscript digit three = cubed
{"acute", "180"}, // acute accent = spacing acute
{"micro", "181"}, // micro sign
{"para", "182"}, // pilcrow sign = paragraph sign
{"middot", "183"}, // middle dot = Georgian comma = Greek middle dot
{"cedil", "184"}, // cedilla = spacing cedilla
{"sup1", "185"}, // superscript one = superscript digit one
{"ordm", "186"}, // masculine ordinal indicator
{"raquo", "187"}, // right-pointing double angle quotation mark = right pointing guillemet
{"frac14", "188"}, // vulgar fraction one quarter = fraction one quarter
{"frac12", "189"}, // vulgar fraction one half = fraction one half
{"frac34", "190"}, // vulgar fraction three quarters = fraction three quarters
{"iquest", "191"}, // inverted question mark = turned question mark
{"Agrave", "192"}, // � - uppercase A, grave accent
{"Aacute", "193"}, // � - uppercase A, acute accent
{"Acirc", "194"}, // � - uppercase A, circumflex accent
{"Atilde", "195"}, // � - uppercase A, tilde
{"Auml", "196"}, // � - uppercase A, umlaut
{"Aring", "197"}, // � - uppercase A, ring
{"AElig", "198"}, // � - uppercase AE
{"Ccedil", "199"}, // � - uppercase C, cedilla
{"Egrave", "200"}, // � - uppercase E, grave accent
{"Eacute", "201"}, // � - uppercase E, acute accent
{"Ecirc", "202"}, // � - uppercase E, circumflex accent
{"Euml", "203"}, // � - uppercase E, umlaut
{"Igrave", "204"}, // � - uppercase I, grave accent
{"Iacute", "205"}, // � - uppercase I, acute accent
{"Icirc", "206"}, // � - uppercase I, circumflex accent
{"Iuml", "207"}, // � - uppercase I, umlaut
{"ETH", "208"}, // � - uppercase Eth, Icelandic
{"Ntilde", "209"}, // � - uppercase N, tilde
{"Ograve", "210"}, // � - uppercase O, grave accent
{"Oacute", "211"}, // � - uppercase O, acute accent
{"Ocirc", "212"}, // � - uppercase O, circumflex accent
{"Otilde", "213"}, // � - uppercase O, tilde
{"Ouml", "214"}, // � - uppercase O, umlaut
{"times", "215"}, // multiplication sign
{"Oslash", "216"}, // � - uppercase O, slash
{"Ugrave", "217"}, // � - uppercase U, grave accent
{"Uacute", "218"}, // � - uppercase U, acute accent
{"Ucirc", "219"}, // � - uppercase U, circumflex accent
{"Uuml", "220"}, // � - uppercase U, umlaut
{"Yacute", "221"}, // � - uppercase Y, acute accent
{"THORN", "222"}, // � - uppercase THORN, Icelandic
{"szlig", "223"}, // � - lowercase sharps, German
{"agrave", "224"}, // � - lowercase a, grave accent
{"aacute", "225"}, // � - lowercase a, acute accent
{"acirc", "226"}, // � - lowercase a, circumflex accent
{"atilde", "227"}, // � - lowercase a, tilde
{"auml", "228"}, // � - lowercase a, umlaut
{"aring", "229"}, // � - lowercase a, ring
{"aelig", "230"}, // � - lowercase ae
{"ccedil", "231"}, // � - lowercase c, cedilla
{"egrave", "232"}, // � - lowercase e, grave accent
{"eacute", "233"}, // � - lowercase e, acute accent
{"ecirc", "234"}, // � - lowercase e, circumflex accent
{"euml", "235"}, // � - lowercase e, umlaut
{"igrave", "236"}, // � - lowercase i, grave accent
{"iacute", "237"}, // � - lowercase i, acute accent
{"icirc", "238"}, // � - lowercase i, circumflex accent
{"iuml", "239"}, // � - lowercase i, umlaut
{"eth", "240"}, // � - lowercase eth, Icelandic
{"ntilde", "241"}, // � - lowercase n, tilde
{"ograve", "242"}, // � - lowercase o, grave accent
{"oacute", "243"}, // � - lowercase o, acute accent
{"ocirc", "244"}, // � - lowercase o, circumflex accent
{"otilde", "245"}, // � - lowercase o, tilde
{"ouml", "246"}, // � - lowercase o, umlaut
{"divide", "247"}, // division sign
{"oslash", "248"}, // � - lowercase o, slash
{"ugrave", "249"}, // � - lowercase u, grave accent
{"uacute", "250"}, // � - lowercase u, acute accent
{"ucirc", "251"}, // � - lowercase u, circumflex accent
{"uuml", "252"}, // � - lowercase u, umlaut
{"yacute", "253"}, // � - lowercase y, acute accent
{"thorn", "254"}, // � - lowercase thorn, Icelandic
{"yuml", "255"}, // � - lowercase y, umlaut
};
// http://www.w3.org/TR/REC-html40/sgml/entities.html
// package scoped for testing
static final String[][] HTML40_ARRAY = {
// <!-- Latin Extended-B -->
{"fnof", "402"}, // latin small f with hook = function= florin, U+0192 ISOtech -->
// <!-- Greek -->
{"Alpha", "913"}, // greek capital letter alpha, U+0391 -->
{"Beta", "914"}, // greek capital letter beta, U+0392 -->
{"Gamma", "915"}, // greek capital letter gamma,U+0393 ISOgrk3 -->
{"Delta", "916"}, // greek capital letter delta,U+0394 ISOgrk3 -->
{"Epsilon", "917"}, // greek capital letter epsilon, U+0395 -->
{"Zeta", "918"}, // greek capital letter zeta, U+0396 -->
{"Eta", "919"}, // greek capital letter eta, U+0397 -->
{"Theta", "920"}, // greek capital letter theta,U+0398 ISOgrk3 -->
{"Iota", "921"}, // greek capital letter iota, U+0399 -->
{"Kappa", "922"}, // greek capital letter kappa, U+039A -->
{"Lambda", "923"}, // greek capital letter lambda,U+039B ISOgrk3 -->
{"Mu", "924"}, // greek capital letter mu, U+039C -->
{"Nu", "925"}, // greek capital letter nu, U+039D -->
{"Xi", "926"}, // greek capital letter xi, U+039E ISOgrk3 -->
{"Omicron", "927"}, // greek capital letter omicron, U+039F -->
{"Pi", "928"}, // greek capital letter pi, U+03A0 ISOgrk3 -->
{"Rho", "929"}, // greek capital letter rho, U+03A1 -->
// <!-- there is no Sigmaf, and no U+03A2 character either -->
{"Sigma", "931"}, // greek capital letter sigma,U+03A3 ISOgrk3 -->
{"Tau", "932"}, // greek capital letter tau, U+03A4 -->
{"Upsilon", "933"}, // greek capital letter upsilon,U+03A5 ISOgrk3 -->
{"Phi", "934"}, // greek capital letter phi,U+03A6 ISOgrk3 -->
{"Chi", "935"}, // greek capital letter chi, U+03A7 -->
{"Psi", "936"}, // greek capital letter psi,U+03A8 ISOgrk3 -->
{"Omega", "937"}, // greek capital letter omega,U+03A9 ISOgrk3 -->
{"alpha", "945"}, // greek small letter alpha,U+03B1 ISOgrk3 -->
{"beta", "946"}, // greek small letter beta, U+03B2 ISOgrk3 -->
{"gamma", "947"}, // greek small letter gamma,U+03B3 ISOgrk3 -->
{"delta", "948"}, // greek small letter delta,U+03B4 ISOgrk3 -->
{"epsilon", "949"}, // greek small letter epsilon,U+03B5 ISOgrk3 -->
{"zeta", "950"}, // greek small letter zeta, U+03B6 ISOgrk3 -->
{"eta", "951"}, // greek small letter eta, U+03B7 ISOgrk3 -->
{"theta", "952"}, // greek small letter theta,U+03B8 ISOgrk3 -->
{"iota", "953"}, // greek small letter iota, U+03B9 ISOgrk3 -->
{"kappa", "954"}, // greek small letter kappa,U+03BA ISOgrk3 -->
{"lambda", "955"}, // greek small letter lambda,U+03BB ISOgrk3 -->
{"mu", "956"}, // greek small letter mu, U+03BC ISOgrk3 -->
{"nu", "957"}, // greek small letter nu, U+03BD ISOgrk3 -->
{"xi", "958"}, // greek small letter xi, U+03BE ISOgrk3 -->
{"omicron", "959"}, // greek small letter omicron, U+03BF NEW -->
{"pi", "960"}, // greek small letter pi, U+03C0 ISOgrk3 -->
{"rho", "961"}, // greek small letter rho, U+03C1 ISOgrk3 -->
{"sigmaf", "962"}, // greek small letter final sigma,U+03C2 ISOgrk3 -->
{"sigma", "963"}, // greek small letter sigma,U+03C3 ISOgrk3 -->
{"tau", "964"}, // greek small letter tau, U+03C4 ISOgrk3 -->
{"upsilon", "965"}, // greek small letter upsilon,U+03C5 ISOgrk3 -->
{"phi", "966"}, // greek small letter phi, U+03C6 ISOgrk3 -->
{"chi", "967"}, // greek small letter chi, U+03C7 ISOgrk3 -->
{"psi", "968"}, // greek small letter psi, U+03C8 ISOgrk3 -->
{"omega", "969"}, // greek small letter omega,U+03C9 ISOgrk3 -->
{"thetasym", "977"}, // greek small letter theta symbol,U+03D1 NEW -->
{"upsih", "978"}, // greek upsilon with hook symbol,U+03D2 NEW -->
{"piv", "982"}, // greek pi symbol, U+03D6 ISOgrk3 -->
// <!-- General Punctuation -->
{"bull", "8226"}, // bullet = black small circle,U+2022 ISOpub -->
// <!-- bullet is NOT the same as bullet operator, U+2219 -->
{"hellip", "8230"}, // horizontal ellipsis = three dot leader,U+2026 ISOpub -->
{"prime", "8242"}, // prime = minutes = feet, U+2032 ISOtech -->
{"Prime", "8243"}, // double prime = seconds = inches,U+2033 ISOtech -->
{"oline", "8254"}, // overline = spacing overscore,U+203E NEW -->
{"frasl", "8260"}, // fraction slash, U+2044 NEW -->
// <!-- Letterlike Symbols -->
{"weierp", "8472"}, // script capital P = power set= Weierstrass p, U+2118 ISOamso -->
{"image", "8465"}, // blackletter capital I = imaginary part,U+2111 ISOamso -->
{"real", "8476"}, // blackletter capital R = real part symbol,U+211C ISOamso -->
{"trade", "8482"}, // trade mark sign, U+2122 ISOnum -->
{"alefsym", "8501"}, // alef symbol = first transfinite cardinal,U+2135 NEW -->
// <!-- alef symbol is NOT the same as hebrew letter alef,U+05D0 although the
// same glyph could be used to depict both characters -->
// <!-- Arrows -->
{"larr", "8592"}, // leftwards arrow, U+2190 ISOnum -->
{"uarr", "8593"}, // upwards arrow, U+2191 ISOnum-->
{"rarr", "8594"}, // rightwards arrow, U+2192 ISOnum -->
{"darr", "8595"}, // downwards arrow, U+2193 ISOnum -->
{"harr", "8596"}, // left right arrow, U+2194 ISOamsa -->
{"crarr", "8629"}, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW -->
{"lArr", "8656"}, // leftwards double arrow, U+21D0 ISOtech -->
// <!-- ISO 10646 does not say that lArr is the same as the 'is implied by'
// arrow but also does not have any other character for that function.
// So ? lArr canbe used for 'is implied by' as ISOtech suggests -->
{"uArr", "8657"}, // upwards double arrow, U+21D1 ISOamsa -->
{"rArr", "8658"}, // rightwards double arrow,U+21D2 ISOtech -->
// <!-- ISO 10646 does not say this is the 'implies' character but does not
// have another character with this function so ?rArr can be used for
// 'implies' as ISOtech suggests -->
{"dArr", "8659"}, // downwards double arrow, U+21D3 ISOamsa -->
{"hArr", "8660"}, // left right double arrow,U+21D4 ISOamsa -->
// <!-- Mathematical Operators -->
{"forall", "8704"}, // for all, U+2200 ISOtech -->
{"part", "8706"}, // partial differential, U+2202 ISOtech -->
{"exist", "8707"}, // there exists, U+2203 ISOtech -->
{"empty", "8709"}, // empty set = null set = diameter,U+2205 ISOamso -->
{"nabla", "8711"}, // nabla = backward difference,U+2207 ISOtech -->
{"isin", "8712"}, // element of, U+2208 ISOtech -->
{"notin", "8713"}, // not an element of, U+2209 ISOtech -->
{"ni", "8715"}, // contains as member, U+220B ISOtech -->
// <!-- should there be a more memorable name than 'ni'? -->
{"prod", "8719"}, // n-ary product = product sign,U+220F ISOamsb -->
// <!-- prod is NOT the same character as U+03A0 'greek capital letter pi'
// though the same glyph might be used for both -->
{"sum", "8721"}, // n-ary summation, U+2211 ISOamsb -->
// <!-- sum is NOT the same character as U+03A3 'greek capital letter sigma'
// though the same glyph might be used for both -->
{"minus", "8722"}, // minus sign, U+2212 ISOtech -->
{"lowast", "8727"}, // asterisk operator, U+2217 ISOtech -->
{"radic", "8730"}, // square root = radical sign,U+221A ISOtech -->
{"prop", "8733"}, // proportional to, U+221D ISOtech -->
{"infin", "8734"}, // infinity, U+221E ISOtech -->
{"ang", "8736"}, // angle, U+2220 ISOamso -->
{"and", "8743"}, // logical and = wedge, U+2227 ISOtech -->
{"or", "8744"}, // logical or = vee, U+2228 ISOtech -->
{"cap", "8745"}, // intersection = cap, U+2229 ISOtech -->
{"cup", "8746"}, // union = cup, U+222A ISOtech -->
{"int", "8747"}, // integral, U+222B ISOtech -->
{"there4", "8756"}, // therefore, U+2234 ISOtech -->
{"sim", "8764"}, // tilde operator = varies with = similar to,U+223C ISOtech -->
// <!-- tilde operator is NOT the same character as the tilde, U+007E,although
// the same glyph might be used to represent both -->
{"cong", "8773"}, // approximately equal to, U+2245 ISOtech -->
{"asymp", "8776"}, // almost equal to = asymptotic to,U+2248 ISOamsr -->
{"ne", "8800"}, // not equal to, U+2260 ISOtech -->
{"equiv", "8801"}, // identical to, U+2261 ISOtech -->
{"le", "8804"}, // less-than or equal to, U+2264 ISOtech -->
{"ge", "8805"}, // greater-than or equal to,U+2265 ISOtech -->
{"sub", "8834"}, // subset of, U+2282 ISOtech -->
{"sup", "8835"}, // superset of, U+2283 ISOtech -->
// <!-- note that nsup, 'not a superset of, U+2283' is not covered by the
// Symbol font encoding and is not included. Should it be, for symmetry?
// It is in ISOamsn --> <!ENTITY nsub", "8836"},
// not a subset of, U+2284 ISOamsn -->
{"sube", "8838"}, // subset of or equal to, U+2286 ISOtech -->
{"supe", "8839"}, // superset of or equal to,U+2287 ISOtech -->
{"oplus", "8853"}, // circled plus = direct sum,U+2295 ISOamsb -->
{"otimes", "8855"}, // circled times = vector product,U+2297 ISOamsb -->
{"perp", "8869"}, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech -->
{"sdot", "8901"}, // dot operator, U+22C5 ISOamsb -->
// <!-- dot operator is NOT the same character as U+00B7 middle dot -->
// <!-- Miscellaneous Technical -->
{"lceil", "8968"}, // left ceiling = apl upstile,U+2308 ISOamsc -->
{"rceil", "8969"}, // right ceiling, U+2309 ISOamsc -->
{"lfloor", "8970"}, // left floor = apl downstile,U+230A ISOamsc -->
{"rfloor", "8971"}, // right floor, U+230B ISOamsc -->
{"lang", "9001"}, // left-pointing angle bracket = bra,U+2329 ISOtech -->
// <!-- lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation
// mark' -->
{"rang", "9002"}, // right-pointing angle bracket = ket,U+232A ISOtech -->
// <!-- rang is NOT the same character as U+003E 'greater than' or U+203A
// 'single right-pointing angle quotation mark' -->
// <!-- Geometric Shapes -->
{"loz", "9674"}, // lozenge, U+25CA ISOpub -->
// <!-- Miscellaneous Symbols -->
{"spades", "9824"}, // black spade suit, U+2660 ISOpub -->
// <!-- black here seems to mean filled as opposed to hollow -->
{"clubs", "9827"}, // black club suit = shamrock,U+2663 ISOpub -->
{"hearts", "9829"}, // black heart suit = valentine,U+2665 ISOpub -->
{"diams", "9830"}, // black diamond suit, U+2666 ISOpub -->
// <!-- Latin Extended-A -->
{"OElig", "338"}, // -- latin capital ligature OE,U+0152 ISOlat2 -->
{"oelig", "339"}, // -- latin small ligature oe, U+0153 ISOlat2 -->
// <!-- ligature is a misnomer, this is a separate character in some languages -->
{"Scaron", "352"}, // -- latin capital letter S with caron,U+0160 ISOlat2 -->
{"scaron", "353"}, // -- latin small letter s with caron,U+0161 ISOlat2 -->
{"Yuml", "376"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 -->
// <!-- Spacing Modifier Letters -->
{"circ", "710"}, // -- modifier letter circumflex accent,U+02C6 ISOpub -->
{"tilde", "732"}, // small tilde, U+02DC ISOdia -->
// <!-- General Punctuation -->
{"ensp", "8194"}, // en space, U+2002 ISOpub -->
{"emsp", "8195"}, // em space, U+2003 ISOpub -->
{"thinsp", "8201"}, // thin space, U+2009 ISOpub -->
{"zwnj", "8204"}, // zero width non-joiner,U+200C NEW RFC 2070 -->
{"zwj", "8205"}, // zero width joiner, U+200D NEW RFC 2070 -->
{"lrm", "8206"}, // left-to-right mark, U+200E NEW RFC 2070 -->
{"rlm", "8207"}, // right-to-left mark, U+200F NEW RFC 2070 -->
{"ndash", "8211"}, // en dash, U+2013 ISOpub -->
{"mdash", "8212"}, // em dash, U+2014 ISOpub -->
{"lsquo", "8216"}, // left single quotation mark,U+2018 ISOnum -->
{"rsquo", "8217"}, // right single quotation mark,U+2019 ISOnum -->
{"sbquo", "8218"}, // single low-9 quotation mark, U+201A NEW -->
{"ldquo", "8220"}, // left double quotation mark,U+201C ISOnum -->
{"rdquo", "8221"}, // right double quotation mark,U+201D ISOnum -->
{"bdquo", "8222"}, // double low-9 quotation mark, U+201E NEW -->
{"dagger", "8224"}, // dagger, U+2020 ISOpub -->
{"Dagger", "8225"}, // double dagger, U+2021 ISOpub -->
{"permil", "8240"}, // per mille sign, U+2030 ISOtech -->
{"lsaquo", "8249"}, // single left-pointing angle quotation mark,U+2039 ISO proposed -->
// <!-- lsaquo is proposed but not yet ISO standardized -->
{"rsaquo", "8250"}, // single right-pointing angle quotation mark,U+203A ISO proposed -->
// <!-- rsaquo is proposed but not yet ISO standardized -->
{"euro", "8364"}, // -- euro sign, U+20AC NEW -->
};
/**
* <p>
* The set of entities supported by standard XML.
* </p>
*/
public static final Entities XML;
/**
* <p>
* The set of entities supported by HTML 3.2.
* </p>
*/
public static final Entities HTML32;
/**
* <p>
* The set of entities supported by HTML 4.0.
* </p>
*/
public static final Entities HTML40;
static {
XML = new Entities();
XML.addEntities(BASIC_ARRAY);
XML.addEntities(APOS_ARRAY);
}
static {
HTML32 = new Entities();
HTML32.addEntities(BASIC_ARRAY);
HTML32.addEntities(ISO8859_1_ARRAY);
}
static {
HTML40 = new Entities();
fillWithHtml40Entities(HTML40);
}
/**
* <p>
* Fills the specified entities instance with HTML 40 entities.
* </p>
*
* @param entities
* the instance to be filled.
*/
static void fillWithHtml40Entities(Entities entities) {
entities.addEntities(BASIC_ARRAY);
entities.addEntities(ISO8859_1_ARRAY);
entities.addEntities(HTML40_ARRAY);
}
static interface EntityMap {
/**
* <p>
* Add an entry to this entity map.
* </p>
*
* @param name
* the entity name
* @param value
* the entity value
*/
void add(String name, int value);
/**
* <p>
* Returns the name of the entity identified by the specified value.
* </p>
*
* @param value
* the value to locate
* @return entity name associated with the specified value
*/
String name(int value);
/**
* <p>
* Returns the value of the entity identified by the specified name.
* </p>
*
* @param name
* the name to locate
* @return entity value associated with the specified name
*/
int value(String name);
}
static class PrimitiveEntityMap implements EntityMap {
private Map mapNameToValue = new HashMap();
private IntHashMap mapValueToName = new IntHashMap();
/**
* {@inheritDoc}
*/
public void add(String name, int value) {
mapNameToValue.put(name, Integer.valueOf(value));
mapValueToName.put(value, name);
}
/**
* {@inheritDoc}
*/
public String name(int value) {
return (String) mapValueToName.get(value);
}
/**
* {@inheritDoc}
*/
public int value(String name) {
Object value = mapNameToValue.get(name);
if (value == null) {
return -1;
}
return ((Integer) value).intValue();
}
}
static abstract class MapIntMap implements Entities.EntityMap {
protected Map mapNameToValue;
protected Map mapValueToName;
/**
* {@inheritDoc}
*/
public void add(String name, int value) {
mapNameToValue.put(name, Integer.valueOf(value));
mapValueToName.put(Integer.valueOf(value), name);
}
/**
* {@inheritDoc}
*/
public String name(int value) {
return (String) mapValueToName.get(Integer.valueOf(value));
}
/**
* {@inheritDoc}
*/
public int value(String name) {
Object value = mapNameToValue.get(name);
if (value == null) {
return -1;
}
return ((Integer) value).intValue();
}
}
static class HashEntityMap extends MapIntMap {
/**
* Constructs a new instance of <code>HashEntityMap</code>.
*/
public HashEntityMap() {
mapNameToValue = new HashMap();
mapValueToName = new HashMap();
}
}
static class TreeEntityMap extends MapIntMap {
/**
* Constructs a new instance of <code>TreeEntityMap</code>.
*/
public TreeEntityMap() {
mapNameToValue = new TreeMap();
mapValueToName = new TreeMap();
}
}
static class LookupEntityMap extends PrimitiveEntityMap {
private String[] lookupTable;
private int LOOKUP_TABLE_SIZE = 256;
/**
* {@inheritDoc}
*/
public String name(int value) {
if (value < LOOKUP_TABLE_SIZE) {
return lookupTable()[value];
}
return super.name(value);
}
/**
* <p>
* Returns the lookup table for this entity map. The lookup table is created if it has not been previously.
* </p>
*
* @return the lookup table
*/
private String[] lookupTable() {
if (lookupTable == null) {
createLookupTable();
}
return lookupTable;
}
/**
* <p>
* Creates an entity lookup table of LOOKUP_TABLE_SIZE elements, initialized with entity names.
* </p>
*/
private void createLookupTable() {
lookupTable = new String[LOOKUP_TABLE_SIZE];
for (int i = 0; i < LOOKUP_TABLE_SIZE; ++i) {
lookupTable[i] = super.name(i);
}
}
}
static class ArrayEntityMap implements EntityMap {
protected int growBy = 100;
protected int size = 0;
protected String[] names;
protected int[] values;
/**
* Constructs a new instance of <code>ArrayEntityMap</code>.
*/
public ArrayEntityMap() {
names = new String[growBy];
values = new int[growBy];
}
/**
* Constructs a new instance of <code>ArrayEntityMap</code> specifying the size by which the array should
* grow.
*
* @param growBy
* array will be initialized to and will grow by this amount
*/
public ArrayEntityMap(int growBy) {
this.growBy = growBy;
names = new String[growBy];
values = new int[growBy];
}
/**
* {@inheritDoc}
*/
public void add(String name, int value) {
ensureCapacity(size + 1);
names[size] = name;
values[size] = value;
size++;
}
/**
* Verifies the capacity of the entity array, adjusting the size if necessary.
*
* @param capacity
* size the array should be
*/
protected void ensureCapacity(int capacity) {
if (capacity > names.length) {
int newSize = Math.max(capacity, size + growBy);
String[] newNames = new String[newSize];
System.arraycopy(names, 0, newNames, 0, size);
names = newNames;
int[] newValues = new int[newSize];
System.arraycopy(values, 0, newValues, 0, size);
values = newValues;
}
}
/**
* {@inheritDoc}
*/
public String name(int value) {
for (int i = 0; i < size; ++i) {
if (values[i] == value) {
return names[i];
}
}
return null;
}
/**
* {@inheritDoc}
*/
public int value(String name) {
for (int i = 0; i < size; ++i) {
if (names[i].equals(name)) {
return values[i];
}
}
return -1;
}
}
static class BinaryEntityMap extends ArrayEntityMap {
/**
* Constructs a new instance of <code>BinaryEntityMap</code>.
*/
public BinaryEntityMap() {
super();
}
/**
* Constructs a new instance of <code>ArrayEntityMap</code> specifying the size by which the underlying array
* should grow.
*
* @param growBy
* array will be initialized to and will grow by this amount
*/
public BinaryEntityMap(int growBy) {
super(growBy);
}
/**
* Performs a binary search of the entity array for the specified key. This method is based on code in
* {@link java.util.Arrays}.
*
* @param key
* the key to be found
* @return the index of the entity array matching the specified key
*/
private int binarySearch(int key) {
int low = 0;
int high = size - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = values[mid];
if (midVal < key) {
low = mid + 1;
} else if (midVal > key) {
high = mid - 1;
} else {
return mid; // key found
}
}
return -(low + 1); // key not found.
}
/**
* {@inheritDoc}
*/
public void add(String name, int value) {
ensureCapacity(size + 1);
int insertAt = binarySearch(value);
if (insertAt > 0) {
return; // note: this means you can't insert the same value twice
}
insertAt = -(insertAt + 1); // binarySearch returns it negative and off-by-one
System.arraycopy(values, insertAt, values, insertAt + 1, size - insertAt);
values[insertAt] = value;
System.arraycopy(names, insertAt, names, insertAt + 1, size - insertAt);
names[insertAt] = name;
size++;
}
/**
* {@inheritDoc}
*/
public String name(int value) {
int index = binarySearch(value);
if (index < 0) {
return null;
}
return names[index];
}
}
// package scoped for testing
EntityMap map = new Entities.LookupEntityMap();
/**
* <p>
* Adds entities to this entity.
* </p>
*
* @param entityArray
* array of entities to be added
*/
public void addEntities(String[][] entityArray) {
for (int i = 0; i < entityArray.length; ++i) {
addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1]));
}
}
/**
* <p>
* Add an entity to this entity.
* </p>
*
* @param name
* name of the entity
* @param value
* vale of the entity
*/
public void addEntity(String name, int value) {
map.add(name, value);
}
/**
* <p>
* Returns the name of the entity identified by the specified value.
* </p>
*
* @param value
* the value to locate
* @return entity name associated with the specified value
*/
public String entityName(int value) {
return map.name(value);
}
/**
* <p>
* Returns the value of the entity identified by the specified name.
* </p>
*
* @param name
* the name to locate
* @return entity value associated with the specified name
*/
public int entityValue(String name) {
return map.value(name);
}
/**
* <p>
* Escapes the characters in a <code>String</code>.
* </p>
*
* <p>
* For example, if you have called addEntity("foo", 0xA1), escape("\u00A1") will return
* "&foo;"
* </p>
*
* @param str
* The <code>String</code> to escape.
* @return A new escaped <code>String</code>.
*/
public String escape(String str) {
StringWriter stringWriter = createStringWriter(str);
try {
this.escape(stringWriter, str);
} catch (IOException e) {
// This should never happen because ALL the StringWriter methods called by #escape(Writer, String) do not
// throw IOExceptions.
throw new IllegalStateException(e);
}
return stringWriter.toString();
}
/**
* <p>
* Escapes the characters in the <code>String</code> passed and writes the result to the <code>Writer</code>
* passed.
* </p>
*
* @param writer
* The <code>Writer</code> to write the results of the escaping to. Assumed to be a non-null value.
* @param str
* The <code>String</code> to escape. Assumed to be a non-null value.
* @throws IOException
* when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)}
* methods.
*
* @see #escape(String)
* @see Writer
*/
public void escape(Writer writer, String str) throws IOException {
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
String entityName = this.entityName(c);
if (entityName == null) {
if (c > 0x7F) {
writer.write("&#");
writer.write(Integer.toString(c, 10));
writer.write(';');
} else {
writer.write(c);
}
} else {
writer.write('&');
writer.write(entityName);
writer.write(';');
}
}
}
/**
* <p>
* Unescapes the entities in a <code>String</code>.
* </p>
*
* <p>
* For example, if you have called addEntity("foo", 0xA1), unescape("&foo;") will return
* "\u00A1"
* </p>
*
* @param str
* The <code>String</code> to escape.
* @return A new escaped <code>String</code>.
*/
public String unescape(String str) {
int firstAmp = str.indexOf('&');
if (firstAmp < 0) {
return str;
} else {
StringWriter stringWriter = createStringWriter(str);
try {
this.doUnescape(stringWriter, str, firstAmp);
} catch (IOException e) {
// This should never happen because ALL the StringWriter methods called by #escape(Writer, String)
// do not throw IOExceptions.
throw new IllegalStateException(e);
}
return stringWriter.toString();
}
}
/**
* Make the StringWriter 10% larger than the source String to avoid growing the writer
*
* @param str The source string
* @return A newly created StringWriter
*/
private StringWriter createStringWriter(String str) {
return new StringWriter((int) (str.length() + (str.length() * 0.1)));
}
/**
* <p>
* Unescapes the escaped entities in the <code>String</code> passed and writes the result to the
* <code>Writer</code> passed.
* </p>
*
* @param writer
* The <code>Writer</code> to write the results to; assumed to be non-null.
* @param str
* The source <code>String</code> to unescape; assumed to be non-null.
* @throws IOException
* when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)}
* methods.
*
* @see #escape(String)
* @see Writer
*/
public void unescape(Writer writer, String str) throws IOException {
int firstAmp = str.indexOf('&');
if (firstAmp < 0) {
writer.write(str);
return;
} else {
doUnescape(writer, str, firstAmp);
}
}
/**
* Underlying unescape method that allows the optimisation of not starting from the 0 index again.
*
* @param writer
* The <code>Writer</code> to write the results to; assumed to be non-null.
* @param str
* The source <code>String</code> to unescape; assumed to be non-null.
* @param firstAmp
* The <code>int</code> index of the first ampersand in the source String.
* @throws IOException
* when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)}
* methods.
*/
private void doUnescape(Writer writer, String str, int firstAmp) throws IOException {
writer.write(str, 0, firstAmp);
int len = str.length();
for (int i = firstAmp; i < len; i++) {
char c = str.charAt(i);
if (c == '&') {
int nextIdx = i + 1;
int semiColonIdx = str.indexOf(';', nextIdx);
if (semiColonIdx == -1) {
writer.write(c);
continue;
}
int amphersandIdx = str.indexOf('&', i + 1);
if (amphersandIdx != -1 && amphersandIdx < semiColonIdx) {
// Then the text looks like &...&...;
writer.write(c);
continue;
}
String entityContent = str.substring(nextIdx, semiColonIdx);
int entityValue = -1;
int entityContentLen = entityContent.length();
if (entityContentLen > 0) {
if (entityContent.charAt(0) == '#') { // escaped value content is an integer (decimal or
// hexidecimal)
if (entityContentLen > 1) {
char isHexChar = entityContent.charAt(1);
try {
switch (isHexChar) {
case 'X' :
case 'x' : {
entityValue = Integer.parseInt(entityContent.substring(2), 16);
break;
}
default : {
entityValue = Integer.parseInt(entityContent.substring(1), 10);
}
}
if (entityValue > 0xFFFF) {
entityValue = -1;
}
} catch (NumberFormatException e) {
entityValue = -1;
}
}
} else { // escaped value content is an entity name
entityValue = this.entityValue(entityContent);
}
}
if (entityValue == -1) {
writer.write('&');
writer.write(entityContent);
writer.write(';');
} else {
writer.write(entityValue);
}
i = semiColonIdx; // move index up to the semi-colon
} else {
writer.write(c);
}
}
}
}
| apache-2.0 |
reynoldsm88/drools | drools-beliefs/src/main/java/org/drools/beliefs/bayes/runtime/BayesRuntimeImpl.java | 2480 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.beliefs.bayes.runtime;
import org.drools.beliefs.bayes.BayesInstance;
import org.drools.beliefs.bayes.JunctionTree;
import org.drools.beliefs.bayes.assembler.BayesPackage;
import org.drools.core.common.InternalKnowledgeRuntime;
import org.drools.core.definitions.InternalKnowledgePackage;
import org.kie.api.internal.io.ResourceTypePackage;
import org.kie.api.io.ResourceType;
import java.util.Map;
public class BayesRuntimeImpl implements BayesRuntime {
private InternalKnowledgeRuntime runtime;
//private Map<String, BayesInstance> instances;
public BayesRuntimeImpl(InternalKnowledgeRuntime runtime) {
this.runtime = runtime;
//this.instances = new HashMap<String, BayesInstance>();
}
// @Override
// public BayesInstance createBayesFact(Class cls) {
// // using the two-tone pattern, to ensure only one is created
// BayesInstance instance = instances.get( cls.getName() );
// if ( instance == null ) {
// instance = createInstance(cls);
// }
//
// return instance;
// }
public BayesInstance createInstance(Class cls) {
// synchronised using the two-tone pattern, to ensure only one is created
// BayesInstance instance = instances.get( cls.getName() );
// if ( instance != null ) {
// return instance;
// }
InternalKnowledgePackage kpkg = (InternalKnowledgePackage) runtime.getKieBase().getKiePackage( cls.getPackage().getName() );
Map<ResourceType, ResourceTypePackage> map = kpkg.getResourceTypePackages();
BayesPackage bayesPkg = (BayesPackage) map.get( ResourceType.BAYES );
JunctionTree jtree = bayesPkg.getJunctionTree(cls.getSimpleName());
BayesInstance instance = new BayesInstance( jtree, cls );
// instances.put( cls.getName() , instance );
return instance;
}
}
| apache-2.0 |
immqy/MutiChannelPackup | jar-build/JarBuild/src/com/finalteam/jarbuild/FileUtils.java | 2757 | package com.finalteam.jarbuild;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
*
* @author pengjianbo
*
*/
public class FileUtils {
public static String getFileExtension(String filePath) {
if (filePath == null || filePath.trim().length() == 0) {
return filePath;
}
int extenPosi = filePath.lastIndexOf(".");
int filePosi = filePath.lastIndexOf(File.separator);
if (extenPosi == -1) {
return "";
}
return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1);
}
public static boolean makeDirs(String filePath) {
String folderName = getFolderName(filePath);
if (folderName == null || folderName.trim().length() == 0) {
return false;
}
File folder = new File(folderName);
return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
}
public static String getFolderName(String filePath) {
if (filePath == null || filePath.trim().length() == 0) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
}
public static String getFileNameWithoutExtension(String filePath) {
if (filePath == null || filePath.trim().length() == 0) {
return filePath;
}
int extenPosi = filePath.lastIndexOf(".");
int filePosi = filePath.lastIndexOf(File.separator);
if (filePosi == -1) {
return (extenPosi == -1 ? filePath : filePath.substring(0, extenPosi));
}
if (extenPosi == -1) {
return filePath.substring(filePosi + 1);
}
return (filePosi < extenPosi ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1));
}
/**
* 使用文件通道的方式复制文件
* @param s 源文件
* @param t复制到的新文件
*/
public static void copy(File sourceFile, File targeFile) {
FileInputStream fi = null;
FileOutputStream fo = null;
FileChannel in = null;
FileChannel out = null;
try {
fi = new FileInputStream(sourceFile);
fo = new FileOutputStream(targeFile);
in = fi.getChannel();// 得到对应的文件通道
out = fo.getChannel();// 得到对应的文件通道
in.transferTo(0, in.size(), out);// 连接两个通道,并且从in通道读取,然后写入out通道
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fi.close();
in.close();
fo.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| apache-2.0 |
evandor/skysail | skysail.server/src/io/skysail/server/commands/StaticServiceAnalysisCommand.java | 4278 | package io.skysail.server.commands;
import java.util.*;
import java.util.regex.*;
import java.util.stream.Collectors;
import org.apache.felix.service.command.CommandProcessor;
import org.osgi.framework.Bundle;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.*;
import io.skysail.server.utils.BundleUtils;
import lombok.Getter;
@Component(property = { CommandProcessor.COMMAND_SCOPE + ":String=skysail",
CommandProcessor.COMMAND_FUNCTION + ":String=analysis", }, service = Object.class)
public class StaticServiceAnalysisCommand { // NO_UCD (unused code)
@Getter
public class Ref {
private String source;
private String target;
private String group;
public Ref(String source, String target, String group) {
this.source = source.substring(source.lastIndexOf(".")+1);
this.target = target.substring(target.lastIndexOf(".")+1);
this.group = group.substring(group.lastIndexOf(".")+1);
}
}
private ComponentContext ctx;
private Pattern implementationPattern = Pattern.compile("implementation class=\"(.*)\"");
private Pattern interfacesPattern = Pattern.compile("provide interface=\"(.*)\"");
private Pattern referencesPattern = Pattern.compile("reference (.)*interface=\"([^\"]*)\"");
private List<Ref> refs = new ArrayList<>();
@Activate
public void activate(ComponentContext ctx) {
this.ctx = ctx;
}
@Deactivate
public void deactivate(ComponentContext ctx) {
this.ctx = null;
}
public void analysis() {
System.out.println("Running static services analysis... ");
System.out.println("========================================================");
System.out.println("(past the following to e.g. http://www.webgraphviz.com/)");
System.out.println();
Arrays.stream(ctx.getBundleContext().getBundles()).forEach(b -> {
List<String> files = getDSFiles(b);
files.stream().forEach(file -> parse(file));
});
System.out.println("digraph {");
refs.forEach(ref -> {
System.out.println(ref.getSource().replace(".", "") + " -> " + ref.getTarget().replace(".", "")
+ "[label=\"" + ref.getGroup() + "\"];");
});
System.out.println("}");
}
private Object parse(String file) {
Matcher matcher = implementationPattern.matcher(file);
while (matcher.find()) {
String group = matcher.group(1);
//System.out.println(group);
List<String> targets = new ArrayList<>();
List<String> sources = new ArrayList<>();
Matcher interfacesMatcher = interfacesPattern.matcher(file);
while (interfacesMatcher.find()) {
String implementing = interfacesMatcher.group(1);
//System.out.println(" > " + implementing);
targets.add(implementing);
}
Matcher referenceMatcher = referencesPattern.matcher(file);
while (referenceMatcher.find()) {
String referencing = referenceMatcher.group(2);
sources.add(referencing);
//System.out.println(" >>> " + referencing);
}
sources.stream().forEach(source -> {
targets.stream().forEach(target -> {
if (source.contains("skysail") && target.contains("skysail")) {
refs.add(new Ref(source, target, group));
}
});
});
}
return null;
}
private List<String> getDSFiles(Bundle bundle) {
Enumeration<String> entryPathsEnumeration = bundle.getEntryPaths("OSGI-INF");
if (entryPathsEnumeration == null) {
return Collections.emptyList();
}
List<String> entryPaths = Collections.list(entryPathsEnumeration);
return entryPaths.stream().filter(path -> path.endsWith(".xml")).map(path -> readBundleFile(bundle, path))
.collect(Collectors.toList());
}
private String readBundleFile(Bundle bundle, String path) {
return BundleUtils.readResource(bundle, path);
}
}
| apache-2.0 |
cuba-platform/cuba | modules/desktop/src/com/haulmont/cuba/desktop/sys/validation/ValidationAwareAction.java | 1704 | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.desktop.sys.validation;
import com.haulmont.cuba.desktop.gui.components.DesktopComponentsHelper;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public abstract class ValidationAwareAction extends AbstractAction {
@Override
public void actionPerformed(final ActionEvent e) {
final RootPaneContainer window;
if (e.getSource() instanceof Component) {
window = DesktopComponentsHelper.getSwingWindow((Component) e.getSource());
} else {
window = null;
}
ValidationAlertHolder.runIfValid(new Runnable() {
@Override
public void run() {
if (window == null
|| window.getGlassPane() == null
|| !window.getGlassPane().isVisible()) {
// check modal dialogs on the front of current component
actionPerformedAfterValidation(e);
}
}
});
}
public abstract void actionPerformedAfterValidation(ActionEvent e);
} | apache-2.0 |
NetoDevel/spring-boot | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.java | 14787 | /*
* Copyright 2012-2020 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.web.servlet.context;
import java.util.Collection;
import java.util.Collections;
import java.util.EventListener;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.boot.web.context.ConfigurableWebServerApplicationContext;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.ServletContextInitializerBeans;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextException;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.context.support.ServletContextAwareProcessor;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.context.support.ServletContextScope;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* A {@link WebApplicationContext} that can be used to bootstrap itself from a contained
* {@link ServletWebServerFactory} bean.
* <p>
* This context will create, initialize and run an {@link WebServer} by searching for a
* single {@link ServletWebServerFactory} bean within the {@link ApplicationContext}
* itself. The {@link ServletWebServerFactory} is free to use standard Spring concepts
* (such as dependency injection, lifecycle callbacks and property placeholder variables).
* <p>
* In addition, any {@link Servlet} or {@link Filter} beans defined in the context will be
* automatically registered with the web server. In the case of a single Servlet bean, the
* '/' mapping will be used. If multiple Servlet beans are found then the lowercase bean
* name will be used as a mapping prefix. Any Servlet named 'dispatcherServlet' will
* always be mapped to '/'. Filter beans will be mapped to all URLs ('/*').
* <p>
* For more advanced configuration, the context can instead define beans that implement
* the {@link ServletContextInitializer} interface (most often
* {@link ServletRegistrationBean}s and/or {@link FilterRegistrationBean}s). To prevent
* double registration, the use of {@link ServletContextInitializer} beans will disable
* automatic Servlet and Filter bean registration.
* <p>
* Although this context can be used directly, most developers should consider using the
* {@link AnnotationConfigServletWebServerApplicationContext} or
* {@link XmlServletWebServerApplicationContext} variants.
*
* @author Phillip Webb
* @author Dave Syer
* @since 2.0.0
* @see AnnotationConfigServletWebServerApplicationContext
* @see XmlServletWebServerApplicationContext
* @see ServletWebServerFactory
*/
public class ServletWebServerApplicationContext extends GenericWebApplicationContext
implements ConfigurableWebServerApplicationContext {
private static final Log logger = LogFactory.getLog(ServletWebServerApplicationContext.class);
/**
* Constant value for the DispatcherServlet bean name. A Servlet bean with this name
* is deemed to be the "main" servlet and is automatically given a mapping of "/" by
* default. To change the default behavior you can use a
* {@link ServletRegistrationBean} or a different bean name.
*/
public static final String DISPATCHER_SERVLET_NAME = "dispatcherServlet";
private volatile WebServer webServer;
private ServletConfig servletConfig;
private String serverNamespace;
/**
* Create a new {@link ServletWebServerApplicationContext}.
*/
public ServletWebServerApplicationContext() {
}
/**
* Create a new {@link ServletWebServerApplicationContext} with the given
* {@code DefaultListableBeanFactory}.
* @param beanFactory the DefaultListableBeanFactory instance to use for this context
*/
public ServletWebServerApplicationContext(DefaultListableBeanFactory beanFactory) {
super(beanFactory);
}
/**
* Register ServletContextAwareProcessor.
* @see ServletContextAwareProcessor
*/
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
registerWebApplicationScopes();
}
@Override
public final void refresh() throws BeansException, IllegalStateException {
try {
super.refresh();
}
catch (RuntimeException ex) {
stopAndReleaseWebServer();
throw ex;
}
}
@Override
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
@Override
protected void finishRefresh() {
super.finishRefresh();
WebServer webServer = startWebServer();
if (webServer != null) {
publishEvent(new ServletWebServerInitializedEvent(webServer, this));
}
}
@Override
protected void doClose() {
AvailabilityChangeEvent.publish(this, ReadinessState.REFUSING_TRAFFIC);
WebServer webServer = this.webServer;
if (webServer != null) {
webServer.shutDownGracefully();
}
super.doClose();
}
@Override
protected void onClose() {
super.onClose();
stopAndReleaseWebServer();
}
private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null) {
ServletWebServerFactory factory = getWebServerFactory();
this.webServer = factory.getWebServer(getSelfInitializer());
}
else if (servletContext != null) {
try {
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context", ex);
}
}
initPropertySources();
}
/**
* Returns the {@link ServletWebServerFactory} that should be used to create the
* embedded {@link WebServer}. By default this method searches for a suitable bean in
* the context itself.
* @return a {@link ServletWebServerFactory} (never {@code null})
*/
protected ServletWebServerFactory getWebServerFactory() {
// Use bean names so that we don't consider the hierarchy
String[] beanNames = getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class);
if (beanNames.length == 0) {
throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to missing "
+ "ServletWebServerFactory bean.");
}
if (beanNames.length > 1) {
throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to multiple "
+ "ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames));
}
return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
}
/**
* Returns the {@link ServletContextInitializer} that will be used to complete the
* setup of this {@link WebApplicationContext}.
* @return the self initializer
* @see #prepareWebApplicationContext(ServletContext)
*/
private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() {
return this::selfInitialize;
}
private void selfInitialize(ServletContext servletContext) throws ServletException {
prepareWebApplicationContext(servletContext);
registerApplicationScope(servletContext);
WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext);
for (ServletContextInitializer beans : getServletContextInitializerBeans()) {
beans.onStartup(servletContext);
}
}
private void registerApplicationScope(ServletContext servletContext) {
ServletContextScope appScope = new ServletContextScope(servletContext);
getBeanFactory().registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
// Register as ServletContext attribute, for ContextCleanupListener to detect it.
servletContext.setAttribute(ServletContextScope.class.getName(), appScope);
}
private void registerWebApplicationScopes() {
ExistingWebApplicationScopes existingScopes = new ExistingWebApplicationScopes(getBeanFactory());
WebApplicationContextUtils.registerWebApplicationScopes(getBeanFactory());
existingScopes.restore();
}
/**
* Returns {@link ServletContextInitializer}s that should be used with the embedded
* web server. By default this method will first attempt to find
* {@link ServletContextInitializer}, {@link Servlet}, {@link Filter} and certain
* {@link EventListener} beans.
* @return the servlet initializer beans
*/
protected Collection<ServletContextInitializer> getServletContextInitializerBeans() {
return new ServletContextInitializerBeans(getBeanFactory());
}
/**
* Prepare the {@link WebApplicationContext} with the given fully loaded
* {@link ServletContext}. This method is usually called from
* {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the
* functionality usually provided by a {@link ContextLoaderListener}.
* @param servletContext the operational servlet context
*/
protected void prepareWebApplicationContext(ServletContext servletContext) {
Object rootContext = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
if (rootContext != null) {
if (rootContext == this) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - "
+ "check whether you have multiple ServletContextInitializers!");
}
return;
}
Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring embedded WebApplicationContext");
try {
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this);
if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name ["
+ WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
setServletContext(servletContext);
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - getStartupDate();
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
}
}
catch (RuntimeException | Error ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
}
private WebServer startWebServer() {
WebServer webServer = this.webServer;
if (webServer != null) {
webServer.start();
}
return webServer;
}
private void stopAndReleaseWebServer() {
WebServer webServer = this.webServer;
if (webServer != null) {
try {
webServer.stop();
this.webServer = null;
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
}
@Override
protected Resource getResourceByPath(String path) {
if (getServletContext() == null) {
return new ClassPathContextResource(path, getClassLoader());
}
return new ServletContextResource(getServletContext(), path);
}
@Override
public String getServerNamespace() {
return this.serverNamespace;
}
@Override
public void setServerNamespace(String serverNamespace) {
this.serverNamespace = serverNamespace;
}
@Override
public void setServletConfig(ServletConfig servletConfig) {
this.servletConfig = servletConfig;
}
@Override
public ServletConfig getServletConfig() {
return this.servletConfig;
}
/**
* Returns the {@link WebServer} that was created by the context or {@code null} if
* the server has not yet been created.
* @return the embedded web server
*/
@Override
public WebServer getWebServer() {
return this.webServer;
}
/**
* Utility class to store and restore any user defined scopes. This allow scopes to be
* registered in an ApplicationContextInitializer in the same way as they would in a
* classic non-embedded web application context.
*/
public static class ExistingWebApplicationScopes {
private static final Set<String> SCOPES;
static {
Set<String> scopes = new LinkedHashSet<>();
scopes.add(WebApplicationContext.SCOPE_REQUEST);
scopes.add(WebApplicationContext.SCOPE_SESSION);
SCOPES = Collections.unmodifiableSet(scopes);
}
private final ConfigurableListableBeanFactory beanFactory;
private final Map<String, Scope> scopes = new HashMap<>();
public ExistingWebApplicationScopes(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
for (String scopeName : SCOPES) {
Scope scope = beanFactory.getRegisteredScope(scopeName);
if (scope != null) {
this.scopes.put(scopeName, scope);
}
}
}
public void restore() {
this.scopes.forEach((key, value) -> {
if (logger.isInfoEnabled()) {
logger.info("Restoring user defined scope " + key);
}
this.beanFactory.registerScope(key, value);
});
}
}
}
| apache-2.0 |
intalio/axis2 | modules/jaxws/src/org/apache/axis2/jaxws/message/util/impl/XMLStreamReaderFromDOM.java | 23554 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axis2.jaxws.message.util.impl;
import org.apache.axis2.jaxws.i18n.Messages;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.StringTokenizer;
/**
* XMLStreamReader created from walking a DOM. This is an implementation class used by
* SOAPElementReader.
*
* @see org.apache.axis2.jaxws.util.SOAPElementReader
*/
public class XMLStreamReaderFromDOM implements XMLStreamReader {
private Node cursor;
private Stack<Node> nextCursorStack = new Stack<Node>();
private Node root;
private int event = XMLStreamReader.START_DOCUMENT;
private Node nextCursor = null;
private int nextEvent = -1;
private NamespaceContextFromDOM cacheNCI = null;
private Element cacheNCIKey = null;
private List cacheND = null;
private Element cacheNDKey = null;
/**
* Create the XMLStreamReader with an Envelope
*
* @param envelope Element (probably an SAAJ SOAPEnvelope) representing the Envelope
*/
public XMLStreamReaderFromDOM(Element envelope) {
root = envelope;
cursor = root;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getProperty(java.lang.String)
*/
public Object getProperty(String key) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException(Messages.getMessage("XMLSRErr1"));
}
return null;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#next()
*/
public int next() throws XMLStreamException {
if (!hasNext()) {
throw new XMLStreamException(Messages.getMessage("XMLSRErr2"));
}
getNext();
cursor = nextCursor;
event = nextEvent;
return event;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#require(int, java.lang.String, java.lang.String)
*/
public void require(int event, String namespace, String localPart)
throws XMLStreamException {
try {
if (event != this.event) {
throw new XMLStreamException(Messages.getMessage("XMLSRErr3", String.valueOf(event),
String.valueOf(this.event)));
}
if (namespace != null &&
!namespace.equals(cursor.getNamespaceURI())) {
throw new XMLStreamException(
Messages.getMessage("XMLSRErr3", namespace, this.cursor.getNamespaceURI()));
}
if (localPart != null &&
!localPart.equals(cursor.getLocalName())) {
throw new XMLStreamException(
Messages.getMessage("XMLSRErr3", localPart, this.cursor.getLocalName()));
}
} catch (XMLStreamException e) {
throw e;
} catch (Exception e) {
throw new XMLStreamException(e);
}
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getElementText()
*/
public String getElementText() throws XMLStreamException {
if (event == XMLStreamReader.START_ELEMENT) {
next();
StringBuffer buffer = new StringBuffer();
while (event != XMLStreamReader.END_ELEMENT) {
if (event == XMLStreamReader.CHARACTERS ||
event == XMLStreamReader.CDATA ||
event == XMLStreamReader.SPACE ||
event == XMLStreamReader.ENTITY_REFERENCE) {
buffer.append(getText());
} else if (event == XMLStreamReader.PROCESSING_INSTRUCTION ||
event == XMLStreamReader.COMMENT) {
// whitespace
} else {
throw new XMLStreamException(
Messages.getMessage("XMLSRErr4", "getElementText()"));
}
next();
}
return buffer.toString();
}
throw new XMLStreamException(Messages.getMessage("XMLSRErr4", "getElementText()"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#nextTag()
*/
public int nextTag() throws XMLStreamException {
next();
while (event == XMLStreamReader.CHARACTERS && isWhiteSpace() ||
event == XMLStreamReader.CDATA && isWhiteSpace() ||
event == XMLStreamReader.SPACE ||
event == XMLStreamReader.PROCESSING_INSTRUCTION ||
event == XMLStreamReader.COMMENT) {
event = next();
}
if (event == XMLStreamReader.START_ELEMENT ||
event == XMLStreamReader.END_ELEMENT) {
return event;
}
throw new XMLStreamException(Messages.getMessage("XMLSRErr4", "nextTag()"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#hasNext()
*/
public boolean hasNext() throws XMLStreamException {
return (event != XMLStreamReader.END_DOCUMENT);
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#close()
*/
public void close() throws XMLStreamException {
return;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getNamespaceURI(java.lang.String)
*/
public String getNamespaceURI(String prefix) {
if (cursor instanceof Element) {
return getNamespaceContext().getNamespaceURI(prefix);
}
throw new IllegalStateException(
Messages.getMessage("XMLSRErr4", "getNamespaceURI(String)"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#isStartElement()
*/
public boolean isStartElement() {
return (event == XMLStreamReader.START_ELEMENT);
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#isEndElement()
*/
public boolean isEndElement() {
return (event == XMLStreamReader.END_ELEMENT);
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#isCharacters()
*/
public boolean isCharacters() {
return (event == XMLStreamReader.CHARACTERS);
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#isWhiteSpace()
*/
public boolean isWhiteSpace() {
if (event == XMLStreamReader.CHARACTERS ||
event == XMLStreamReader.CDATA) {
String value = ((CharacterData)cursor).getData();
StringTokenizer st = new StringTokenizer(value);
return !(st.hasMoreTokens());
}
return false;
}
/** @return list of attributes that are not namespace declarations */
private List getAttributes() {
if (event == XMLStreamReader.START_ELEMENT) {
List attrs = new ArrayList();
NamedNodeMap map = ((Element)cursor).getAttributes();
if (map != null) {
for (int i = 0; i < map.getLength(); i++) {
Attr attr = (Attr)map.item(i);
if (attr.getName().equals("xmlns") ||
attr.getName().startsWith("xmlns:")) {
// this is a namespace declaration
} else {
attrs.add(attr);
}
}
}
return attrs;
}
throw new IllegalStateException(Messages.getMessage("XMLSRErr4", "getAttributes()"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getAttributeValue(java.lang.String, java.lang.String)
*/
public String getAttributeValue(String namespace, String localPart) {
if (event == XMLStreamReader.START_ELEMENT) {
return ((Element)cursor).getAttributeNS(namespace, localPart);
}
throw new IllegalStateException(
Messages.getMessage("XMLSRErr4", "getAttributeValue(String, String)"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getAttributeCount()
*/
public int getAttributeCount() {
return getAttributes().size();
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getAttributeName(int)
*/
public QName getAttributeName(int index) {
Attr attr = (Attr)getAttributes().get(index);
return new QName(attr.getNamespaceURI(), attr.getLocalName());
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getAttributeNamespace(int)
*/
public String getAttributeNamespace(int index) {
Attr attr = (Attr)getAttributes().get(index);
return attr.getNamespaceURI();
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getAttributeLocalName(int)
*/
public String getAttributeLocalName(int index) {
Attr attr = (Attr)getAttributes().get(index);
return attr.getLocalName();
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getAttributePrefix(int)
*/
public String getAttributePrefix(int index) {
Attr attr = (Attr)getAttributes().get(index);
return attr.getPrefix();
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getAttributeType(int)
*/
public String getAttributeType(int index) {
Attr attr = (Attr)getAttributes().get(index);
return attr.getSchemaTypeInfo().getTypeName();
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getAttributeValue(int)
*/
public String getAttributeValue(int index) {
Attr attr = (Attr)getAttributes().get(index);
return attr.getValue();
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#isAttributeSpecified(int)
*/
public boolean isAttributeSpecified(int arg0) {
return true;
}
/*
* @return number of namespace declarations on this element
*/
public int getNamespaceCount() {
if (cursor instanceof Element) {
List list = getNamespaceDeclarations();
return list.size();
}
throw new IllegalStateException(Messages.getMessage("XMLSRErr4", "getNamespaceCount()"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getNamespacePrefix(int)
*/
public String getNamespacePrefix(int index) {
if (cursor instanceof Element) {
List list = getNamespaceDeclarations();
return ((NamespaceDeclare)list.get(index)).getPrefix();
}
throw new IllegalStateException(
Messages.getMessage("XMLSRErr4", "getNamespacePrefix(int)"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getNamespaceURI(int)
*/
public String getNamespaceURI(int index) {
if (cursor instanceof Element) {
List list = getNamespaceDeclarations();
return ((NamespaceDeclare)list.get(index)).getURI();
}
throw new IllegalStateException(Messages.getMessage("XMLSRErr4", "getNamespaceURI(int)"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getNamespaceContext()
*/
public NamespaceContext getNamespaceContext() {
Element element = null;
if (cursor instanceof Element) {
element = (Element)cursor;
} else {
Element parent = (Element)cursor.getParentNode();
if (parent == null) {
parent = (Element)nextCursorStack.peek();
}
element = (Element)cursor.getParentNode();
}
if (element == cacheNCIKey) {
return cacheNCI;
}
cacheNCIKey = element;
cacheNCI = new NamespaceContextFromDOM(element);
return cacheNCI;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getEventType()
*/
public int getEventType() {
return event;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getText()
*/
public String getText() {
if (event == XMLStreamReader.CHARACTERS ||
event == XMLStreamReader.CDATA ||
event == XMLStreamReader.COMMENT) {
return ((CharacterData)cursor).getData();
}
throw new IllegalStateException(Messages.getMessage("XMLSRErr4", "getText()"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getTextCharacters()
*/
public char[] getTextCharacters() {
return getText().toCharArray();
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getTextCharacters(int, char[], int, int)
*/
public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length)
throws XMLStreamException {
String value = getText();
// Calculate the sourceEnd index
int sourceEnd = sourceStart + length;
if (value.length() < sourceEnd) {
sourceEnd = value.length();
}
value.getChars(sourceStart, sourceEnd, target, targetStart);
return sourceEnd - sourceStart;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getTextStart()
*/
public int getTextStart() {
return 0;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getTextLength()
*/
public int getTextLength() {
return getText().length();
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getEncoding()
*/
public String getEncoding() {
return null;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#hasText()
*/
public boolean hasText() {
return (event == XMLStreamReader.CHARACTERS ||
event == XMLStreamReader.CDATA ||
event == XMLStreamReader.COMMENT);
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getLocation()
*/
public Location getLocation() {
return dummyLocation;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getName()
*/
public QName getName() {
if (cursor instanceof Element) {
return new QName(cursor.getNamespaceURI(), cursor.getLocalName());
}
throw new IllegalStateException(Messages.getMessage("XMLSRErr4", "getName()"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getLocalName()
*/
public String getLocalName() {
if (cursor instanceof Element) {
return cursor.getLocalName();
}
throw new IllegalStateException(Messages.getMessage("XMLSRErr4", "getLocalName()"));
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#hasName()
*/
public boolean hasName() {
return (isStartElement() || isEndElement());
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getNamespaceURI()
*/
public String getNamespaceURI() {
if (cursor instanceof Element) {
return cursor.getNamespaceURI();
} else {
return null;
}
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getPrefix()
*/
public String getPrefix() {
if (cursor instanceof Element) {
return cursor.getPrefix();
} else {
return null;
}
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getVersion()
*/
public String getVersion() {
return null;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#isStandalone()
*/
public boolean isStandalone() {
return false;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#standaloneSet()
*/
public boolean standaloneSet() {
return false;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getCharacterEncodingScheme()
*/
public String getCharacterEncodingScheme() {
return null;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getPITarget()
*/
public String getPITarget() {
return null;
}
/* (non-Javadoc)
* @see javax.xml.stream.XMLStreamReader#getPIData()
*/
public String getPIData() {
return null;
}
/** Sets nextCursor and nextEvent from using the current cursor and event. */
private void getNext() throws IllegalStateException {
switch (event) {
case XMLStreamReader.START_DOCUMENT: {
nextCursor = cursor;
nextEvent = XMLStreamReader.START_ELEMENT;
break;
}
case XMLStreamReader.START_ELEMENT: {
if (cursor.getFirstChild() != null) {
nextCursorStack.push(nextCursor);
nextCursor = cursor.getFirstChild();
nextEvent = startEvent(nextCursor);
} else {
nextEvent = XMLStreamReader.END_ELEMENT;
}
break;
}
case XMLStreamReader.ATTRIBUTE: {
throw new IllegalStateException(Messages.getMessage("XMLSRErr5", "ATTRIBUTE"));
}
case XMLStreamReader.NAMESPACE: {
throw new IllegalStateException(Messages.getMessage("XMLSRErr5", "NAMESPACE"));
}
case XMLStreamReader.END_ELEMENT:
case XMLStreamReader.CHARACTERS:
case XMLStreamReader.CDATA:
case XMLStreamReader.COMMENT:
case XMLStreamReader.SPACE:
case XMLStreamReader.PROCESSING_INSTRUCTION:
case XMLStreamReader.ENTITY_REFERENCE:
case XMLStreamReader.DTD: {
if (cursor.getNextSibling() != null) {
nextCursor = cursor.getNextSibling();
nextEvent = startEvent(nextCursor);
} else if (cursor == root) {
nextEvent = XMLStreamReader.END_DOCUMENT;
} else {
// The following does not work with
// Axiom Text nodes
// nextCursor = cursor.getParentNode();
// This is the reason why a stack is used.
nextCursor = nextCursorStack.pop();
nextEvent = XMLStreamReader.END_ELEMENT;
}
break;
}
case XMLStreamReader.END_DOCUMENT: {
nextCursor = null;
nextEvent = -1;
}
default:
throw new IllegalStateException(
Messages.getMessage("XMLSRErr5", String.valueOf(event)));
}
}
/**
* Returns the start event for this particular node
*
* @param node
* @return
*/
private int startEvent(Node node) {
if (node instanceof ProcessingInstruction) {
return XMLStreamReader.PROCESSING_INSTRUCTION;
}
if (node instanceof CDATASection) {
return XMLStreamReader.CDATA;
}
if (node instanceof Comment) {
return XMLStreamReader.COMMENT;
}
if (node instanceof Text) {
if (node instanceof javax.xml.soap.Text) {
javax.xml.soap.Text soapText = (javax.xml.soap.Text)node;
if (soapText.isComment()) {
return XMLStreamReader.COMMENT;
} else {
return XMLStreamReader.CHARACTERS;
}
}
return XMLStreamReader.CHARACTERS;
}
if (node instanceof Element) {
return XMLStreamReader.START_ELEMENT;
}
if (node instanceof Attr) {
return XMLStreamReader.ATTRIBUTE;
}
if (node instanceof Document) {
return XMLStreamReader.START_DOCUMENT;
}
if (node instanceof EntityReference) {
return XMLStreamReader.ENTITY_REFERENCE;
}
if (node instanceof DocumentType) {
return XMLStreamReader.DTD;
}
return -1;
}
// This is the definition of a dummy Location
private DummyLocation dummyLocation = new DummyLocation();
private class DummyLocation implements Location {
public int getLineNumber() {
return -1;
}
public int getColumnNumber() {
return 0;
}
public int getCharacterOffset() {
return 0;
}
public String getPublicId() {
return null;
}
public String getSystemId() {
return null;
}
}
public List getNamespaceDeclarations() {
Element element = null;
if (cursor instanceof Element) {
element = (Element)cursor;
} else {
return new ArrayList();
}
if (element == cacheNDKey) {
return cacheND;
}
cacheNDKey = element;
cacheND = new ArrayList();
NamedNodeMap attrs = element.getAttributes();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr)attrs.item(i);
String name = attr.getNodeName();
if (name.startsWith("xmlns")) {
String prefix = "";
if (name.startsWith("xmlns:")) {
prefix = name.substring(6);
}
NamespaceDeclare nd = new NamespaceDeclare(prefix, attr.getNodeValue());
cacheND.add(nd);
}
}
}
return cacheND;
}
class NamespaceDeclare {
String prefix;
String uri;
NamespaceDeclare(String prefix, String uri) {
this.prefix = prefix;
this.uri = uri;
}
String getPrefix() {
return prefix;
}
String getURI() {
return uri;
}
}
Node getNode() {
return cursor;
}
}
| apache-2.0 |
nhnent/toast-haste.framework | transport/src/main/java/com/nhnent/haste/transport/EventExecutor.java | 1184 | /*
* Copyright 2016 NHN Entertainment Corp.
*
* NHN Entertainment Corp. 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.nhnent.haste.transport;
import java.nio.channels.Selector;
/**
* Control information about the network.
* For instance, {@link Selector}, {@link TransportProxy}, and timeout, etc.
*/
public interface EventExecutor {
/**
* Return a selector.
*/
Selector selector();
/**
* Register proxy that processed event when received data from a socket.
*/
void registerProxy(TransportProxy transportProxy);
/**
* Set a timeout of selector.
*/
void setSelectorTimeout(long milliseconds);
}
| apache-2.0 |
WACREN/IDPPublic | src/java/it/infn/ct/security/utilities/LDAPCleaner.java | 9234 | /***********************************************************************
* Copyright (c) 2011:
* Istituto Nazionale di Fisica Nucleare (INFN), Italy
* Consorzio COMETA (COMETA), Italy
*
* See http://www.infn.it and and http://www.consorzio-cometa.it for details on
* the copyright holders.
*
* 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 it.infn.ct.security.utilities;
import it.infn.ct.security.actions.MailException;
import it.infn.ct.security.entities.UserConfirmUpdate;
import it.infn.ct.security.entities.UserRequest;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
/**
*
* @author Marco Fargetta <marco.fargetta@ct.infn.it>
*/
public class LDAPCleaner implements Runnable{
private Log _log= LogFactory.getLog(LDAPCleaner.class);
private SessionFactory factory;
private int cycle[];
private ResourceBundle rb;
public LDAPCleaner(SessionFactory factory) {
rb= ResourceBundle.getBundle("cleaner");
this.factory = factory;
try{
String strCycles[]= rb.getString("NotifyCycle").split(",");
cycle= new int[strCycles.length];
for(int i=0; i<strCycles.length; i++){
cycle[i]=Integer.parseInt(strCycles[i]);
}
}
catch(MissingResourceException mre){
cycle= new int[3];
cycle[0]=20;
cycle[1]=10;
cycle[2]=5;
}
}
public void run() {
_log.info("Users cleaning cycle start");
firstCheck(cycle[0]);
for(int i=1; i<cycle.length; i++){
followingChecks(cycle[i]);
}
stopUsers();
_log.info("Users cleaning cycle stop");
}
private void firstCheck(int days){
_log.info("Search users starting the account extension cycle");
List<LDAPUser> userLst= LDAPUtils.getIdPUserList();
for(LDAPUser user: userLst){
Calendar cal= GregorianCalendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, days);
Calendar userCreation= GregorianCalendar.getInstance();
userCreation.setTime(user.getCreationTime());
if(cal.get(Calendar.DAY_OF_YEAR)==userCreation.get(Calendar.DAY_OF_YEAR)){
_log.info("Update account procedure for the user "+user.getGivenname()+" "+user.getSurname()+"("+user.getUsername()+") started");
UserConfirmUpdate ucu= new UserConfirmUpdate(user.getUsername(),cal.getTime(),false);
Session ses= factory.openSession();
ses.beginTransaction();
if(ses.createCriteria(UserConfirmUpdate.class)
.add(Restrictions.eq("username", user.getUsername()))
.add(Restrictions.eq("updated", Boolean.FALSE))
.list()
.isEmpty())
{
ses.save(ucu);
}
ses.getTransaction().commit();
ses.close();
sendUserRemainder(user, days);
}
}
}
private void followingChecks(int days){
_log.info("Check users who have not extended yet");
Calendar cal= GregorianCalendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, days);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar calEnd= GregorianCalendar.getInstance();
calEnd.setTime(cal.getTime());
calEnd.add(Calendar.DAY_OF_YEAR, 1);
Session ses= factory.openSession();
List lstUserUpdates= ses.createCriteria(UserConfirmUpdate.class)
.add(Restrictions.between("timelimit", cal.getTime(), calEnd.getTime()))
.add(Restrictions.eq("updated", Boolean.FALSE))
.list();
for(UserConfirmUpdate ucu: (List<UserConfirmUpdate>) lstUserUpdates){
UserRequest ur= LDAPUtils.getUser(ucu.getUsername());
sendUserRemainder(ur, days);
}
ses.close();
}
private void stopUsers(){
_log.info("Disable users who do not confirm the account extension");
Session session = factory.openSession();
session.beginTransaction();
Calendar cal= GregorianCalendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar calEnd= GregorianCalendar.getInstance();
calEnd.setTime(cal.getTime());
calEnd.add(Calendar.DAY_OF_YEAR, 1);
Session ses= factory.openSession();
List lstUserUpdates= ses.createCriteria(UserConfirmUpdate.class)
.add(Restrictions.between("timelimit", cal.getTime(), calEnd.getTime()))
.add(Restrictions.eq("updated", Boolean.FALSE))
.list();
for(UserConfirmUpdate ucu: (List<UserConfirmUpdate>) lstUserUpdates){
UserRequest ur= LDAPUtils.getUser(ucu.getUsername());
LDAPUtils.disableUser(ucu.getUsername());
sendUserRemainder(ur, 0);
}
ses.close();
session.getTransaction().commit();
session.close();
}
private void sendUserRemainder(UserRequest ur, int days){
javax.mail.Session session=null;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
session = (javax.mail.Session) envCtx.lookup("mail/Users");
Message mailMsg = new MimeMessage(session);
mailMsg.setFrom(new InternetAddress(rb.getString("mailSender"),rb.getString("IdPAdmin")));
InternetAddress mailTo[] = new InternetAddress[1];
mailTo[0] = new InternetAddress(getGoodMail(ur), ur.getTitle()+" "+ur.getGivenname()+" "+ur.getSurname());
mailMsg.setRecipients(Message.RecipientType.TO, mailTo);
if(rb.containsKey("mailCopy") && !rb.getString("mailCopy").isEmpty()){
String ccMail[] = rb.getString("mailCopy").split(";");
InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
for(int i=0; i<ccMail.length;i++) {
mailCCopy[i] = new InternetAddress(ccMail[i]);
}
mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy);
}
if(days>0){
mailMsg.setSubject(rb.getString("mailNotificationSubject").replace("_DAYS_", Integer.toString(days)));
mailMsg.setText(rb.getString("mailNotificationBody").replaceAll("_USER_", ur.getTitle()+" "+ur.getGivenname()+" "+ur.getSurname()).replace("_DAYS_", Integer.toString(days)));
}
else{
mailMsg.setSubject(rb.getString("mailDeleteSubject").replace("_DAYS_", Integer.toString(days)));
mailMsg.setText(rb.getString("mailDeleteBody").replaceAll("_USER_", ur.getTitle()+" "+ur.getGivenname()+" "+ur.getSurname()).replace("_DAYS_", Integer.toString(days)));
}
Transport.send(mailMsg);
} catch (Exception ex) {
_log.error("Mail resource lookup error");
_log.error(ex.getMessage());
}
}
private String getGoodMail(UserRequest ur) throws MailException{
String mail= ur.getPreferredMail();
if(rb.containsKey("mailFilter") && !rb.getString("mailFilter").isEmpty()){
for(String filter: rb.getString("mailFilter").split(",")){
if(mail.contains(filter)){
throw new MailException("Preferred mail from filtered provider");
}
}
}
return mail;
}
}
| apache-2.0 |
brendandouglas/intellij | base/src/com/google/idea/blaze/base/lang/buildfile/formatting/BuildBraceMatcher.java | 2599 | /*
* Copyright 2016 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.base.lang.buildfile.formatting;
import com.google.idea.blaze.base.lang.buildfile.lexer.BuildToken;
import com.google.idea.blaze.base.lang.buildfile.lexer.TokenKind;
import com.intellij.lang.BracePair;
import com.intellij.lang.PairedBraceMatcher;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import java.util.Arrays;
import javax.annotation.Nullable;
/**
* This adds a close brace automatically once an opening brace is typed by the user in the editor.
*/
public class BuildBraceMatcher implements PairedBraceMatcher {
private static final BracePair[] PAIRS =
new BracePair[] {
new BracePair(
BuildToken.fromKind(TokenKind.LPAREN), BuildToken.fromKind(TokenKind.RPAREN), true),
new BracePair(
BuildToken.fromKind(TokenKind.LBRACKET), BuildToken.fromKind(TokenKind.RBRACKET), true),
new BracePair(
BuildToken.fromKind(TokenKind.LBRACE), BuildToken.fromKind(TokenKind.RBRACE), true)
};
private static final TokenSet BRACES_ALLOWED_BEFORE =
tokenSet(
TokenKind.NEWLINE,
TokenKind.WHITESPACE,
TokenKind.COMMENT,
TokenKind.COLON,
TokenKind.COMMA,
TokenKind.RPAREN,
TokenKind.RBRACKET,
TokenKind.RBRACE,
TokenKind.LBRACE);
@Override
public BracePair[] getPairs() {
return PAIRS;
}
@Override
public boolean isPairedBracesAllowedBeforeType(
IElementType lbraceType, @Nullable IElementType contextType) {
return contextType == null || BRACES_ALLOWED_BEFORE.contains(contextType);
}
@Override
public int getCodeConstructStart(PsiFile file, int openingBraceOffset) {
return openingBraceOffset;
}
private static TokenSet tokenSet(TokenKind... kind) {
return TokenSet.create(
Arrays.stream(kind).map(BuildToken::fromKind).toArray(IElementType[]::new));
}
}
| apache-2.0 |
papicella/snappy-store | gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/VersionedThinRegionEntryOffHeap.java | 9792 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal.cache;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import com.gemstone.gemfire.internal.concurrent.AtomicUpdaterFactory;
import com.gemstone.gemfire.internal.offheap.OffHeapRegionEntryHelper;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.offheap.annotations.Retained;
import com.gemstone.gemfire.internal.offheap.annotations.Unretained;
import com.gemstone.gemfire.cache.EntryEvent;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
import com.gemstone.gemfire.internal.cache.versions.VersionSource;
import com.gemstone.gemfire.internal.cache.versions.VersionStamp;
import com.gemstone.gemfire.internal.cache.versions.VersionTag;
import com.gemstone.gemfire.internal.concurrent.CustomEntryConcurrentHashMap.HashEntry;
// macros whose definition changes this class:
// disk: DISK
// lru: LRU
// stats: STATS
// versioned: VERSIONED
// offheap: OFFHEAP
// rowlocation: ROWLOCATION
// local: LOCAL
// bucket: BUCKET
// package: PKG
/**
* Do not modify this class. It was generated.
* Instead modify LeafRegionEntry.cpp and then run
* bin/generateRegionEntryClasses.sh from the directory
* that contains your build.xml.
*/
@SuppressWarnings("serial")
public class VersionedThinRegionEntryOffHeap extends VMThinRegionEntry
implements OffHeapRegionEntry, VersionStamp
{
public VersionedThinRegionEntryOffHeap (RegionEntryContext context, Object key,
@Retained
Object value
) {
super(context,
value
);
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
this.key = key;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// common code
protected int hash;
private HashEntry<Object, Object> next;
@SuppressWarnings("unused")
private volatile long lastModified;
private static final AtomicLongFieldUpdater<VersionedThinRegionEntryOffHeap> lastModifiedUpdater
= AtomicUpdaterFactory.newLongFieldUpdater(VersionedThinRegionEntryOffHeap.class, "lastModified");
protected long getlastModifiedField() {
return lastModifiedUpdater.get(this);
}
protected boolean compareAndSetLastModifiedField(long expectedValue, long newValue) {
return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
}
/**
* @see HashEntry#getEntryHash()
*/
@Override
public final int getEntryHash() {
return this.hash;
}
@Override
protected void setEntryHash(int v) {
this.hash = v;
}
/**
* @see HashEntry#getNextEntry()
*/
@Override
public final HashEntry<Object, Object> getNextEntry() {
return this.next;
}
/**
* @see HashEntry#setNextEntry
*/
@Override
public final void setNextEntry(final HashEntry<Object, Object> n) {
this.next = n;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// versioned code
private VersionSource memberID;
private short entryVersionLowBytes;
private short regionVersionHighBytes;
private int regionVersionLowBytes;
private byte entryVersionHighByte;
private byte distributedSystemId;
public int getEntryVersion() {
return ((entryVersionHighByte << 16) & 0xFF0000) | (entryVersionLowBytes & 0xFFFF);
}
public long getRegionVersion() {
return (((long)regionVersionHighBytes) << 32) | (regionVersionLowBytes & 0x00000000FFFFFFFFL);
}
public long getVersionTimeStamp() {
return getLastModified();
}
public void setVersionTimeStamp(long time) {
setLastModified(time);
}
public VersionSource getMemberID() {
return this.memberID;
}
public int getDistributedSystemId() {
return this.distributedSystemId;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
public void setVersions(VersionTag tag) {
this.memberID = tag.getMemberID();
int eVersion = tag.getEntryVersion();
this.entryVersionLowBytes = (short)(eVersion & 0xffff);
this.entryVersionHighByte = (byte)((eVersion & 0xff0000) >> 16);
this.regionVersionHighBytes = tag.getRegionVersionHighBytes();
this.regionVersionLowBytes = tag.getRegionVersionLowBytes();
if (!(tag.isGatewayTag()) && this.distributedSystemId == tag.getDistributedSystemId()) {
if (getVersionTimeStamp() <= tag.getVersionTimeStamp()) {
setVersionTimeStamp(tag.getVersionTimeStamp());
} else {
tag.setVersionTimeStamp(getVersionTimeStamp());
}
} else {
setVersionTimeStamp(tag.getVersionTimeStamp());
}
this.distributedSystemId = (byte)(tag.getDistributedSystemId() & 0xff);
}
public void setMemberID(VersionSource memberID) {
this.memberID = memberID;
}
@Override
public VersionStamp getVersionStamp() {
return this;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
public VersionTag asVersionTag() {
VersionTag tag = VersionTag.create(memberID);
tag.setEntryVersion(getEntryVersion());
tag.setRegionVersion(this.regionVersionHighBytes, this.regionVersionLowBytes);
tag.setVersionTimeStamp(getVersionTimeStamp());
tag.setDistributedSystemId(this.distributedSystemId);
return tag;
}
public void processVersionTag(LocalRegion r, VersionTag tag,
boolean isTombstoneFromGII, boolean hasDelta,
VersionSource thisVM, InternalDistributedMember sender, boolean checkForConflicts) {
basicProcessVersionTag(r, tag, isTombstoneFromGII, hasDelta, thisVM, sender, checkForConflicts);
}
@Override
public void processVersionTag(EntryEvent cacheEvent) {
// this keeps Eclipse happy. without it the sender chain becomes confused
// while browsing this code
super.processVersionTag(cacheEvent);
}
/** get rvv internal high byte. Used by region entries for transferring to storage */
public short getRegionVersionHighBytes() {
return this.regionVersionHighBytes;
}
/** get rvv internal low bytes. Used by region entries for transferring to storage */
public int getRegionVersionLowBytes() {
return this.regionVersionLowBytes;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// key code
private Object key;
@Override
public final Object getRawKey() {
return this.key;
}
@Override
protected void _setRawKey(Object key) {
this.key = key;
}
/**
* All access done using ohAddrUpdater so it is used even though the compiler can not tell it is.
*/
@Retained @Released private volatile long ohAddress;
/**
* I needed to add this because I wanted clear to call setValue which normally can only be called while the re is synced.
* But if I sync in that code it causes a lock ordering deadlock with the disk regions because they also get a rw lock in clear.
* Some hardware platforms do not support CAS on a long. If gemfire is run on one of those the AtomicLongFieldUpdater does a sync
* on the re and we will once again be deadlocked.
* I don't know if we support any of the hardware platforms that do not have a 64bit CAS. If we do then we can expect deadlocks
* on disk regions.
*/
private final static AtomicLongFieldUpdater<VersionedThinRegionEntryOffHeap> ohAddrUpdater =
AtomicUpdaterFactory.newLongFieldUpdater(VersionedThinRegionEntryOffHeap.class, "ohAddress");
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
@Override
public Token getValueAsToken() {
return OffHeapRegionEntryHelper.getValueAsToken(this);
}
@Override
@Unretained
protected Object getValueField() {
return OffHeapRegionEntryHelper._getValue(this);
}
@Override
protected void setValueField(@Unretained Object v) {
OffHeapRegionEntryHelper.setValue(this, v);
}
@Override
@Retained
public Object _getValueRetain(RegionEntryContext context, boolean decompress) {
return OffHeapRegionEntryHelper._getValueRetain(this, decompress);
}
@Override
public long getAddress() {
return ohAddrUpdater.get(this);
}
@Override
public boolean setAddress(long expectedAddr, long newAddr) {
return ohAddrUpdater.compareAndSet(this, expectedAddr, newAddr);
}
@Override
@Released
public void release() {
OffHeapRegionEntryHelper.releaseEntry(this);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
private static RegionEntryFactory factory = new RegionEntryFactory() {
public final RegionEntry createEntry(RegionEntryContext context, Object key, Object value) {
return new VersionedThinRegionEntryOffHeap(context, key, value);
}
public final Class<?> getEntryClass() {
return VersionedThinRegionEntryOffHeap.class;
}
public RegionEntryFactory makeVersioned() {
return this;
}
@Override
public RegionEntryFactory makeOnHeap() {
return VersionedThinRegionEntryHeap.getEntryFactory();
}
};
public static RegionEntryFactory getEntryFactory() {
return factory;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
}
| apache-2.0 |
electricalwind/greycat | plugins/ml/src/main/java/greycat/ml/preprocessing/AttributeNode.java | 6850 | /**
* Copyright 2017 The GreyCat Authors. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 greycat.ml.preprocessing;
import greycat.Callback;
import greycat.Graph;
import greycat.Node;
import greycat.Type;
import greycat.base.BaseNode;
import greycat.plugin.NodeState;
public class AttributeNode extends BaseNode {
public final static String NAME = "AttributeNode";
public static final String VALUE = "value"; //ToDo move value to a subnode
public static final String VALID_VALUE = "valid_value";
public static final String IS_VALID = "is_valid";
public static final String EXTRAPOLATE = "extrapolate";
//To set the business logic - tolerated min, max
public static final String MIN_TOLERATED = "min_tol";
public static final String MAX_TOLERATED = "max_tol";
public static final String MIN_OBSERVED = "min_obs";
public static final String MAX_OBSERVED = "max_obs";
public static final String MIN_VALID = "min_val";
public static final String MAX_VALID = "max_val";
public static final String AVG = "avg";
public static final String SIGMA = "sigma";
public static final String TOTAL = "total";
public static final String TOTAL_VALID = "total_val";
private static final String INTERNAL_SUM_KEY = "_sum";
private static final String INTERNAL_SUMSQUARE_KEY = "_sumSquare";
private final static String NOT_MANAGED_ATT_ERROR = "Attribute node can only handle value attribute, please use a super node to store other data";
public AttributeNode(long p_world, long p_time, long p_id, Graph p_graph) {
super(p_world, p_time, p_id, p_graph);
}
//Override default Abstract node default setters and getters
@Override
public Node set(String propertyName, int propertyType, Object propertyValue) {
if (propertyName.equals(VALUE)) {
internalSet(Double.parseDouble(propertyValue.toString()), null);
} else if (propertyName.equals(MIN_TOLERATED)) {
super.set(MIN_TOLERATED, Type.DOUBLE, propertyValue);
} else if (propertyName.equals(MAX_TOLERATED)) {
super.set(MAX_TOLERATED, Type.DOUBLE, propertyValue);
} else if (propertyName.equals(EXTRAPOLATE)) {
super.set(EXTRAPOLATE, Type.BOOL, propertyValue);
} else {
throw new RuntimeException(NOT_MANAGED_ATT_ERROR);
}
return this;
}
@Override
public Object get(String propertyName) {
switch (propertyName) {
case VALUE:
return getValue();
case VALID_VALUE:
return getValidValue();
case IS_VALID:
return super.get(propertyName);
case AVG:
return getAvg();
case SIGMA:
return getSigma();
default:
return super.get(propertyName);
}
}
private Double getValue() {
return 0.0; //ToDo not implemented yet should take a callback
}
private Double getValidValue() {
return 0.0; //ToDo not implemented yet should take a callback
}
private Double getAvg() {
NodeState state = phasedState();
long totalVal = state.getWithDefault(TOTAL_VALID, 0);
if (totalVal == 0) {
return null;
} else {
Double v = state.getWithDefault(INTERNAL_SUM_KEY, 0.0);
return v / totalVal;
}
}
private Double getSigma() {
NodeState state = phasedState();
long totalVal = state.getWithDefault(TOTAL_VALID, 0);
if (totalVal < 1) {
return null;
} else {
double avg = state.getWithDefault(INTERNAL_SUM_KEY, 0);
avg = avg / totalVal;
double correction = totalVal;
correction = correction / (totalVal - 1);
double sumsq = state.getWithDefault(INTERNAL_SUMSQUARE_KEY, 0.0);
double cov = (sumsq / totalVal - avg * avg) * correction;
return Math.sqrt(cov);
}
}
private boolean checkValid(double v, Double min, Double max) {
boolean res = true;
if (min != null) {
res = res && (v >= min);
}
if (max != null) {
res = res && (v <= max);
}
return res;
}
//Return the validity state of the set
private void internalSet(double v, Callback<Boolean> callback) {
//Get the phase state now
NodeState state = phasedState();
//Set the value whatever it is
state.set(VALUE, Type.DOUBLE, v); //ToDo set on another subnode
//Check the total and uptade min max for the first time
long total = state.getWithDefault(TOTAL, 0);
if (total == 0) {
state.set(MIN_OBSERVED, Type.DOUBLE, v);
state.set(MAX_OBSERVED, Type.DOUBLE, v);
}
state.set(TOTAL, Type.LONG, total + 1);
//Get tolerated bound
Double mintol = state.getWithDefault(MIN_TOLERATED, null);
Double maxtol = state.getWithDefault(MAX_TOLERATED, null);
Double minval = state.getWithDefault(MIN_VALID, null);
Double maxval = state.getWithDefault(MAX_VALID, null);
//Check validity of the current insert
boolean valid = checkValid(v, mintol, maxtol);
state.set(IS_VALID, Type.BOOL, valid);
if (valid) {
//Update min, max valid
if (minval == null || v < minval) {
state.set(MIN_VALID, Type.DOUBLE, v);
}
if (maxval == null || v > maxval) {
state.set(MAX_VALID, Type.DOUBLE, v);
}
//Update statistics:
double internalSum = state.getWithDefault(INTERNAL_SUM_KEY, 0);
internalSum += v;
state.set(INTERNAL_SUM_KEY, Type.DOUBLE, internalSum);
double internalSumSq = state.getWithDefault(INTERNAL_SUMSQUARE_KEY, 0);
internalSumSq += v * v;
state.set(INTERNAL_SUMSQUARE_KEY, Type.DOUBLE, internalSumSq);
long totalval = state.getWithDefault(TOTAL_VALID, 0);
totalval++;
state.set(TOTAL_VALID, Type.LONG, totalval);
}
if (callback != null) {
callback.on(valid);
}
}
}
| apache-2.0 |
Esri/performance-test-harness-for-geoevent | performance-test-harness-api/src/main/java/com/esri/geoevent/test/performance/jaxb/Report.java | 3422 | /*
Copyright 1995-2015 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, contact:
Environmental Systems Research Institute, Inc.
Attn: Contracts Dept
380 New York Street
Redlands, California, USA 92373
email: contracts@esri.com
*/
package com.esri.geoevent.test.performance.jaxb;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.esri.geoevent.test.performance.report.ReportType;
@XmlRootElement(name = "Report")
public class Report
{
private ReportType type;
private String reportFile;
private int maxNumberOfReportFiles = 10;
private List<String> reportColumns;
private List<String> additionalReportColumns;
@XmlAttribute
public ReportType getType()
{
return type;
}
public void setType(ReportType type)
{
this.type = type;
}
@XmlElement(name = "ReportFile")
public String getReportFile()
{
return reportFile;
}
public void setReportFile(String reportFile)
{
this.reportFile = reportFile;
}
@XmlAttribute(name = "maxNumberOfReportFiles")
public int getMaxNumberOfReportFiles()
{
return maxNumberOfReportFiles;
}
public void setMaxNumberOfReportFiles(int maxNumberOfReportFiles)
{
this.maxNumberOfReportFiles = maxNumberOfReportFiles;
}
@XmlList
@XmlElement(name = "ReportColumns", required=false)
public List<String> getReportColumns()
{
return reportColumns;
}
public void setReportColumns(List<String> reportColumns)
{
this.reportColumns = reportColumns;
}
@XmlList
@XmlElement(name="AdditionalReportColumns", required = false)
public List<String> getAdditionalReportColumns()
{
return additionalReportColumns;
}
public void setAdditionalReportColumns(List<String> additionalReportColumns)
{
this.additionalReportColumns = additionalReportColumns;
}
@Override
public boolean equals(Object obj)
{
if (obj == null || !(obj instanceof Report))
return false;
Report report = (Report) obj;
if (!ObjectUtils.equals(getMaxNumberOfReportFiles(), report.getMaxNumberOfReportFiles()))
return false;
if (!ObjectUtils.equals(getReportFile(), report.getReportFile()))
return false;
if (!ObjectUtils.equals(getType(), report.getType()))
return false;
if (!ObjectUtils.equals(getReportColumns(), report.getReportColumns()))
return false;
if (!ObjectUtils.equals(getAdditionalReportColumns(), report.getAdditionalReportColumns()))
return false;
return true;
}
@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
| apache-2.0 |
paulbrodner/SeLion | client/src/test/java/com/paypal/selion/platform/html/LabelTest.java | 2941 | /*-------------------------------------------------------------------------------------------------------------------*\
| Copyright (C) 2014 PayPal |
| |
| 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.paypal.selion.platform.html;
import static com.paypal.selion.platform.asserts.SeLionAsserts.assertEquals;
import static com.paypal.selion.platform.asserts.SeLionAsserts.assertTrue;
import org.testng.annotations.Test;
import com.paypal.selion.TestServerUtils;
import com.paypal.selion.annotations.WebTest;
import com.paypal.selion.platform.grid.Grid;
/**
* This class test the Label class methods
*/
public class LabelTest {
Label editableTestField = new Label(TestObjectRepository.LABEL_EDITABLE.getValue());
Label testLabel2 = new Label(TestObjectRepository.LABEL_EDITABLE.getValue(), "normal_text");
@Test(groups = { "browser-tests" })
@WebTest
public void testLabel() {
Grid.driver().get(TestServerUtils.getTestEditableURL());
assertTrue(editableTestField.isTextPresent("Editable text-field"), "Validated isTextPresent method");
}
@Test(groups = { "browser-tests" })
@WebTest
public void testLabel2() {
Grid.driver().get(TestServerUtils.getTestEditableURL());
assertTrue(testLabel2.isTextPresent("Editable text-field"), "Validated isTextPresent method");
assertEquals(testLabel2.getControlName(), "normal_text", "Validated isTextPresent method");
}
}
| apache-2.0 |
bernardator/cts2-framework | cts2-webapp/src/main/java/edu/mayo/cts2/framework/webapp/soap/wsdl/LocationAdjustingWsdlDefinitionHandlerAdapter.java | 854 | package edu.mayo.cts2.framework.webapp.soap.wsdl;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.ws.transport.http.WsdlDefinitionHandlerAdapter;
import edu.mayo.cts2.framework.core.config.ServerContext;
public class LocationAdjustingWsdlDefinitionHandlerAdapter extends WsdlDefinitionHandlerAdapter {
private static final String SOAP_URL_PREFIX = "/soap/service/";
@Resource
private ServerContext serverContext;
@Override
protected String transformLocation(String location, HttpServletRequest request) {
return this.serverContext.getServerRootWithAppName() +
SOAP_URL_PREFIX +
this.getServiceName(location);
}
private String getServiceName(String location){
return StringUtils.substringAfterLast(location, "/");
}
}
| apache-2.0 |
USEF-Foundation/ri.usef.energy | usef-build/usef-core/usef-core-transport/src/main/java/energy/usef/core/service/helper/DispatcherHelperService.java | 3493 | /*
* Copyright 2015-2016 USEF 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 energy.usef.core.service.helper;
import energy.usef.core.controller.DefaultIncomingMessageController;
import energy.usef.core.controller.IncomingMessageController;
import energy.usef.core.controller.factory.IncomingControllerClassFactory;
import energy.usef.core.data.xml.bean.message.Message;
import energy.usef.core.exception.BusinessException;
import energy.usef.core.service.business.error.MessageControllerError;
import energy.usef.core.util.XMLUtil;
import java.util.Iterator;
import javax.ejb.Stateless;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This service is designed to route incoming XML messages to corresponding controllers for processing.
*/
@Stateless
public class DispatcherHelperService {
private static final Logger LOGGER = LoggerFactory.getLogger(DispatcherHelperService.class);
@Inject
private BeanManager beanManager;
@Inject
private DefaultIncomingMessageController defaultIncomingMessageController;
/**
* The method routes an incoming message to a corresponding controller and invokes a required action.
*
* @param xml xml message
* @throws BusinessException
*/
public void dispatch(String xml) throws BusinessException {
// transform
Object xmlObject = XMLUtil.xmlToMessage(xml);
if (!(xmlObject instanceof Message)) {
throw new BusinessException(MessageControllerError.XML_NOT_CONVERTED_TO_OBJECT);
}
process(xml, (Message) xmlObject);
}
private void process(String xml, Message message) throws BusinessException {
IncomingMessageController<Message> controller = null;
Class<?> controllerClass = IncomingControllerClassFactory.getControllerClass(message.getClass());
controller = getController(controllerClass);
if (controller == null) {
LOGGER.error("No controller is found for the message of type: {}, default controller will be used", message.getClass());
controller = defaultIncomingMessageController;
}
// process the message
controller.execute(xml, message);
}
@SuppressWarnings("unchecked")
private IncomingMessageController<Message> getController(Class<?> clazz) {
if (clazz == null) {
return null;
}
Iterator<Bean<?>> iterator = beanManager.getBeans(clazz).iterator();
if (iterator.hasNext()) {
Bean<?> bean = iterator.next();
CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
return (IncomingMessageController<Message>) beanManager.getReference(bean, clazz, creationalContext);
}
return null;
}
}
| apache-2.0 |
lhong375/aura | aura-integration-test/src/test/java/org/auraframework/test/AuraJettyServer.java | 2951 | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.test;
import java.io.File;
import org.auraframework.Aura;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;
import org.openqa.selenium.net.PortProber;
/**
* A Jetty server configured with default Aura descriptor and resources.
*
*
* @since 0.0.302
*/
public class AuraJettyServer extends Server {
private static Server instance = null;
public static Server getInstance() {
if (instance == null) {
String possiblePort = System.getProperty("jetty.port");
int port;
try {
port = Integer.parseInt(possiblePort);
} catch (Throwable t) {
port = PortProber.findFreePort();
}
String host = System.getProperty("jetty.host");
instance = new AuraJettyServer(host, port, "/");
}
return instance;
}
private AuraJettyServer(String host, int port, String contextPath) {
String tmpPath = System.getProperty("java.io.tmpdir") + "/webapp";
File tmpDir = new File(tmpPath);
if (!tmpDir.exists()) {
tmpDir.mkdirs();
tmpDir.deleteOnExit();
}
Connector connector = new SelectChannelConnector();
if (host != null) {
connector.setHost(host);
}
connector.setPort(port);
setConnectors(new Connector[] { connector });
WebAppContext context = new WebAppContext();
context.setDefaultsDescriptor(Aura.class.getResource("/aura/http/WEB-INF/webdefault.xml").toString());
context.setDescriptor(Aura.class.getResource("/aura/http/WEB-INF/web.xml").toString());
context.setContextPath(contextPath);
context.setParentLoaderPriority(true);
context.setTempDirectory(tmpDir);
String resources = System.getProperty("jetty.resources",
AuraJettyServer.class.getResource("/org/auraframework/test").toString());
context.setResourceBase(resources);
setHandler(context);
}
public static void main(String... args) throws Exception {
Server server = AuraJettyServer.getInstance();
server.start();
server.join();
}
}
| apache-2.0 |
smulikHakipod/zb4osgi | zb4o-ha-driver/src/main/java/it/cnr/isti/zigbee/ha/device/api/generic/LevelControllableOutput.java | 2692 | /*
Copyright 2013-2014 CNR-ISTI, http://isti.cnr.it
Institute of Information Science and Technologies
of the Italian National Research Council
See the NOTICE file distributed with this work for additional
information regarding copyright ownership
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 it.cnr.isti.zigbee.ha.device.api.generic;
import it.cnr.isti.zigbee.ha.cluster.glue.general.Groups;
import it.cnr.isti.zigbee.ha.cluster.glue.general.LevelControl;
import it.cnr.isti.zigbee.ha.cluster.glue.general.OnOff;
import it.cnr.isti.zigbee.ha.cluster.glue.general.Scenes;
import it.cnr.isti.zigbee.ha.driver.ArraysUtil;
import it.cnr.isti.zigbee.ha.driver.core.HADevice;
import it.cnr.isti.zigbee.ha.driver.core.HAProfile;
/**
* @author <a href="mailto:stefano.lenzi@isti.cnr.it">Stefano "Kismet" Lenzi</a>
* @version $LastChangedRevision$ ($LastChangedDate$)
* @since 0.7.0
*
*/
public interface LevelControllableOutput extends HADevice {
public static final int DEVICE_ID = 0x0003;
public static final String NAME = "Level Controllable Output";
public static final int[] MANDATORY = ArraysUtil.append( HADevice.MANDATORY, new int[] {
HAProfile.ON_OFF, HAProfile.LEVEL_CONTROL, HAProfile.SCENES, HAProfile.GROUPS
} );
public static final int[] OPTIONAL = HADevice.OPTIONAL;
public static final int[] STANDARD = ArraysUtil.append(MANDATORY, OPTIONAL);
public static final int[] CUSTOM = {};
/**
* Access method for the <b>Mandatory</b> cluster: {@link OnOff}
*
* @return the {@link OnOff} cluster object
*/
public OnOff getOnOff();
/**
* Access method for the <b>Mandatory</b> cluster: {@link LevelControl}
*
* @return the {@link LevelControl} cluster object
*/
public LevelControl getLevelControl();
/**
* Access method for the <b>Mandatory</b> cluster: {@link Scenes}
*
* @return the {@link Scenes} cluster object
*/
public Scenes getScenes();
/**
* Access method for the <b>Mandatory</b> cluster: {@link Groups}
*
* @return the {@link Groups} cluster object
*/
public Groups getGroups();
}
| apache-2.0 |
alfishe/Rythm | src/test/java/org/rythmengine/advanced/TransformerTest.java | 6587 | /*
* Copyright (C) 2013 The Rythm Engine project
* Gelin Luo <greenlaw110(at)gmail.com>
*
* 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.rythmengine.advanced;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Test;
import org.rythmengine.Rythm;
import org.rythmengine.TestBase;
import org.rythmengine.conf.RythmConfigurationKey;
import org.rythmengine.extension.Transformer;
import org.rythmengine.utils.S;
import java.util.*;
@Transformer
public class TransformerTest extends TestBase {
public static Integer dbl(Integer i) {
return i * 2;
}
public static String dbl(String s) {
if (null == s) return "";
return s + s;
}
public static String dbl(Object o) {
if (null == o) return "";
return dbl(o.toString());
}
@Test
public void testBuiltInTranformers() {
System.setProperty("feature.type_inference.enabled", "true");
Rythm.shutdown();
String p;
// raw
p = "<h1>h1</h1>";
s = Rythm.render("@1.raw()", p);
eq(p);
// escape
s = Rythm.render("<script>alert('@1.escape()' + x);</script>", "xyz,'abc'");
eq("<script>alert('xyz,\'abc\'' + x);</script>");
String[] sa = "json,xml,javascript,html,csv,raw".split(",");
for (String escape : sa) {
System.err.println(escape);
s = Rythm.render(String.format("@1.escape(\"%s\")", escape), p);
assertEquals(S.escape(p, escape).toString(), s);
}
// lowerFirst
p = "FOO BAR";
s = Rythm.render("@1.lowerFirst()", p);
assertEquals("fOO BAR", s);
// capFirst
p = "foo bar";
s = Rythm.render("@1.capFirst()", p);
assertEquals("Foo bar", s);
// camelCase
p = "foo_bar zee";
s = Rythm.render("@1.camelCase()", p);
assertEquals("FooBar Zee", s);
// format date
Date d = new Date();
s = Rythm.render("@1.format(\"dd/MM/yyyy\")", d);
assertEquals(S.format(d, "dd/MM/yyyy"), s);
s = Rythm.render("@1.format()", d);
eq(S.format(d));
//format number
Number n = 113432.33;
s = r("@1.format()", n);
eq(S.format(n));
System.out.println(s);
n = .03;
String np = "#,###,###,000.00";
s = r("@1.format(@2)", n, np);
eq(S.format(n, np));
System.out.println(s);
// format currency
s = Rythm.render("@1.formatCurrency()", 100000/100);
eq(S.formatCurrency("1000.00"));
s = Rythm.render("@args int x;@s().formatCurrency(x)", 100000/100);
eq(S.formatCurrency("1000.00"));
// eq
s = Rythm.render("@1.eq(@2)", "a", "b");
eq("false");
s = Rythm.render("@1.eq(@2)", "a", "a");
eq("true");
s = Rythm.render("@1.eq(@2)", 1, 3);
eq("false");
s = Rythm.render("@1.eq(@2)", 1, 1);
eq("true");
s = Rythm.render("@1.eq(@2)", null, null);
eq("true");
// format joda date time
DateTime dt = new DateTime();
s = r("@1.format(\"dd/MM/yyyy hh:mm\")", dt);
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy hh:mm");
eq(fmt.print(dt));
System.out.println(s);
}
@Test
public void testJoin() {
System.setProperty("feature.type_inference.enabled", "true");
Rythm.shutdown();
List l = Arrays.asList(new Integer[]{1, 2, 3});
s = r("@1.join()", l);
eq("1,2,3");
s = r("@1.join(\";\")", l);
eq("1;2;3");
s = r("@1.join(':')", l);
eq("1:2:3");
}
@Test
public void testUserDefinedTransformer() {
Rythm.engine().registerTransformer(TransformerTest.class);
String t = "@args String s, int i\n" +
"double of \"@s\" is \"@s.app_dbl()\",\n " +
"double of [@i] is [@i.app_dbl().format(\"0000.00\")]";
String s = Rythm.render(t, "Java", 99);
assertContains(s, "double of \"Java\" is \"JavaJava\"");
//assertContains(s, "double of [99] is [0198.00]");
assertContains(s, "double of [99] is [" + S.format(dbl(99), "0000.00") + "]");
}
@Test
public void testUserDefinedTransformerWithNamespace() {
// test register with namespace specified
Rythm.engine().registerTransformer("foo", "", TransformerTest.class);
String t = "@args String s, int i\n" +
"double of \"@s\" is \"@s.foo_dbl()\",\n " +
"double of [@i] is [@i.foo_dbl().format(\"0000.00\")]";
String s = Rythm.render(t, "Java", 99);
assertContains(s, "double of \"Java\" is \"JavaJava\"");
//assertContains(s, "double of [99] is [0198.00]");
assertContains(s, "double of [99] is [" + S.format(dbl(99), "0000.00") + "]");
}
@Test
public void testTransformerConf() {
Map<String, Object> conf = new HashMap<String, Object>();
conf.put(RythmConfigurationKey.EXT_TRANSFORMER_IMPLS.getKey(), "org.rythmengine.advanced.TransformerTest");
Rythm.init(conf);
String t = "@args String s, int i\n" +
"double of \"@s\" is \"@s.app_dbl()\",\n " +
"double of [@i] is [@i.app_dbl().format(\"0000.00\")]";
String s = Rythm.render(t, "Java", 99);
assertContains(s, "double of \"Java\" is \"JavaJava\"");
//assertContains(s, "double of [99] is [0198.00]");
assertContains(s, "double of [99] is [" + S.format(dbl(99), "0000.00") + "]");
}
public static void main(String[] args) {
run(TransformerTest.class);
}
}
| apache-2.0 |
lstav/accumulo | core/src/main/java/org/apache/accumulo/core/util/LocalityGroupUtil.java | 13383 | /*
* 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.accumulo.core.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.ConfigurationCopy;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.ArrayByteSequence;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Column;
import org.apache.accumulo.core.data.ColumnUpdate;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.dataImpl.thrift.TMutation;
import org.apache.accumulo.core.file.FileSKVIterator;
import org.apache.accumulo.core.file.rfile.RFile.Reader;
import org.apache.commons.lang3.mutable.MutableLong;
import org.apache.hadoop.io.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
public class LocalityGroupUtil {
private static final Logger log = LoggerFactory.getLogger(LocalityGroupUtil.class);
// using an ImmutableSet here for more efficient comparisons in LocalityGroupIterator
public static final Set<ByteSequence> EMPTY_CF_SET = Set.of();
/**
* Create a set of families to be passed into the SortedKeyValueIterator seek call from a supplied
* set of columns. We are using the ImmutableSet to enable faster comparisons down in the
* LocalityGroupIterator.
*
* @param columns
* The set of columns
* @return An immutable set of columns
*/
public static Set<ByteSequence> families(Collection<Column> columns) {
if (columns.size() == 0) {
return EMPTY_CF_SET;
}
var builder = ImmutableSet.<ByteSequence>builder();
columns.forEach(c -> builder.add(new ArrayByteSequence(c.getColumnFamily())));
return builder.build();
}
@SuppressWarnings("serial")
public static class LocalityGroupConfigurationError extends AccumuloException {
LocalityGroupConfigurationError(String why) {
super(why);
}
}
public static boolean isLocalityGroupProperty(String prop) {
return prop.startsWith(Property.TABLE_LOCALITY_GROUP_PREFIX.getKey())
|| prop.equals(Property.TABLE_LOCALITY_GROUPS.getKey());
}
public static void checkLocalityGroups(Iterable<Entry<String,String>> config)
throws LocalityGroupConfigurationError {
ConfigurationCopy cc = new ConfigurationCopy(config);
if (cc.get(Property.TABLE_LOCALITY_GROUPS) != null) {
getLocalityGroups(cc);
}
}
public static Map<String,Set<ByteSequence>>
getLocalityGroupsIgnoringErrors(AccumuloConfiguration acuconf, TableId tableId) {
try {
return getLocalityGroups(acuconf);
} catch (LocalityGroupConfigurationError | RuntimeException e) {
log.warn("Failed to get locality group config for tableId:" + tableId
+ ", proceeding without locality groups.", e);
}
return Collections.emptyMap();
}
public static Map<String,Set<ByteSequence>> getLocalityGroups(AccumuloConfiguration acuconf)
throws LocalityGroupConfigurationError {
Map<String,Set<ByteSequence>> result = new HashMap<>();
String[] groups = acuconf.get(Property.TABLE_LOCALITY_GROUPS).split(",");
for (String group : groups) {
if (group.length() > 0) {
result.put(group, new HashSet<>());
}
}
HashSet<ByteSequence> all = new HashSet<>();
for (Entry<String,String> entry : acuconf) {
String property = entry.getKey();
String value = entry.getValue();
String prefix = Property.TABLE_LOCALITY_GROUP_PREFIX.getKey();
if (property.startsWith(prefix)) {
// this property configures a locality group, find out which one:
String group = property.substring(prefix.length());
String[] parts = group.split("\\.");
group = parts[0];
if (result.containsKey(group)) {
if (parts.length == 1) {
Set<ByteSequence> colFamsSet = decodeColumnFamilies(value);
if (!Collections.disjoint(all, colFamsSet)) {
colFamsSet.retainAll(all);
throw new LocalityGroupConfigurationError("Column families " + colFamsSet
+ " in group " + group + " is already used by another locality group");
}
all.addAll(colFamsSet);
result.put(group, colFamsSet);
}
}
}
}
Set<Entry<String,Set<ByteSequence>>> es = result.entrySet();
for (Entry<String,Set<ByteSequence>> entry : es) {
if (entry.getValue().isEmpty()) {
throw new LocalityGroupConfigurationError(
"Locality group " + entry.getKey() + " specified but not declared");
}
}
// result.put("", all);
return result;
}
public static Set<ByteSequence> decodeColumnFamilies(String colFams)
throws LocalityGroupConfigurationError {
HashSet<ByteSequence> colFamsSet = new HashSet<>();
for (String family : colFams.split(",")) {
ByteSequence cfbs = decodeColumnFamily(family);
colFamsSet.add(cfbs);
}
return colFamsSet;
}
public static ByteSequence decodeColumnFamily(String colFam)
throws LocalityGroupConfigurationError {
byte[] output = new byte[colFam.length()];
int pos = 0;
for (int i = 0; i < colFam.length(); i++) {
char c = colFam.charAt(i);
if (c == '\\') {
// next char must be 'x' or '\'
i++;
if (i >= colFam.length()) {
throw new LocalityGroupConfigurationError("Expected 'x' or '\' after '\' in " + colFam);
}
char nc = colFam.charAt(i);
switch (nc) {
case '\\':
output[pos++] = '\\';
break;
case 'x':
// next two chars must be [0-9][0-9]
i++;
output[pos++] = (byte) (0xff & Integer.parseInt(colFam.substring(i, i + 2), 16));
i++;
break;
default:
throw new LocalityGroupConfigurationError(
"Expected 'x' or '\' after '\' in " + colFam);
}
} else {
output[pos++] = (byte) (0xff & c);
}
}
return new ArrayByteSequence(output, 0, pos);
}
public static String encodeColumnFamilies(Set<Text> colFams) {
SortedSet<String> ecfs = new TreeSet<>();
StringBuilder sb = new StringBuilder();
for (Text text : colFams) {
String ecf = encodeColumnFamily(sb, text.getBytes(), text.getLength());
ecfs.add(ecf);
}
return Joiner.on(",").join(ecfs);
}
public static String encodeColumnFamily(ByteSequence bs) {
if (bs.offset() != 0) {
throw new IllegalArgumentException("The offset cannot be non-zero.");
}
return encodeColumnFamily(new StringBuilder(), bs.getBackingArray(), bs.length());
}
private static String encodeColumnFamily(StringBuilder sb, byte[] ba, int len) {
sb.setLength(0);
for (int i = 0; i < len; i++) {
int c = 0xff & ba[i];
if (c == '\\') {
sb.append("\\\\");
} else if (c >= 32 && c <= 126 && c != ',') {
sb.append((char) c);
} else {
sb.append("\\x").append(String.format("%02X", c));
}
}
return sb.toString();
}
public static class PartitionedMutation extends Mutation {
private byte[] row;
private List<ColumnUpdate> updates;
public PartitionedMutation(byte[] row, List<ColumnUpdate> updates) {
this.row = row;
this.updates = updates;
}
@Override
public byte[] getRow() {
return row;
}
@Override
public List<ColumnUpdate> getUpdates() {
return updates;
}
@Override
public TMutation toThrift() {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Mutation m) {
throw new UnsupportedOperationException();
}
}
public static class Partitioner {
private Map<ByteSequence,Integer> colfamToLgidMap;
private PreAllocatedArray<Map<ByteSequence,MutableLong>> groups;
public Partitioner(PreAllocatedArray<Map<ByteSequence,MutableLong>> groups) {
this.groups = groups;
this.colfamToLgidMap = new HashMap<>();
for (int i = 0; i < groups.length; i++) {
for (ByteSequence cf : groups.get(i).keySet()) {
colfamToLgidMap.put(cf, i);
}
}
}
public void partition(List<Mutation> mutations,
PreAllocatedArray<List<Mutation>> partitionedMutations) {
MutableByteSequence mbs = new MutableByteSequence(new byte[0], 0, 0);
PreAllocatedArray<List<ColumnUpdate>> parts = new PreAllocatedArray<>(groups.length + 1);
for (Mutation mutation : mutations) {
if (mutation.getUpdates().size() == 1) {
int lgid = getLgid(mbs, mutation.getUpdates().get(0));
partitionedMutations.get(lgid).add(mutation);
} else {
for (int i = 0; i < parts.length; i++) {
parts.set(i, null);
}
int lgcount = 0;
for (ColumnUpdate cu : mutation.getUpdates()) {
int lgid = getLgid(mbs, cu);
if (parts.get(lgid) == null) {
parts.set(lgid, new ArrayList<>());
lgcount++;
}
parts.get(lgid).add(cu);
}
if (lgcount == 1) {
for (int i = 0; i < parts.length; i++) {
if (parts.get(i) != null) {
partitionedMutations.get(i).add(mutation);
break;
}
}
} else {
for (int i = 0; i < parts.length; i++) {
if (parts.get(i) != null) {
partitionedMutations.get(i)
.add(new PartitionedMutation(mutation.getRow(), parts.get(i)));
}
}
}
}
}
}
private Integer getLgid(MutableByteSequence mbs, ColumnUpdate cu) {
mbs.setArray(cu.getColumnFamily(), 0, cu.getColumnFamily().length);
Integer lgid = colfamToLgidMap.get(mbs);
if (lgid == null) {
lgid = groups.length;
}
return lgid;
}
}
/**
* This method created to help seek an rfile for a locality group obtained from
* {@link Reader#getLocalityGroupCF()}. This method can possibly return an empty list for the
* default locality group. When this happens the default locality group needs to be seeked
* differently. This method helps do that.
*
* <p>
* For the default locality group will seek using the families of all other locality groups
* non-inclusive.
*
* @see Reader#getLocalityGroupCF()
*/
public static void seek(FileSKVIterator reader, Range range, String lgName,
Map<String,ArrayList<ByteSequence>> localityGroupCF) throws IOException {
Collection<ByteSequence> families;
boolean inclusive;
if (lgName == null) {
// this is the default locality group, create a set of all families not in the default group
Set<ByteSequence> nonDefaultFamilies = new HashSet<>();
for (Entry<String,ArrayList<ByteSequence>> entry : localityGroupCF.entrySet()) {
if (entry.getKey() != null) {
nonDefaultFamilies.addAll(entry.getValue());
}
}
families = nonDefaultFamilies;
inclusive = false;
} else {
families = localityGroupCF.get(lgName);
inclusive = true;
}
reader.seek(range, families, inclusive);
}
public static void ensureNonOverlappingGroups(Map<String,Set<Text>> groups) {
HashSet<Text> all = new HashSet<>();
for (Entry<String,Set<Text>> entry : groups.entrySet()) {
if (!Collections.disjoint(all, entry.getValue())) {
throw new IllegalArgumentException(
"Group " + entry.getKey() + " overlaps with another group");
}
if (entry.getValue().isEmpty()) {
throw new IllegalArgumentException("Group " + entry.getKey() + " is empty");
}
all.addAll(entry.getValue());
}
}
}
| apache-2.0 |
nileshpatelksy/hello-pod-cast | archive/FILE/Compiler/bpwj-java-phrase/code/sjm/examples/engine/ShowAnonymous.java | 1525 | package sjm.examples.engine;
import sjm.engine.*;
/*
* Copyright (c) 1999 Steven J. Metsker. All Rights Reserved.
*
* Steve Metsker makes no representations or warranties about
* the fitness of this software for any particular purpose,
* including the implied warranty of merchantability.
*/
/**
* Show how to use an anonymous variable.
*
* @author Steven J. Metsker
*
* @version 1.0
*/
public class ShowAnonymous {
/**
* Show how to use an anonymous variable.
*/
public static void main(String[] args) {
// marriage(001, balthasar, grimelda, 14560512, 14880711);
Fact m1 = new Fact("marriage", new Object[] {
new Integer(1),
"balthasar",
"grimelda",
new Integer(14560512),
new Integer(14880711)});
// marriage(257, kevin, karla, 19790623, present);
Fact m257 = new Fact("marriage", new Object[] {
new Integer(257),
"kevin",
"karla",
new Integer(19790623),
"present"});
Program p = new Program();
p.addAxiom(m1);
p.addAxiom(m257);
// marriage(Id, Hub, _, _, _);
Variable id = new Variable("Id");
Variable hub = new Variable("Hub");
Anonymous a = new Anonymous();
Query q = new Query(p, new Structure(
"marriage", new Term[] {id, hub, a, a, a}));
// output
System.out.println("Program: \n" + p + "\n");
System.out.println("Query: \n" + q + "\n");
System.out.println("Results: \n");
while (q.canFindNextProof()) {
System.out.println(
"Id: " + id + ", Husband: " + hub);
}
}
} | apache-2.0 |
GovernmentCommunicationsHeadquarters/Gaffer | library/sketches-library/src/test/java/uk/gov/gchq/gaffer/sketches/datasketches/sampling/serialisation/ReservoirNumbersUnionSerialiserTest.java | 2584 | /*
* Copyright 2017-2020 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.gchq.gaffer.sketches.datasketches.sampling.serialisation;
import com.yahoo.sketches.sampling.ReservoirItemsUnion;
import org.junit.jupiter.api.Test;
import uk.gov.gchq.gaffer.commonutil.pair.Pair;
import uk.gov.gchq.gaffer.serialisation.Serialiser;
import uk.gov.gchq.gaffer.sketches.clearspring.cardinality.serialisation.ViaCalculatedArrayValueSerialiserTest;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ReservoirNumbersUnionSerialiserTest extends ViaCalculatedArrayValueSerialiserTest<ReservoirItemsUnion<Number>, Number> {
@Override
protected ReservoirItemsUnion<Number> getEmptyExampleOutput() {
return ReservoirItemsUnion.newInstance(20);
}
@Override
public Serialiser<ReservoirItemsUnion<Number>, byte[]> getSerialisation() {
return new ReservoirNumbersUnionSerialiser();
}
@Override
@SuppressWarnings("unchecked")
public Pair<ReservoirItemsUnion<Number>, byte[]>[] getHistoricSerialisationPairs() {
final ReservoirItemsUnion<Number> union = getExampleOutput();
return new Pair[]{new Pair(union, new byte[]{1, 2, 12, 0, 20, 0, 0, 0, -62, 2, 11, 0, 20, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 12, 1, 0, 0, 0, 0, 0, 0, 0, 12, 2, 0, 0, 0, 0, 0, 0, 0, 12, 3, 0, 0, 0, 0, 0, 0, 0})};
}
@Override
protected ReservoirItemsUnion<Number> getExampleOutput() {
final ReservoirItemsUnion<Number> union = ReservoirItemsUnion.newInstance(20);
union.update(1L);
union.update(2L);
union.update(3L);
return union;
}
@Override
protected Number[] getTestValue(final ReservoirItemsUnion<Number> object) {
return object.getResult().getSamples();
}
@Test
public void testCanHandleReservoirItemsUnion() {
assertTrue(serialiser.canHandle(ReservoirItemsUnion.class));
assertFalse(serialiser.canHandle(String.class));
}
}
| apache-2.0 |
subchen/jetbrick-template-1x | src/test/java/testcase/model/User.java | 2342 | /**
* jetbrick-template
* http://subchen.github.io/jetbrick-template/
*
* Copyright 2010-2013 Guoqiang Chen. All rights reserved.
* Email: subchen@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package testcase.model;
import java.util.*;
public class User {
private String name;
private int status;
private Date birthday;
private boolean locked;
private List<Book> bookList;
public static User newInstance() {
User user = new User();
List<Book> bookList = new ArrayList<Book>();
bookList.add(new Book("JavaBook", 10.99, user));
bookList.add(new Book("DotNetBook", 99.00, user));
bookList.add(new Book("JavaScriptBook", 20.10, user));
user.name = "Jack";
user.status = 0;
user.birthday = new Date();
user.locked = false;
user.bookList = bookList;
return user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
public Book find(String name) {
return new Book(name, 99.99, this);
}
public Book notFind(String name) {
return null;
}
public Book getNone() {
return null;
}
}
| apache-2.0 |
fonoster/astivetoolkit | astive-agi/src/test/java/com/fonoster/astive/agi/test/DatabaseDelTreeTest.java | 2016 | /*
* Copyright (C) 2017 by Fonoster Inc (http://fonoster.com)
* http://github.com/fonoster/astive
*
* This file is part of Astive
*
* 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.fonoster.astive.agi.test;
import junit.framework.TestCase;
import com.fonoster.astive.agi.AgiException;
import com.fonoster.astive.agi.CommandProcessor;
import com.fonoster.astive.agi.command.DatabaseDelTree;
/**
* Test case for command {@link com.fonoster.astive.agi.command.DatabaseDel}.
*
* @since 1.0
*/
public class DatabaseDelTreeTest extends TestCase {
/**
* Creates a new DatabaseDelTreeTest object.
*
* @param testName {@inheritDoc}.
*/
public DatabaseDelTreeTest(String testName) {
super(testName);
}
/**
* Test method.
*
* @throws AgiException if command is malformed.
*/
public void testCommand() throws AgiException {
String family = "familyDb";
String keyTree = "keyTreeDb";
// Testing first constructor
StringBuilder b = new StringBuilder("DATABASE DELTREE");
b.append(" ");
b.append("\"");
b.append(family);
b.append("\"");
DatabaseDelTree command = new DatabaseDelTree(family);
assertEquals(b.toString(), CommandProcessor.buildCommand(command));
// Testing second constructor
b.append(" ");
b.append("\"");
b.append(keyTree);
b.append("\"");
command = new DatabaseDelTree(family, keyTree);
assertEquals(b.toString(), CommandProcessor.buildCommand(command));
}
}
| apache-2.0 |
gmarz/elasticsearch | modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/CustomMustacheFactoryTests.java | 5251 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.script.mustache;
import com.github.mustachejava.Mustache;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.ScriptEngineService;
import org.elasticsearch.test.ESTestCase;
import java.util.Map;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.script.ScriptService.ScriptType.INLINE;
import static org.elasticsearch.script.mustache.CustomMustacheFactory.CONTENT_TYPE_PARAM;
import static org.elasticsearch.script.mustache.CustomMustacheFactory.JSON_MIME_TYPE;
import static org.elasticsearch.script.mustache.CustomMustacheFactory.PLAIN_TEXT_MIME_TYPE;
import static org.elasticsearch.script.mustache.CustomMustacheFactory.X_WWW_FORM_URLENCODED_MIME_TYPE;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
public class CustomMustacheFactoryTests extends ESTestCase {
public void testCreateEncoder() {
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> CustomMustacheFactory.createEncoder(null));
assertThat(e.getMessage(), equalTo("No encoder found for MIME type [null]"));
e = expectThrows(IllegalArgumentException.class, () -> CustomMustacheFactory.createEncoder(""));
assertThat(e.getMessage(), equalTo("No encoder found for MIME type []"));
e = expectThrows(IllegalArgumentException.class, () -> CustomMustacheFactory.createEncoder("test"));
assertThat(e.getMessage(), equalTo("No encoder found for MIME type [test]"));
assertThat(CustomMustacheFactory.createEncoder(CustomMustacheFactory.JSON_MIME_TYPE),
instanceOf(CustomMustacheFactory.JsonEscapeEncoder.class));
assertThat(CustomMustacheFactory.createEncoder(CustomMustacheFactory.PLAIN_TEXT_MIME_TYPE),
instanceOf(CustomMustacheFactory.DefaultEncoder.class));
assertThat(CustomMustacheFactory.createEncoder(CustomMustacheFactory.X_WWW_FORM_URLENCODED_MIME_TYPE),
instanceOf(CustomMustacheFactory.UrlEncoder.class));
}
public void testJsonEscapeEncoder() {
final ScriptEngineService engine = new MustacheScriptEngineService(Settings.EMPTY);
final Map<String, String> params = randomBoolean() ? singletonMap(CONTENT_TYPE_PARAM, JSON_MIME_TYPE) : emptyMap();
Mustache script = (Mustache) engine.compile(null, "{\"field\": \"{{value}}\"}", params);
CompiledScript compiled = new CompiledScript(INLINE, null, MustacheScriptEngineService.NAME, script);
ExecutableScript executable = engine.executable(compiled, singletonMap("value", "a \"value\""));
BytesReference result = (BytesReference) executable.run();
assertThat(result.utf8ToString(), equalTo("{\"field\": \"a \\\"value\\\"\"}"));
}
public void testDefaultEncoder() {
final ScriptEngineService engine = new MustacheScriptEngineService(Settings.EMPTY);
final Map<String, String> params = singletonMap(CONTENT_TYPE_PARAM, PLAIN_TEXT_MIME_TYPE);
Mustache script = (Mustache) engine.compile(null, "{\"field\": \"{{value}}\"}", params);
CompiledScript compiled = new CompiledScript(INLINE, null, MustacheScriptEngineService.NAME, script);
ExecutableScript executable = engine.executable(compiled, singletonMap("value", "a \"value\""));
BytesReference result = (BytesReference) executable.run();
assertThat(result.utf8ToString(), equalTo("{\"field\": \"a \"value\"\"}"));
}
public void testUrlEncoder() {
final ScriptEngineService engine = new MustacheScriptEngineService(Settings.EMPTY);
final Map<String, String> params = singletonMap(CONTENT_TYPE_PARAM, X_WWW_FORM_URLENCODED_MIME_TYPE);
Mustache script = (Mustache) engine.compile(null, "{\"field\": \"{{value}}\"}", params);
CompiledScript compiled = new CompiledScript(INLINE, null, MustacheScriptEngineService.NAME, script);
ExecutableScript executable = engine.executable(compiled, singletonMap("value", "tilde~ AND date:[2016 FROM*]"));
BytesReference result = (BytesReference) executable.run();
assertThat(result.utf8ToString(), equalTo("{\"field\": \"tilde%7E+AND+date%3A%5B2016+FROM*%5D\"}"));
}
}
| apache-2.0 |
streamsets/datacollector | jdbc-protolib/src/main/java/com/streamsets/pipeline/lib/jdbc/typesupport/PrimitiveJdbcTypeSupport.java | 2495 | /*
* Copyright 2017 StreamSets 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.streamsets.pipeline.lib.jdbc.typesupport;
import com.streamsets.pipeline.api.Field;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.lib.jdbc.schemawriter.JdbcSchemaWriter;
import com.streamsets.pipeline.lib.jdbc.JdbcStageCheckedException;
import java.util.LinkedHashMap;
public class PrimitiveJdbcTypeSupport extends JdbcTypeSupport {
@Override
protected Field generateExtraInfoFieldForMetadataRecord(JdbcTypeInfo jdbcTypeInfo) {
return Field.create(new LinkedHashMap<>());
}
@Override
@SuppressWarnings("unchecked")
protected PrimitiveJdbcTypeInfo generateJdbcTypeInfoFromMetadataField(JdbcType type, Field hiveTypeField, JdbcSchemaWriter schemaWriter) throws StageException {
return new PrimitiveJdbcTypeInfo(type, schemaWriter);
}
@Override
@SuppressWarnings("unchecked")
public PrimitiveJdbcTypeInfo generateJdbcTypeInfoFromResultSet(String jdbcTypeString, JdbcSchemaWriter schemaWriter)
throws JdbcStageCheckedException {
JdbcType type = JdbcType.prefixMatch(jdbcTypeString);
return new PrimitiveJdbcTypeInfo(type, schemaWriter);
}
@Override
@SuppressWarnings("unchecked")
public PrimitiveJdbcTypeInfo generateJdbcTypeInfoFromRecordField(Field field, JdbcSchemaWriter schemaWriter, Object... auxillaryArgs)
throws JdbcStageCheckedException{
return new PrimitiveJdbcTypeInfo(JdbcType.getJdbcTypeForFieldType(field.getType()),schemaWriter);
}
@Override
@SuppressWarnings("unchecked")
public PrimitiveJdbcTypeInfo createTypeInfo(JdbcType jdbcType, JdbcSchemaWriter schemaWriter, Object... auxillaryArgs){
return new PrimitiveJdbcTypeInfo(jdbcType, schemaWriter);
}
public static class PrimitiveJdbcTypeInfo extends JdbcTypeInfo {
public PrimitiveJdbcTypeInfo(JdbcType jdbcType, JdbcSchemaWriter schemaWriter) {
super(jdbcType, schemaWriter);
}
}
}
| apache-2.0 |
bitgilde/HyperImage3 | hi3-editor/src/org/hyperimage/client/ws/UpdateViewSortOrder.java | 1813 |
package org.hyperimage.client.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für updateViewSortOrder complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="updateViewSortOrder">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="viewID" type="{http://www.w3.org/2001/XMLSchema}long"/>
* <element name="sortOrder" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "updateViewSortOrder", propOrder = {
"viewID",
"sortOrder"
})
public class UpdateViewSortOrder {
protected long viewID;
protected String sortOrder;
/**
* Ruft den Wert der viewID-Eigenschaft ab.
*
*/
public long getViewID() {
return viewID;
}
/**
* Legt den Wert der viewID-Eigenschaft fest.
*
*/
public void setViewID(long value) {
this.viewID = value;
}
/**
* Ruft den Wert der sortOrder-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSortOrder() {
return sortOrder;
}
/**
* Legt den Wert der sortOrder-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSortOrder(String value) {
this.sortOrder = value;
}
}
| apache-2.0 |
ngouagna/alien4cloud | alien4cloud-rest-api/src/main/java/alien4cloud/rest/topology/UpdateTopologyException.java | 311 | package alien4cloud.rest.topology;
import alien4cloud.exception.TechnicalException;
public class UpdateTopologyException extends TechnicalException {
private static final long serialVersionUID = -9183124153128279999L;
public UpdateTopologyException(String message) {
super(message);
}
}
| apache-2.0 |
scorpionvicky/elasticsearch | buildSrc/src/main/java/org/elasticsearch/gradle/transform/UnpackTransform.java | 3906 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle.transform;
import org.gradle.api.artifacts.transform.InputArtifact;
import org.gradle.api.artifacts.transform.TransformAction;
import org.gradle.api.artifacts.transform.TransformOutputs;
import org.gradle.api.artifacts.transform.TransformParameters;
import org.gradle.api.file.FileSystemLocation;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.internal.UncheckedException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Function;
public interface UnpackTransform extends TransformAction<UnpackTransform.Parameters> {
interface Parameters extends TransformParameters {
@Input
@Optional
String getTrimmedPrefixPattern();
void setTrimmedPrefixPattern(String pattern);
}
@PathSensitive(PathSensitivity.NAME_ONLY)
@InputArtifact
Provider<FileSystemLocation> getArchiveFile();
@Override
default void transform(TransformOutputs outputs) {
File archiveFile = getArchiveFile().get().getAsFile();
File extractedDir = outputs.dir(archiveFile.getName());
try {
unpack(archiveFile, extractedDir);
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
void unpack(File archiveFile, File targetDir) throws IOException;
default Function<String, Path> pathResolver() {
String trimmedPrefixPattern = getParameters().getTrimmedPrefixPattern();
return trimmedPrefixPattern != null ? (i) -> trimArchiveExtractPath(trimmedPrefixPattern, i) : (i) -> Path.of(i);
}
/*
* We want to be able to trim off certain prefixes when transforming archives.
*
* E.g We want to remove up to the and including the jdk-.* relative paths. That is a JDK archive is structured as:
* jdk-12.0.1/
* jdk-12.0.1/Contents
* ...
*
* and we want to remove the leading jdk-12.0.1. Note however that there could also be a leading ./ as in
* ./
* ./jdk-12.0.1/
* ./jdk-12.0.1/Contents
*
* so we account for this and search the path components until we find the jdk-12.0.1, and strip the leading components.
*/
static Path trimArchiveExtractPath(String ignoredPattern, String relativePath) {
final Path entryName = Paths.get(relativePath);
int index = 0;
for (; index < entryName.getNameCount(); index++) {
if (entryName.getName(index).toString().matches(ignoredPattern)) {
break;
}
}
if (index + 1 >= entryName.getNameCount()) {
// this happens on the top-level directories in the archive, which we are removing
return null;
}
// finally remove the top-level directories from the output path
return entryName.subpath(index + 1, entryName.getNameCount());
}
}
| apache-2.0 |
kunickiaj/datacollector | jdbc-protolib/src/test/java/com/streamsets/pipeline/stage/origin/jdbc/table/MultiThreadedIT.java | 19100 | /*
* Copyright 2017 StreamSets 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.streamsets.pipeline.stage.origin.jdbc.table;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.streamsets.pipeline.api.EventRecord;
import com.streamsets.pipeline.api.Field;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.lib.event.NoMoreDataEvent;
import com.streamsets.pipeline.lib.jdbc.multithread.BatchTableStrategy;
import com.streamsets.pipeline.lib.jdbc.multithread.SchemaFinishedEvent;
import com.streamsets.pipeline.lib.jdbc.multithread.TableFinishedEvent;
import com.streamsets.pipeline.sdk.PushSourceRunner;
import com.streamsets.pipeline.sdk.RecordCreator;
import com.streamsets.pipeline.sdk.StageRunner;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.reflect.Whitebox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class MultiThreadedIT extends BaseTableJdbcSourceIT {
private static final Logger LOG = LoggerFactory.getLogger(MultiThreadedIT.class);
private static final String TABLE_NAME_PREFIX = "TAB";
private static final String COLUMN_NAME_PREFIX = "col";
private static final String OFFSET_FIELD_NAME = "off";
private static final String OFFSET_FIELD_RAW_NAME = "off_raw";
private static final int NON_INCREMENTAL_LOAD_TEST_TABLE_NUMBER = 1;
private static final int NUMBER_OF_TABLES = 10;
private static final int NUMBER_OF_COLUMNS_PER_TABLE = 1;
private static final int NUMBER_OF_THREADS = 4;
private static final int MAX_ROWS_PER_TABLE = 100000;
private static final List<Field.Type> OTHER_FIELD_TYPES =
Arrays.stream(Field.Type.values())
.filter(
fieldType ->
!fieldType.isOneOf(
Field.Type.LIST_MAP,
Field.Type.MAP,
Field.Type.LIST,
Field.Type.FILE_REF,
Field.Type.BYTE_ARRAY,
Field.Type.BYTE,
Field.Type.CHAR
)
)
.collect(Collectors.toList());
private static final Map<String, List<Record>> EXPECTED_TABLES_TO_RECORDS = new LinkedHashMap<>();
@Rule
public Timeout globalTimeout = Timeout.seconds(300); // 5 minutes
private static void populateColumns(
Map<String, Field.Type> columnToFieldType,
Map<String, String> offsetColumns,
Map<String, String> otherColumns
) {
columnToFieldType.put(OFFSET_FIELD_NAME, Field.Type.INTEGER);
offsetColumns.put(
OFFSET_FIELD_NAME,
FIELD_TYPE_TO_SQL_TYPE_AND_STRING.get(columnToFieldType.get(OFFSET_FIELD_NAME))
);
IntStream.range(0, NUMBER_OF_COLUMNS_PER_TABLE).forEach(columnNumber -> {
String columnName = COLUMN_NAME_PREFIX + columnNumber;
columnToFieldType.put(
columnName,
OTHER_FIELD_TYPES.get(RANDOM.nextInt(OTHER_FIELD_TYPES.size()))
);
otherColumns.put(columnName, FIELD_TYPE_TO_SQL_TYPE_AND_STRING.get(columnToFieldType.get(columnName)));
});
}
private static void createRecordsAndExecuteInsertStatements(
String tableName,
Statement st,
Map<String, Field.Type> columnToFieldType,
boolean multipleRecordsWithSameOffset
) throws Exception {
int numberOfRecordsInTable = RANDOM.nextInt(MAX_ROWS_PER_TABLE - 1) + 1;
IntStream.range(0, numberOfRecordsInTable).forEach(recordNum -> {
Record record = RecordCreator.create();
LinkedHashMap<String, Field> rootField = new LinkedHashMap<>();
final int recordNumDivisor = multipleRecordsWithSameOffset ? 100 : 1;
final int calculatedRecordNum = recordNum / recordNumDivisor;
rootField.put(OFFSET_FIELD_NAME, Field.create(calculatedRecordNum));
columnToFieldType.entrySet().stream()
.filter(columnToFieldTypeEntry -> !columnToFieldTypeEntry.getKey().equals(OFFSET_FIELD_NAME))
.forEach(columnToFieldTypeEntry -> {
String fieldName = columnToFieldTypeEntry.getKey();
Field.Type fieldType = columnToFieldTypeEntry.getValue();
rootField.put(fieldName, Field.create(fieldType, generateRandomData(fieldType)));
});
if (multipleRecordsWithSameOffset) {
rootField.put(OFFSET_FIELD_RAW_NAME, Field.create(recordNum));
}
record.set(Field.createListMap(rootField));
List<Record> records = EXPECTED_TABLES_TO_RECORDS.computeIfAbsent(tableName, t -> new ArrayList<>());
records.add(record);
try {
st.addBatch(getInsertStatement(database, tableName, rootField.values()));
} catch (Exception e) {
LOG.error("Error Happened", e);
Throwables.propagate(e);
}
});
st.executeBatch();
}
@BeforeClass
public static void setupTables() throws Exception {
IntStream.range(0, NUMBER_OF_TABLES).forEach(tableNumber -> {
try (Statement st = connection.createStatement()){
final boolean multipleRecordsWithSameOffsetTable = tableNumber == 0;
final boolean nonIncrementalTestTable = tableNumber == NON_INCREMENTAL_LOAD_TEST_TABLE_NUMBER;
String tableName = TABLE_NAME_PREFIX + tableNumber;
Map<String, Field.Type> columnToFieldType = new LinkedHashMap<>();
Map<String, String> offsetColumns = new LinkedHashMap<>();
Map<String, String> otherColumns = new LinkedHashMap<>();
populateColumns(columnToFieldType, offsetColumns, otherColumns);
if (multipleRecordsWithSameOffsetTable) {
columnToFieldType.put(OFFSET_FIELD_RAW_NAME, Field.Type.INTEGER);
otherColumns.put(OFFSET_FIELD_RAW_NAME, FIELD_TYPE_TO_SQL_TYPE_AND_STRING.get(Field.Type.INTEGER));
}
st.execute(
getCreateStatement(
database,
tableName,
offsetColumns,
otherColumns,
!multipleRecordsWithSameOffsetTable && !nonIncrementalTestTable
)
);
createRecordsAndExecuteInsertStatements(tableName, st, columnToFieldType, multipleRecordsWithSameOffsetTable);
} catch (Exception e) {
LOG.error("Error Happened", e);
Throwables.propagate(e);
}
});
}
@AfterClass
public static void deleteTables() throws Exception {
try (Statement st = connection.createStatement()) {
EXPECTED_TABLES_TO_RECORDS.keySet().forEach(table -> {
try {
st.addBatch(String.format(DROP_STATEMENT_TEMPLATE, database, table));
} catch (SQLException e) {
LOG.error("Error Happened", e);
Throwables.propagate(e);
}
}
);
}
}
private static class MultiThreadedJdbcTestCallback implements PushSourceRunner.Callback {
private final PushSourceRunner pushSourceRunner;
private final Map<String, List<Record>> tableToRecords;
private final List<Record> eventRecords;
private final Set<String> tablesYetToBeCompletelyRead;
private final AtomicBoolean noMoreDataEvent = new AtomicBoolean(false);
private MultiThreadedJdbcTestCallback(PushSourceRunner pushSourceRunner, Set<String> tables) {
this.pushSourceRunner = pushSourceRunner;
this.tableToRecords = new ConcurrentHashMap<>();
this.eventRecords = new LinkedList<>();
this.tablesYetToBeCompletelyRead = new HashSet<>(tables);
}
private Map<String, List<Record>> waitForAllBatchesAndReset() {
try {
pushSourceRunner.waitOnProduce();
} catch (Exception e) {
Throwables.propagate(e);
Assert.fail(e.getMessage());
}
return ImmutableMap.copyOf(tableToRecords);
}
@Override
public synchronized void processBatch(StageRunner.Output output) throws StageException {
List<Record> records = output.getRecords().get("a");
if (!records.isEmpty()) {
Record record = records.get(0);
String tableName = record.getHeader().getAttribute("jdbc.tables");
List<Record> recordList =
tableToRecords.computeIfAbsent(tableName, table -> Collections.synchronizedList(new ArrayList<>()));
recordList.addAll(records);
List<Record> expectedRecords = EXPECTED_TABLES_TO_RECORDS.get(tableName);
if (expectedRecords.size() <= recordList.size()) {
tablesYetToBeCompletelyRead.remove(tableName);
}
}
List<EventRecord> eventRecords = new LinkedList<>(pushSourceRunner.getEventRecords());
if (!noMoreDataEvent.get() && eventRecords != null && !eventRecords.isEmpty()) {
for (EventRecord eventRecord : eventRecords) {
if (eventRecord == null) {
// somehow, items in the event records can occasionally be null
continue;
}
if (NoMoreDataEvent.NO_MORE_DATA_TAG.equals(eventRecord.getEventType())) {
noMoreDataEvent.set(true);
break;
}
}
}
if (tablesYetToBeCompletelyRead.isEmpty() && noMoreDataEvent.get()) {
// at this point, we have all expected records and the no more data event
// because of the delay added when generating the no more data event, assume
// that all other new finished events are also received by now
pushSourceRunner.setStop();
}
}
}
public void testMultiThreadedRead(
TableJdbcSource tableJdbcSource,
String... tables
) throws Exception {
testMultiThreadedRead(tableJdbcSource, new HashSet<>(Arrays.asList(tables)));
}
public void testMultiThreadedRead(TableJdbcSource tableJdbcSource) throws Exception {
testMultiThreadedRead(tableJdbcSource, EXPECTED_TABLES_TO_RECORDS.keySet());
}
public void testMultiThreadedRead(TableJdbcSource tableJdbcSource, Set<String> tables) throws Exception {
PushSourceRunner runner = new PushSourceRunner.Builder(TableJdbcDSource.class, tableJdbcSource)
.addOutputLane("a").build();
runner.runInit();
MultiThreadedJdbcTestCallback multiThreadedJdbcTestCallback = new MultiThreadedJdbcTestCallback(runner, tables);
try {
runner.runProduce(Collections.emptyMap(), 20, multiThreadedJdbcTestCallback);
Map<String, List<Record>> actualTableToRecords = multiThreadedJdbcTestCallback.waitForAllBatchesAndReset();
Assert.assertEquals(tables.size(), actualTableToRecords.size());
EXPECTED_TABLES_TO_RECORDS.keySet().stream().filter(table -> tables.contains(table)).forEach((tableName) -> {
final List<Record> expectedRecords = EXPECTED_TABLES_TO_RECORDS.get(tableName);
List<Record> actualRecords = actualTableToRecords.get(tableName);
checkRecords(tableName, expectedRecords, actualRecords, new Comparator<Record>() {
@Override
public int compare(Record o1, Record o2) {
final Field off1 = o1.get("/OFF");
final Field off2 = o2.get("/OFF");
if (off1 == null) {
if (off2 == null) {
return 0;
} else {
return 1;
}
} else if (off2 == null) {
return -1;
}
return off1.getValueAsInteger() - off2.getValueAsInteger();
}
});
});
// assert all expected events are present
// for each table, there should be a table finished event
final Set<String> tableFinishedEvents = new HashSet<>(tables);
// for each schema, there should be a schema finished event
// (in our test case, there is only one schema)
boolean schemaFinishedEvent = false;
// there should also be the no more data event, as before
boolean noMoreDataEvent = false;
for (EventRecord eventRecord : runner.getEventRecords()) {
if (eventRecord == null) {
continue;
}
switch (eventRecord.getEventType()) {
case TableFinishedEvent.TABLE_FINISHED_TAG:
tableFinishedEvents.remove(eventRecord.get("/" + TableFinishedEvent.TABLE_FIELD).getValueAsString());
break;
case SchemaFinishedEvent.SCHEMA_FINISHED_TAG:
schemaFinishedEvent = true;
final Set<String> allSchemaTables = new HashSet<>();
final Field allTablesField = eventRecord.get("/" + SchemaFinishedEvent.TABLES_FIELD);
assertThat(allTablesField, notNullValue());
allTablesField.getValueAsList().forEach(field -> allSchemaTables.add(field.getValueAsString()));
assertEquals(allSchemaTables, tables);
break;
case NoMoreDataEvent.NO_MORE_DATA_TAG:
noMoreDataEvent = true;
break;
}
}
Assert.assertTrue(noMoreDataEvent);
Assert.assertTrue(schemaFinishedEvent);
Assert.assertTrue(tableFinishedEvents.isEmpty());
} finally {
runner.runDestroy();
}
}
@Test
public void testSwitchTables() throws Exception {
TableConfigBeanImpl tableConfigBean = new TableJdbcSourceTestBuilder.TableConfigBeanTestBuilder()
.tablePattern("%")
.maxNumActivePartitions(6)
.partitioningMode(PartitioningMode.BEST_EFFORT)
.partitionSize("1000")
.schema(database)
.offsetColumns(Collections.singletonList(OFFSET_FIELD_NAME.toUpperCase()))
.overrideDefaultOffsetColumns(true)
.build();
TableJdbcSource tableJdbcSource = new TableJdbcSourceTestBuilder(JDBC_URL, true, USER_NAME, PASSWORD)
.tableConfigBeans(ImmutableList.of(tableConfigBean))
.batchTableStrategy(BatchTableStrategy.PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE)
// 4 threads
.numberOfThreads(NUMBER_OF_THREADS)
.build();
testMultiThreadedRead(tableJdbcSource);
}
@Test
public void testProcessAllRows() throws Exception {
TableConfigBeanImpl tableConfigBean = new TableJdbcSourceTestBuilder.TableConfigBeanTestBuilder()
.tablePattern("%")
.schema(database)
.partitionSize("1000")
.partitioningMode(PartitioningMode.BEST_EFFORT)
.offsetColumns(Collections.singletonList(OFFSET_FIELD_NAME.toUpperCase()))
.overrideDefaultOffsetColumns(true)
.build();
TableJdbcSource tableJdbcSource = new TableJdbcSourceTestBuilder(JDBC_URL, true, USER_NAME, PASSWORD)
.tableConfigBeans(ImmutableList.of(tableConfigBean))
.batchTableStrategy(BatchTableStrategy.PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE)
// 4 threads
.numberOfThreads(NUMBER_OF_THREADS)
.build();
testMultiThreadedRead(tableJdbcSource);
}
@Test
public void testSwitchTablesWithNumberOfBatches() throws Exception {
TableConfigBeanImpl tableConfigBean = new TableJdbcSourceTestBuilder.TableConfigBeanTestBuilder()
.tablePattern("%")
.schema(database)
.partitionSize("1000")
.partitioningMode(PartitioningMode.BEST_EFFORT)
.offsetColumns(Collections.singletonList(OFFSET_FIELD_NAME.toUpperCase()))
.overrideDefaultOffsetColumns(true)
.build();
TableJdbcSource tableJdbcSource = new TableJdbcSourceTestBuilder(JDBC_URL, true, USER_NAME, PASSWORD)
.tableConfigBeans(ImmutableList.of(tableConfigBean))
// 4 threads
.numberOfThreads(NUMBER_OF_THREADS)
.batchTableStrategy(BatchTableStrategy.PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE)
.numberOfBatchesFromResultset(2)
.build();
testMultiThreadedRead(tableJdbcSource);
}
@Test
public void testNonIncrementalLoad() throws Exception {
final String nonIncrementalTable = TABLE_NAME_PREFIX + NON_INCREMENTAL_LOAD_TEST_TABLE_NUMBER;
TableConfigBeanImpl tableConfigBean = new TableJdbcSourceTestBuilder.TableConfigBeanTestBuilder()
.tablePattern(nonIncrementalTable)
.schema(database)
.partitionSize("1000")
.partitioningMode(PartitioningMode.BEST_EFFORT)
.enableNonIncremental(true)
.build();
TableJdbcSource tableJdbcSource = new TableJdbcSourceTestBuilder(JDBC_URL, true, USER_NAME, PASSWORD)
.tableConfigBeans(ImmutableList.of(tableConfigBean))
.batchTableStrategy(BatchTableStrategy.PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE)
// 4 threads
.numberOfThreads(NUMBER_OF_THREADS)
.build();
testMultiThreadedRead(tableJdbcSource, nonIncrementalTable);
}
@Test
@Ignore("Figure out how to handle max tables (partitions) per thread map now: SDC-6768")
public void testNumThreadsMoreThanNumTables() throws Exception {
TableConfigBeanImpl tableConfigBean = new TableJdbcSourceTestBuilder.TableConfigBeanTestBuilder()
.tablePattern("%")
.schema(database)
.offsetColumns(Collections.singletonList(OFFSET_FIELD_NAME.toUpperCase()))
.overrideDefaultOffsetColumns(true)
.build();
TableJdbcSource tableJdbcSource = new TableJdbcSourceTestBuilder(JDBC_URL, true, USER_NAME, PASSWORD)
.tableConfigBeans(ImmutableList.of(tableConfigBean))
// 20 threads in config but there are only 10 tables
.numberOfThreads(NUMBER_OF_TABLES + 10)
.batchTableStrategy(BatchTableStrategy.SWITCH_TABLES)
.build();
tableJdbcSource = PowerMockito.spy(tableJdbcSource);
PushSourceRunner runner = new PushSourceRunner.Builder(TableJdbcDSource.class, tableJdbcSource)
.addOutputLane("a").build();
runner.runInit();
try {
int numberOfThreads = Whitebox.getInternalState(tableJdbcSource, "numberOfThreads");
Assert.assertEquals(NUMBER_OF_TABLES, numberOfThreads);
} finally {
runner.runDestroy();
}
}
}
| apache-2.0 |
sflyphotobooks/crp-batik | sources/org/apache/batik/ext/awt/image/codec/tiff/TIFFTranscoderInternalCodecWriteAdapter.java | 4783 | /*
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.batik.ext.awt.image.codec.tiff;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.batik.ext.awt.image.GraphicsUtil;
import org.apache.batik.ext.awt.image.rendered.FormatRed;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.TranscodingHints;
import org.apache.batik.transcoder.image.TIFFTranscoder;
/**
* This class is a helper to <tt>TIFFTranscoder</tt> that writes TIFF images
* through the internal TIFF codec.
*
* @version $Id: TIFFTranscoderInternalCodecWriteAdapter.java 582434 2007-10-06 02:11:51Z cam $
*/
public class TIFFTranscoderInternalCodecWriteAdapter implements
TIFFTranscoder.WriteAdapter {
/**
* @throws TranscoderException
* @see org.apache.batik.transcoder.image.PNGTranscoder.WriteAdapter#writeImage(org.apache.batik.transcoder.image.PNGTranscoder, java.awt.image.BufferedImage, org.apache.batik.transcoder.TranscoderOutput)
*/
public void writeImage(TIFFTranscoder transcoder, BufferedImage img,
TranscoderOutput output) throws TranscoderException {
TranscodingHints hints = transcoder.getTranscodingHints();
TIFFEncodeParam params = new TIFFEncodeParam();
float PixSzMM = transcoder.getUserAgent().getPixelUnitToMillimeter();
// num Pixs in 100 Meters
int numPix = (int)(((1000 * 100) / PixSzMM) + 0.5);
int denom = 100 * 100; // Centimeters per 100 Meters;
long [] rational = {numPix, denom};
TIFFField [] fields = {
new TIFFField(TIFFImageDecoder.TIFF_RESOLUTION_UNIT,
TIFFField.TIFF_SHORT, 1,
new char [] { (char)3 }),
new TIFFField(TIFFImageDecoder.TIFF_X_RESOLUTION,
TIFFField.TIFF_RATIONAL, 1,
new long [][] { rational }),
new TIFFField(TIFFImageDecoder.TIFF_Y_RESOLUTION,
TIFFField.TIFF_RATIONAL, 1,
new long [][] { rational })
};
params.setExtraFields(fields);
if (hints.containsKey(TIFFTranscoder.KEY_COMPRESSION_METHOD)) {
String method = (String)hints.get(TIFFTranscoder.KEY_COMPRESSION_METHOD);
if ("packbits".equals(method)) {
params.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS);
} else if ("deflate".equals(method)) {
params.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
/* TODO: NPE occurs when used.
} else if ("jpeg".equals(method)) {
params.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
*/
} else {
//nop
}
}
try {
int w = img.getWidth();
int h = img.getHeight();
SinglePixelPackedSampleModel sppsm;
sppsm = (SinglePixelPackedSampleModel)img.getSampleModel();
OutputStream ostream = output.getOutputStream();
TIFFImageEncoder tiffEncoder =
new TIFFImageEncoder(ostream, params);
int bands = sppsm.getNumBands();
int [] off = new int[bands];
for (int i = 0; i < bands; i++)
off[i] = i;
SampleModel sm = new PixelInterleavedSampleModel
(DataBuffer.TYPE_BYTE, w, h, bands, w * bands, off);
RenderedImage rimg = new FormatRed(GraphicsUtil.wrap(img), sm);
tiffEncoder.encode(rimg);
ostream.flush();
} catch (IOException ex) {
throw new TranscoderException(ex);
}
}
}
| apache-2.0 |
ligzy/Agrona | src/main/java/uk/co/real_logic/agrona/Verify.java | 1641 | /*
* Copyright 2013 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.real_logic.agrona;
import java.util.Map;
/**
* Various verification checks to be applied in code.
*/
public class Verify
{
/**
* Verify that a reference is not null.
*
* @param ref to be verified not null.
* @param name of the reference to be verified.
*/
public static void notNull(final Object ref, final String name)
{
if (null == ref)
{
throw new NullPointerException(name + " must not be null");
}
}
/**
* Verify that a map contains and entry for a given key.
*
* @param map to be checked.
* @param key to get by.
* @param name of entry.
* @throws NullPointerException if map or key is null
* @throws IllegalStateException if the entry does not exist.
*/
public static void present(final Map<?, ?> map, final Object key, final String name)
{
if (null == map.get(key))
{
throw new IllegalStateException(name + " not found in map for key: " + key);
}
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | platform/lang-impl/src/com/intellij/internal/statistic/tools/InspectionsUsagesCollector.java | 7861 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.tools;
import com.intellij.codeInspection.InspectionEP;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.codeInspection.ex.ScopeToolState;
import com.intellij.internal.statistic.beans.MetricEvent;
import com.intellij.internal.statistic.beans.MetricEventFactoryKt;
import com.intellij.internal.statistic.eventLog.FeatureUsageData;
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType;
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext;
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule;
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector;
import com.intellij.internal.statistic.utils.PluginInfo;
import com.intellij.internal.statistic.utils.PluginInfoDetectorKt;
import com.intellij.lang.Language;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Attribute;
import org.jdom.Content;
import org.jdom.DataConversionException;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Predicate;
public class InspectionsUsagesCollector extends ProjectUsagesCollector {
private static final Predicate<ScopeToolState> ENABLED = state -> !state.getTool().isEnabledByDefault() && state.isEnabled();
private static final Predicate<ScopeToolState> DISABLED = state -> state.getTool().isEnabledByDefault() && !state.isEnabled();
private static final String OPTION_VALUE = "option_value";
private static final String OPTION_TYPE = "option_type";
private static final String OPTION_NAME = "option_name";
private static final String INSPECTION_ID = "inspection_id";
@NotNull
@Override
public String getGroupId() {
return "inspections";
}
@Override
public int getVersion() {
return 5;
}
@NotNull
@Override
public Set<MetricEvent> getMetrics(@NotNull final Project project) {
final Set<MetricEvent> result = new HashSet<>();
final List<ScopeToolState> tools = InspectionProjectProfileManager.getInstance(project).getCurrentProfile().getAllTools();
for (ScopeToolState state : tools) {
InspectionToolWrapper<?, ?> tool = state.getTool();
PluginInfo pluginInfo = getInfo(tool);
if (ENABLED.test(state)) {
result.add(create(tool, pluginInfo, true));
}
else if (DISABLED.test(state)) {
result.add(create(tool, pluginInfo, false));
}
result.addAll(getChangedSettingsEvents(tool, pluginInfo, state.isEnabled()));
}
return result;
}
private static Collection<MetricEvent> getChangedSettingsEvents(InspectionToolWrapper<?, ?> tool,
PluginInfo pluginInfo,
boolean inspectionEnabled) {
if (!isSafeToReport(pluginInfo)) {
return Collections.emptyList();
}
InspectionProfileEntry entry = tool.getTool();
Map<String, Attribute> options = getOptions(entry);
if (options.isEmpty()) {
return Collections.emptyList();
}
Set<String> fields = ContainerUtil.map2Set(ReflectionUtil.collectFields(entry.getClass()), f -> f.getName());
Map<String, Attribute> defaultOptions = getOptions(ReflectionUtil.newInstance(entry.getClass()));
Collection<MetricEvent> result = new ArrayList<>();
String inspectionId = tool.getID();
for (Map.Entry<String, Attribute> option : options.entrySet()) {
String name = option.getKey();
Attribute value = option.getValue();
if (fields.contains(name) && value != null) {
Attribute defaultValue = defaultOptions.get(name);
if (defaultValue == null || !StringUtil.equals(value.getValue(), defaultValue.getValue())) {
FeatureUsageData data = new FeatureUsageData();
data.addData(OPTION_NAME, name);
data.addData(INSPECTION_ID, inspectionId);
data.addData("inspection_enabled", inspectionEnabled);
data.addPluginInfo(pluginInfo);
if (addSettingValue(value, data)) {
result.add(MetricEventFactoryKt.newMetric("setting.non.default.state", data));
}
}
}
}
return result;
}
private static boolean addSettingValue(Attribute value, FeatureUsageData data) {
try {
boolean booleanValue = value.getBooleanValue();
data.addData(OPTION_VALUE, booleanValue);
data.addData(OPTION_TYPE, "boolean");
return true;
}
catch (DataConversionException e) {
return addIntValue(value, data);
}
}
private static boolean addIntValue(Attribute value, FeatureUsageData data) {
try {
int intValue = value.getIntValue();
data.addData(OPTION_VALUE, intValue);
data.addData(OPTION_TYPE, "integer");
return true;
}
catch (DataConversionException e) {
return false;
}
}
@NotNull
private static MetricEvent create(InspectionToolWrapper<?, ?> tool, PluginInfo info, boolean enabled) {
final FeatureUsageData data = new FeatureUsageData().addData("enabled", enabled);
final String language = tool.getLanguage();
if (StringUtil.isNotEmpty(language)) {
data.addLanguage(Language.findLanguageByID(language));
}
if (info != null) {
data.addPluginInfo(info);
}
data.addData(INSPECTION_ID, isSafeToReport(info) ? tool.getID() : "third.party");
return MetricEventFactoryKt.newMetric("not.default.state", data);
}
private static boolean isSafeToReport(PluginInfo info) {
return info != null && info.isSafeToReport();
}
@Nullable
private static PluginInfo getInfo(InspectionToolWrapper<?, ?> tool) {
InspectionEP extension = tool.getExtension();
PluginDescriptor pluginDescriptor = extension == null ? null : extension.getPluginDescriptor();
return pluginDescriptor != null ? PluginInfoDetectorKt.getPluginInfoByDescriptor(pluginDescriptor) : null;
}
private static Map<String, Attribute> getOptions(InspectionProfileEntry entry) {
Element element = new Element("options");
try {
ScopeToolState.tryWriteSettings(entry, element);
List<Content> options = element.getContent();
if (options.isEmpty()) {
return Collections.emptyMap();
}
return ContainerUtil.map2MapNotNull(options, option -> {
if (option instanceof Element) {
Attribute nameAttr = ((Element)option).getAttribute("name");
Attribute valueAttr = ((Element)option).getAttribute("value");
if (nameAttr != null && valueAttr != null) {
return Pair.create(nameAttr.getValue(), valueAttr);
}
}
return null;
});
}
catch (Exception e) {
return Collections.emptyMap();
}
}
public static class InspectionToolValidator extends CustomValidationRule {
@Override
public boolean acceptRuleId(@Nullable String ruleId) {
return "tool".equals(ruleId);
}
@NotNull
@Override
protected ValidationResultType doValidate(@NotNull String data, @NotNull EventContext context) {
if (isThirdPartyValue(data)) return ValidationResultType.ACCEPTED;
return acceptWhenReportedByPluginFromPluginRepository(context);
}
}
} | apache-2.0 |
racker/omnibus | source/db-5.0.26.NC/sql/jdbc/SQLite/JDBC2x/JDBCStatement.java | 6612 | package SQLite.JDBC2x;
import java.sql.*;
import java.util.*;
public class JDBCStatement implements java.sql.Statement {
protected JDBCConnection conn;
protected JDBCResultSet rs;
protected int updcnt;
protected int maxrows = 0;
private ArrayList batch;
public JDBCStatement(JDBCConnection conn) {
this.conn = conn;
this.updcnt = 0;
this.rs = null;
this.batch = null;
}
public void setFetchSize(int fetchSize) throws SQLException {
throw new SQLException("not supported");
}
public int getFetchSize() throws SQLException {
return 1;
}
public int getMaxRows() throws SQLException {
return maxrows;
}
public void setMaxRows(int max) throws SQLException {
maxrows = max;
}
public void setFetchDirection(int fetchDirection) throws SQLException {
throw new SQLException("not supported");
}
public int getFetchDirection() throws SQLException {
return ResultSet.FETCH_UNKNOWN;
}
public int getResultSetConcurrency() throws SQLException {
return ResultSet.CONCUR_READ_ONLY;
}
public int getResultSetType() throws SQLException {
return ResultSet.TYPE_SCROLL_INSENSITIVE;
}
public void setQueryTimeout(int seconds) throws SQLException {
conn.timeout = seconds * 1000;
if (conn.timeout < 0) {
conn.timeout = 120000;
} else if (conn.timeout < 1000) {
conn.timeout = 5000;
}
}
public int getQueryTimeout() throws SQLException {
return conn.timeout;
}
public ResultSet getResultSet() throws SQLException {
return rs;
}
ResultSet executeQuery(String sql, String args[], boolean updonly)
throws SQLException {
SQLite.TableResult tr = null;
if (rs != null) {
rs.close();
rs = null;
}
updcnt = -1;
if (conn == null || conn.db == null) {
throw new SQLException("stale connection");
}
int busy = 0;
boolean starttrans = !conn.autocommit && !conn.intrans;
while (true) {
try {
if (starttrans) {
conn.db.exec("BEGIN TRANSACTION", null);
conn.intrans = true;
}
if (args == null) {
if (updonly) {
conn.db.exec(sql, null);
} else {
tr = conn.db.get_table(sql, maxrows);
}
} else {
if (updonly) {
conn.db.exec(sql, null, args);
} else {
tr = conn.db.get_table(sql, maxrows, args);
}
}
updcnt = (int) conn.db.changes();
} catch (SQLite.Exception e) {
if (conn.db.is3() &&
conn.db.last_error() == SQLite.Constants.SQLITE_BUSY &&
conn.busy3(conn.db, ++busy)) {
try {
if (starttrans && conn.intrans) {
conn.db.exec("ROLLBACK", null);
conn.intrans = false;
}
} catch (SQLite.Exception ee) {
}
try {
int ms = 20 + busy * 10;
if (ms > 1000) {
ms = 1000;
}
synchronized (this) {
this.wait(ms);
}
} catch (java.lang.Exception eee) {
}
continue;
}
throw new SQLException(e.toString());
}
break;
}
if (!updonly && tr == null) {
throw new SQLException("no result set produced");
}
if (!updonly && tr != null) {
rs = new JDBCResultSet(new TableResultX(tr), this);
}
return rs;
}
public ResultSet executeQuery(String sql) throws SQLException {
return executeQuery(sql, null, false);
}
public boolean execute(String sql) throws SQLException {
return executeQuery(sql) != null;
}
public void cancel() throws SQLException {
if (conn == null || conn.db == null) {
throw new SQLException("stale connection");
}
conn.db.interrupt();
}
public void clearWarnings() throws SQLException {
}
public Connection getConnection() throws SQLException {
return conn;
}
public void addBatch(String sql) throws SQLException {
if (batch == null) {
batch = new ArrayList(1);
}
batch.add(sql);
}
public int[] executeBatch() throws SQLException {
if (batch == null) {
return new int[0];
}
int[] ret = new int[batch.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = EXECUTE_FAILED;
}
int errs = 0;
for (int i = 0; i < ret.length; i++) {
try {
execute((String) batch.get(i));
ret[i] = updcnt;
} catch (SQLException e) {
++errs;
}
}
if (errs > 0) {
throw new BatchUpdateException("batch failed", ret);
}
return ret;
}
public void clearBatch() throws SQLException {
if (batch != null) {
batch.clear();
batch = null;
}
}
public void close() throws SQLException {
clearBatch();
conn = null;
}
public int executeUpdate(String sql) throws SQLException {
executeQuery(sql, null, true);
return updcnt;
}
public int getMaxFieldSize() throws SQLException {
return 0;
}
public boolean getMoreResults() throws SQLException {
if (rs != null) {
rs.close();
rs = null;
}
return false;
}
public int getUpdateCount() throws SQLException {
return updcnt;
}
public SQLWarning getWarnings() throws SQLException {
return null;
}
public void setCursorName(String name) throws SQLException {
throw new SQLException("not supported");
}
public void setEscapeProcessing(boolean enable) throws SQLException {
throw new SQLException("not supported");
}
public void setMaxFieldSize(int max) throws SQLException {
throw new SQLException("not supported");
}
public boolean getMoreResults(int x) throws SQLException {
throw new SQLException("not supported");
}
public ResultSet getGeneratedKeys() throws SQLException {
throw new SQLException("not supported");
}
public int executeUpdate(String sql, int autokeys)
throws SQLException {
if (autokeys != Statement.NO_GENERATED_KEYS) {
throw new SQLException("not supported");
}
return executeUpdate(sql);
}
public int executeUpdate(String sql, int colIndexes[])
throws SQLException {
throw new SQLException("not supported");
}
public int executeUpdate(String sql, String colIndexes[])
throws SQLException {
throw new SQLException("not supported");
}
public boolean execute(String sql, int autokeys)
throws SQLException {
if (autokeys != Statement.NO_GENERATED_KEYS) {
throw new SQLException("not supported");
}
return execute(sql);
}
public boolean execute(String sql, int colIndexes[])
throws SQLException {
throw new SQLException("not supported");
}
public boolean execute(String sql, String colIndexes[])
throws SQLException {
throw new SQLException("not supported");
}
public int getResultSetHoldability() throws SQLException {
return ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
}
| apache-2.0 |
HyVar/DarwinSPL | plugins/eu.hyvar.feature.expression/src/eu/hyvar/feature/expression/util/HyExpressionResolverUtil.java | 6310 | package eu.hyvar.feature.expression.util;
import java.util.Date;
import org.eclipse.emf.ecore.EObject;
//import org.eclipse.ui.IEditorPart;
//import org.eclipse.ui.IEditorReference;
//import org.eclipse.ui.IWorkbench;
//import org.eclipse.ui.IWorkbenchPage;
//import org.eclipse.ui.IWorkbenchWindow;
//import org.eclipse.ui.PlatformUI;
import eu.hyvar.context.HyContextModel;
import eu.hyvar.context.HyContextualInformation;
import eu.hyvar.context.information.util.ContextInformationResolverUtil;
import eu.hyvar.dataValues.HyEnum;
import eu.hyvar.feature.HyFeature;
import eu.hyvar.feature.HyFeatureAttribute;
import eu.hyvar.feature.HyFeatureModel;
import eu.hyvar.feature.HyVersion;
import eu.hyvar.feature.data.util.IdentifierWithDateUtil;
import eu.hyvar.feature.data.util.Tuple;
import eu.hyvar.feature.expression.HyAbstractFeatureReferenceExpression;
import eu.hyvar.feature.expression.HyVersionRestriction;
import eu.hyvar.feature.util.HyFeatureModelWellFormednessException;
import eu.hyvar.feature.util.HyFeatureResolverUtil;
public class HyExpressionResolverUtil {
// private final static String FEATUREMODEL_EDITOR_EXTENSIONPOINT_ID = "eu.hyvar.feature.expression.FeatureModelEditor";
public static HyFeature resolveFeature(String identifier, EObject elementFromAccompanyingResource) {
if (elementFromAccompanyingResource == null) {
return null;
}
HyFeatureModel featureModel = HyFeatureResolverUtil
.getAccompanyingFeatureModel(elementFromAccompanyingResource);
return resolveFeatureFromFeatureModel(identifier, featureModel);
}
public static HyFeature resolveFeatureFromFeatureModel(String identifier, HyFeatureModel featureModel) {
if (identifier == null) {
return null;
}
identifier = removeQuotationMarks(identifier);
Tuple<String, Date> identifierAndDate = IdentifierWithDateUtil.getIdentifierAndDate(identifier);
if (identifierAndDate.getSecondEntry() == null) {
identifierAndDate.setSecondEntry(new Date());
}
try {
return HyFeatureResolverUtil.resolveFeature(identifierAndDate.getFirstEntry(), featureModel,
identifierAndDate.getSecondEntry());
} catch (HyFeatureModelWellFormednessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static String removeQuotationMarks(String identifier) {
if (identifier.startsWith("\"") && identifier.endsWith("\"")) {
return identifier.substring(1, identifier.length() - 1);
}
return identifier;
}
public static HyVersion resolveVersion(String identifier, HyVersionRestriction container) {
HyFeature feature = null;
HyAbstractFeatureReferenceExpression featureReference = container.getRestrictedFeatureReferenceExpression();
if(featureReference != null) {
feature = featureReference.getFeature();
}
if(identifier == null || feature == null) {
return null;
}
identifier = removeQuotationMarks(identifier);
Tuple<String, Date> identifierAndDate = IdentifierWithDateUtil.getIdentifierAndDate(identifier);
if (identifierAndDate.getSecondEntry() == null) {
identifierAndDate.setSecondEntry(new Date());
}
try {
return HyFeatureResolverUtil.resolveVersion(identifierAndDate.getFirstEntry(), feature, identifierAndDate.getSecondEntry());
} catch (HyFeatureModelWellFormednessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static HyFeatureAttribute resolveFeatureAttribute(String identifier, EObject elementFromAccompanyingResource,
HyFeature containingFeature) {
// HyFeatureModel featureModel =
// HyFeatureResolverUtil.getAccompanyingFeatureModel(elementFromAccompanyingResource);
if (identifier == null || containingFeature == null) {
return null;
}
identifier = removeQuotationMarks(identifier);
Tuple<String, Date> identifierAndDate = IdentifierWithDateUtil.getIdentifierAndDate(identifier);
if (identifierAndDate.getSecondEntry() == null) {
identifierAndDate.setSecondEntry(new Date());
}
try {
return HyFeatureResolverUtil.resolveFeatureAttribute(identifierAndDate.getFirstEntry(), containingFeature,
identifierAndDate.getSecondEntry());
} catch (HyFeatureModelWellFormednessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static HyEnum resolveEnum(String identifier, EObject elementFromAccompanyingResource) {
HyEnum resolved = null;
if (identifier == null) {
return null;
}
identifier = removeQuotationMarks(identifier);
// TODO: Ambiguity between Enums in FM and ContextModel
// TODO evolution
HyContextModel contextModel = ContextInformationResolverUtil
.getAccompanyingContextModel(elementFromAccompanyingResource);
if (contextModel != null) {
resolved = ContextInformationResolverUtil.resolveEnum(identifier, contextModel, new Date());
}
if (resolved == null) {
HyFeatureModel featureModel = HyFeatureResolverUtil
.getAccompanyingFeatureModel(elementFromAccompanyingResource);
if (featureModel != null) {
resolved = HyFeatureResolverUtil.resolveEnum(identifier, featureModel, new Date());
}
}
return resolved;
}
public static String deresolveEnum(HyEnum hyEnum) {
if (hyEnum == null) {
return "";
}
return ContextInformationResolverUtil.deresolveEnum(hyEnum);
}
public static HyContextualInformation resolveContextualInformation(String identifier,
EObject elementFromAccompanyingResource) {
if (identifier == null) {
return null;
}
// TODO here fix context resolving!
HyContextModel contextModel = ContextInformationResolverUtil
.getAccompanyingContextModel(elementFromAccompanyingResource);
if (contextModel == null) {
return null;
}
Tuple<String, Date> identifierAndDate = IdentifierWithDateUtil.getIdentifierAndDate(identifier);
if (identifierAndDate.getSecondEntry() == null) {
identifierAndDate.setSecondEntry(new Date());
}
return ContextInformationResolverUtil.resolveContextualInformation(identifierAndDate.getFirstEntry(),
contextModel, identifierAndDate.getSecondEntry());
}
public static String deresolveContextualInformation(HyContextualInformation contextInfo) {
if (contextInfo == null) {
return "";
}
return contextInfo.getId();
}
}
| apache-2.0 |
KidEinstein/giraph | giraph-block-app/src/main/java/org/apache/giraph/block_app/framework/output/BlockOutputDesc.java | 1589 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.giraph.block_app.framework.output;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.Progressable;
/**
* Output description
*
* @param <OW> Writer type
*/
public interface BlockOutputDesc<OW extends BlockOutputWriter> {
/**
* Initialize output and perform any necessary checks
*
* @param jobIdentifier Unique identifier of the job
* @param conf Configuration
*/
void initializeAndCheck(String jobIdentifier, Configuration conf);
/**
* Create writer
*
* @param conf Configuration
* @param hadoopProgressable Progressable to call progress on
* @return Writer
*/
OW createOutputWriter(Configuration conf, Progressable hadoopProgressable);
/**
* Commit everything
*/
void commit();
}
| apache-2.0 |
janstey/fuse | fabric/fabric-webapp-agent/src/main/java/org/fusesource/fabric/agent/web/FabricWebRegistrationHandler.java | 8221 | /**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.agent.web;
import java.lang.management.ManagementFactory;
import java.util.HashSet;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.MBeanServerDelegate;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.QueryExp;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.zookeeper.CreateMode;
import org.fusesource.fabric.api.FabricService;
import org.fusesource.fabric.zookeeper.ZkPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.fusesource.fabric.zookeeper.utils.ZooKeeperUtils.setData;
public class FabricWebRegistrationHandler implements ConnectionStateListener {
private static final Logger LOGGER = LoggerFactory.getLogger(FabricWebRegistrationHandler.class);
private FabricService fabricService;
private CuratorFramework curator;
private NotificationListener listener;
private NotificationFilter filter;
private MBeanServer mBeanServer;
private int port = -1;
// TODO load from system properties
String containerId = "tomcat1";
String host = "localhost";
public void init() throws Exception {
LOGGER.info("Initialising " + this + " with fabricService: " + fabricService + " and curator: "
+ curator);
if (mBeanServer == null) {
mBeanServer = ManagementFactory.getPlatformMBeanServer();
}
if (mBeanServer != null) {
Object handback = null;
listener = getNotificationListener();
filter = getNotificationFilter();
mBeanServer
.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, listener, filter, handback);
}
findWebAppMBeans();
}
public void destroy() throws Exception {
if (mBeanServer != null) {
if (listener != null) {
mBeanServer.removeNotificationListener(MBeanServerDelegate.DELEGATE_NAME, listener);
}
}
}
/**
* Lets query JMX for any MBeans to define web apps in containers like Tomcat, Jetty, JBoss
*/
protected void findWebAppMBeans() {
try {
if (port < 0) {
// lets try find the port
Set<ObjectName> objectNames = findObjectNames(null, "Catalina:type=Connector,*",
"Tomcat:type=Connector,*");
for (ObjectName objectName : objectNames) {
Object protocol = mBeanServer.getAttribute(objectName, "protocol");
if (protocol != null && protocol instanceof String && protocol.toString().toLowerCase()
.startsWith("http/")) {
Object portValue = mBeanServer.getAttribute(objectName, "port");
if (portValue instanceof Number) {
port = ((Number)portValue).intValue();
if (port > 0) {
break;
}
}
}
}
}
if (port > 0 && curator != null) {
Set<ObjectName> objectNames = findObjectNames(null, "Catalina:j2eeType=WebModule,*", "Tomcat:j2eeType=WebModule,*");
for (ObjectName objectName : objectNames) {
Object pathValue = mBeanServer.getAttribute(objectName, "path");
if (pathValue != null && pathValue instanceof String) {
String path = pathValue.toString();
String url = "http://" + host + ":" + port + path;
String name = path;
while (name.startsWith("/")) {
name = name.substring(1);
}
// lets try figure out the group / version...
String version = "unknown";
String[] versionSplit = name.split("-\\d\\.\\d");
if (versionSplit.length < 2) {
versionSplit = name.split("-SNAPSHOT");
}
if (versionSplit.length > 1) {
String justName =versionSplit[0];
version = name.substring(justName.length() + 1);
name = justName;
}
LOGGER.info("Found name " + name + " version " + version + " url " + url + " from path " + path);
if (name.length() > 0) {
registerWebapp(name, version, url);
}
}
}
}
} catch (Throwable e) {
LOGGER.warn("Failed to poll for web app mbeans " + e, e);
}
}
protected Set<ObjectName> findObjectNames(QueryExp queryExp, String... objectNames)
throws MalformedObjectNameException {
Set<ObjectName> answer = new HashSet<ObjectName>();
for (String objectName : objectNames) {
Set<ObjectName> set = mBeanServer.queryNames(new ObjectName(objectName), queryExp);
if (set != null) {
answer.addAll(set);
}
}
return answer;
}
protected NotificationListener getNotificationListener() {
return new NotificationListener() {
@Override
public void handleNotification(Notification notification, Object handback) {
findWebAppMBeans();
}
};
}
protected NotificationFilter getNotificationFilter() {
return new NotificationFilter() {
@Override
public boolean isNotificationEnabled(Notification notification) {
return true;
}
};
}
/**
* Registers a webapp to the registry.
*/
protected void registerWebapp(String name, String version, String url) {
String json = "{\"containerId\":\"" + containerId + "\", \"services\":[\"" + url
+ "\"],\"container\":\"" + containerId + "\"}";
try {
String zkPath = ZkPath.WEBAPPS_CONTAINER.getPath(name, version, containerId);
setData(curator, zkPath, json, CreateMode.EPHEMERAL);
} catch (Exception e) {
LOGGER.error("Failed to register webapp {}.", json, e);
}
}
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
switch (newState) {
case CONNECTED:
case RECONNECTED:
this.curator = client;
onConnected();
break;
default:
onDisconnected();
this.curator = null;
break;
}
}
public void onConnected() {
}
public void onDisconnected() {
}
public FabricService getFabricService() {
return fabricService;
}
public void setFabricService(FabricService fabricService) {
this.fabricService = fabricService;
}
public CuratorFramework getCurator() {
return curator;
}
public void setCurator(CuratorFramework curator) {
this.curator = curator;
}
}
| apache-2.0 |
fredfeng/navigator | src/test/java/leaks/StraightLineCaseSplitNoRefute/Node.java | 142 | package leaks.StraightLineCaseSplitNoRefute;
class Node {
public Node next;
public Object data;
public Node() {}
}
| apache-2.0 |
hgschmie/presto | presto-product-tests-launcher/src/main/java/io/prestosql/tests/product/launcher/Extensions.java | 1050 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.tests.product.launcher;
import com.google.inject.Module;
import static java.util.Objects.requireNonNull;
public final class Extensions
{
private final Module additionalEnvironments;
public Extensions(Module additionalEnvironments)
{
this.additionalEnvironments = requireNonNull(additionalEnvironments, "additionalEnvironments is null");
}
public Module getAdditionalEnvironments()
{
return additionalEnvironments;
}
}
| apache-2.0 |
anhhnguyen206/RxSocial | rx-social/src/test/java/io/anhnguyen/rxsocial/ExampleUnitTest.java | 314 | package io.anhnguyen.rxsocial;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
jean-merelis/keycloak | testsuite/integration/src/test/java/org/keycloak/testsuite/OAuthClient.java | 22846 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.junit.Assert;
import org.keycloak.OAuth2Constants;
import org.keycloak.RSATokenVerifier;
import org.keycloak.common.VerificationException;
import org.keycloak.constants.AdapterConstants;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.RefreshToken;
import org.keycloak.util.BasicAuthHelper;
import org.keycloak.common.util.PemUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import javax.ws.rs.core.UriBuilder;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class OAuthClient {
private WebDriver driver;
private String baseUrl = Constants.AUTH_SERVER_ROOT;
private String realm = "test";
private String clientId = "test-app";
private String redirectUri = "http://localhost:8081/app/auth";
private String state = "mystate";
private String scope;
private String uiLocales = null;
private PublicKey realmPublicKey;
private String clientSessionState;
private String clientSessionHost;
public OAuthClient(WebDriver driver) {
this.driver = driver;
try {
JSONObject realmJson = new JSONObject(IOUtils.toString(getClass().getResourceAsStream("/testrealm.json")));
realmPublicKey = PemUtils.decodePublicKey(realmJson.getString("publicKey"));
} catch (Exception e) {
throw new RuntimeException("Failed to retrieve realm public key", e);
}
}
public AuthorizationCodeResponse doLogin(String username, String password) {
openLoginForm();
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.name("login")).click();
return new AuthorizationCodeResponse(this);
}
public void doLoginGrant(String username, String password) {
openLoginForm();
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.name("login")).click();
}
public AccessTokenResponse doAccessTokenRequest(String code, String password) {
CloseableHttpClient client = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(getAccessTokenUrl());
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.AUTHORIZATION_CODE));
if (code != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.CODE, code));
}
if (redirectUri != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.REDIRECT_URI, redirectUri));
}
if (clientId != null && password != null) {
String authorization = BasicAuthHelper.createHeader(clientId, password);
post.setHeader("Authorization", authorization);
} else if (clientId != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, clientId));
}
if (clientSessionState != null) {
parameters.add(new BasicNameValuePair(AdapterConstants.CLIENT_SESSION_STATE, clientSessionState));
}
if (clientSessionHost != null) {
parameters.add(new BasicNameValuePair(AdapterConstants.CLIENT_SESSION_HOST, clientSessionHost));
}
UrlEncodedFormEntity formEntity = null;
try {
formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
post.setEntity(formEntity);
try {
return new AccessTokenResponse(client.execute(post));
} catch (Exception e) {
throw new RuntimeException("Failed to retrieve access token", e);
}
} finally {
closeClient(client);
}
}
public String introspectAccessTokenWithClientCredential(String clientId, String clientSecret, String tokenToIntrospect) {
return introspectTokenWithClientCredential(clientId, clientSecret, "access_token", tokenToIntrospect);
}
public String introspectRefreshTokenWithClientCredential(String clientId, String clientSecret, String tokenToIntrospect) {
return introspectTokenWithClientCredential(clientId, clientSecret, "refresh_token", tokenToIntrospect);
}
public String introspectTokenWithClientCredential(String clientId, String clientSecret, String tokenType, String tokenToIntrospect) {
CloseableHttpClient client = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(getTokenIntrospectionUrl());
String authorization = BasicAuthHelper.createHeader(clientId, clientSecret);
post.setHeader("Authorization", authorization);
List<NameValuePair> parameters = new LinkedList<>();
parameters.add(new BasicNameValuePair("token", tokenToIntrospect));
parameters.add(new BasicNameValuePair("token_type_hint", tokenType));
UrlEncodedFormEntity formEntity;
try {
formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
post.setEntity(formEntity);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
client.execute(post).getEntity().writeTo(out);
return new String(out.toByteArray());
} catch (Exception e) {
throw new RuntimeException("Failed to retrieve access token", e);
}
} finally {
closeClient(client);
}
}
public AccessTokenResponse doGrantAccessTokenRequest(String clientSecret, String username, String password) throws Exception {
return doGrantAccessTokenRequest(realm, username, password, null, clientId, clientSecret);
}
public AccessTokenResponse doGrantAccessTokenRequest(String realm, String username, String password, String totp,
String clientId, String clientSecret) throws Exception {
CloseableHttpClient client = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(getResourceOwnerPasswordCredentialGrantUrl(realm));
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD));
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
if (totp != null) {
parameters.add(new BasicNameValuePair("totp", totp));
}
if (clientSecret != null) {
String authorization = BasicAuthHelper.createHeader(clientId, clientSecret);
post.setHeader("Authorization", authorization);
} else {
parameters.add(new BasicNameValuePair("client_id", clientId));
}
if (clientSessionState != null) {
parameters.add(new BasicNameValuePair(AdapterConstants.CLIENT_SESSION_STATE, clientSessionState));
}
if (clientSessionHost != null) {
parameters.add(new BasicNameValuePair(AdapterConstants.CLIENT_SESSION_HOST, clientSessionHost));
}
if (scope != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.SCOPE, scope));
}
UrlEncodedFormEntity formEntity;
try {
formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
post.setEntity(formEntity);
return new AccessTokenResponse(client.execute(post));
} finally {
closeClient(client);
}
}
public AccessTokenResponse doClientCredentialsGrantAccessTokenRequest(String clientSecret) throws Exception {
CloseableHttpClient client = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(getServiceAccountUrl());
String authorization = BasicAuthHelper.createHeader(clientId, clientSecret);
post.setHeader("Authorization", authorization);
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
if (scope != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.SCOPE, scope));
}
UrlEncodedFormEntity formEntity;
try {
formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
post.setEntity(formEntity);
return new AccessTokenResponse(client.execute(post));
} finally {
closeClient(client);
}
}
public HttpResponse doLogout(String refreshToken, String clientSecret) throws IOException {
CloseableHttpClient client = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(getLogoutUrl(null, null));
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
if (refreshToken != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken));
}
if (clientId != null && clientSecret != null) {
String authorization = BasicAuthHelper.createHeader(clientId, clientSecret);
post.setHeader("Authorization", authorization);
} else if (clientId != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, clientId));
}
UrlEncodedFormEntity formEntity;
try {
formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
post.setEntity(formEntity);
return client.execute(post);
} finally {
closeClient(client);
}
}
public AccessTokenResponse doRefreshTokenRequest(String refreshToken, String password) {
CloseableHttpClient client = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(getRefreshTokenUrl());
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.REFRESH_TOKEN));
if (refreshToken != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.REFRESH_TOKEN, refreshToken));
}
if (clientId != null && password != null) {
String authorization = BasicAuthHelper.createHeader(clientId, password);
post.setHeader("Authorization", authorization);
} else if (clientId != null) {
parameters.add(new BasicNameValuePair(OAuth2Constants.CLIENT_ID, clientId));
}
if (clientSessionState != null) {
parameters.add(new BasicNameValuePair(AdapterConstants.CLIENT_SESSION_STATE, clientSessionState));
}
if (clientSessionHost != null) {
parameters.add(new BasicNameValuePair(AdapterConstants.CLIENT_SESSION_HOST, clientSessionHost));
}
UrlEncodedFormEntity formEntity;
try {
formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
post.setEntity(formEntity);
try {
return new AccessTokenResponse(client.execute(post));
} catch (Exception e) {
throw new RuntimeException("Failed to retrieve access token", e);
}
} finally {
closeClient(client);
}
}
public void closeClient(CloseableHttpClient client) {
try {
client.close();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public AccessToken verifyToken(String token) {
try {
return RSATokenVerifier.verifyToken(token, realmPublicKey, baseUrl + "/realms/" + realm);
} catch (VerificationException e) {
throw new RuntimeException("Failed to verify token", e);
}
}
public RefreshToken verifyRefreshToken(String refreshToken) {
try {
JWSInput jws = new JWSInput(refreshToken);
if (!RSAProvider.verify(jws, realmPublicKey)) {
throw new RuntimeException("Invalid refresh token");
}
return jws.readJsonContent(RefreshToken.class);
} catch (Exception e) {
throw new RuntimeException("Invalid refresh token", e);
}
}
public String getClientId() {
return clientId;
}
public String getCurrentRequest() {
return driver.getCurrentUrl().substring(0, driver.getCurrentUrl().indexOf('?'));
}
public URI getCurrentUri() {
try {
return new URI(driver.getCurrentUrl());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Map<String, String> getCurrentQuery() {
Map<String, String> m = new HashMap<String, String>();
List<NameValuePair> pairs = URLEncodedUtils.parse(getCurrentUri(), "UTF-8");
for (NameValuePair p : pairs) {
m.put(p.getName(), p.getValue());
}
return m;
}
public void openLoginForm() {
driver.navigate().to(getLoginFormUrl());
}
public void openLogout() {
UriBuilder b = OIDCLoginProtocolService.logoutUrl(UriBuilder.fromUri(baseUrl));
if (redirectUri != null) {
b.queryParam(OAuth2Constants.REDIRECT_URI, redirectUri);
}
driver.navigate().to(b.build(realm).toString());
}
public String getRedirectUri() {
return redirectUri;
}
public String getLoginFormUrl() {
UriBuilder b = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri(baseUrl));
b.queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE);
if (clientId != null) {
b.queryParam(OAuth2Constants.CLIENT_ID, clientId);
}
if (redirectUri != null) {
b.queryParam(OAuth2Constants.REDIRECT_URI, redirectUri);
}
if (state != null) {
b.queryParam(OAuth2Constants.STATE, state);
}
if(uiLocales != null){
b.queryParam(OAuth2Constants.UI_LOCALES_PARAM, uiLocales);
}
if (scope != null) {
b.queryParam(OAuth2Constants.SCOPE, scope);
}
return b.build(realm).toString();
}
public String getAccessTokenUrl() {
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
public String getTokenIntrospectionUrl() {
UriBuilder b = OIDCLoginProtocolService.tokenIntrospectionUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
public String getLogoutUrl(String redirectUri, String sessionState) {
UriBuilder b = OIDCLoginProtocolService.logoutUrl(UriBuilder.fromUri(baseUrl));
if (redirectUri != null) {
b.queryParam(OAuth2Constants.REDIRECT_URI, redirectUri);
}
if (sessionState != null) {
b.queryParam("session_state", sessionState);
}
return b.build(realm).toString();
}
public String getResourceOwnerPasswordCredentialGrantUrl() {
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
public String getResourceOwnerPasswordCredentialGrantUrl(String realm) {
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
public String getServiceAccountUrl() {
return getResourceOwnerPasswordCredentialGrantUrl();
}
public String getRefreshTokenUrl() {
UriBuilder b = OIDCLoginProtocolService.tokenUrl(UriBuilder.fromUri(baseUrl));
return b.build(realm).toString();
}
public OAuthClient realm(String realm) {
this.realm = realm;
return this;
}
public OAuthClient realmPublicKey(PublicKey key) {
this.realmPublicKey = key;
return this;
}
public OAuthClient clientId(String clientId) {
this.clientId = clientId;
return this;
}
public OAuthClient redirectUri(String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
public OAuthClient state(String state) {
this.state = state;
return this;
}
public OAuthClient scope(String scope) {
this.scope = scope;
return this;
}
public OAuthClient uiLocales(String uiLocales){
this.uiLocales = uiLocales;
return this;
}
public OAuthClient clientSessionState(String client_session_state) {
this.clientSessionState = client_session_state;
return this;
}
public OAuthClient clientSessionHost(String client_session_host) {
this.clientSessionHost = client_session_host;
return this;
}
public String getRealm() {
return realm;
}
public static class AuthorizationCodeResponse {
private boolean isRedirected;
private String code;
private String state;
private String error;
public AuthorizationCodeResponse(OAuthClient client) {
isRedirected = client.getCurrentRequest().equals(client.getRedirectUri());
code = client.getCurrentQuery().get(OAuth2Constants.CODE);
state = client.getCurrentQuery().get(OAuth2Constants.STATE);
error = client.getCurrentQuery().get(OAuth2Constants.ERROR);
}
public boolean isRedirected() {
return isRedirected;
}
public String getCode() {
return code;
}
public String getState() {
return state;
}
public String getError() {
return error;
}
}
public static class AccessTokenResponse {
private int statusCode;
private String accessToken;
private String tokenType;
private int expiresIn;
private int refreshExpiresIn;
private String refreshToken;
private String error;
private String errorDescription;
public AccessTokenResponse(HttpResponse response) throws Exception {
statusCode = response.getStatusLine().getStatusCode();
if (!"application/json".equals(response.getHeaders("Content-Type")[0].getValue())) {
Assert.fail("Invalid content type");
}
String s = IOUtils.toString(response.getEntity().getContent());
JSONObject responseJson = new JSONObject(s);
if (statusCode == 200) {
accessToken = responseJson.getString("access_token");
tokenType = responseJson.getString("token_type");
expiresIn = responseJson.getInt("expires_in");
refreshExpiresIn = responseJson.getInt("refresh_expires_in");
if (responseJson.has(OAuth2Constants.REFRESH_TOKEN)) {
refreshToken = responseJson.getString(OAuth2Constants.REFRESH_TOKEN);
}
} else {
error = responseJson.getString(OAuth2Constants.ERROR);
errorDescription = responseJson.has(OAuth2Constants.ERROR_DESCRIPTION) ? responseJson.getString(OAuth2Constants.ERROR_DESCRIPTION) : null;
}
}
public String getAccessToken() {
return accessToken;
}
public String getError() {
return error;
}
public String getErrorDescription() {
return errorDescription;
}
public int getExpiresIn() {
return expiresIn;
}
public int getRefreshExpiresIn() {
return refreshExpiresIn;
}
public int getStatusCode() {
return statusCode;
}
public String getRefreshToken() {
return refreshToken;
}
public String getTokenType() {
return tokenType;
}
}
}
| apache-2.0 |
mt0803/squall | squall-core/src/main/java/ch/epfl/data/squall/components/theta/ThetaJoinComponentFactory.java | 1892 | /*
* Copyright (c) 2011-2015 EPFL DATA Laboratory
* Copyright (c) 2014-2015 The Squall Collaboration (see NOTICE)
*
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.epfl.data.squall.components.theta;
import ch.epfl.data.squall.components.Component;
import ch.epfl.data.squall.components.JoinerComponent;
import ch.epfl.data.squall.query_plans.QueryBuilder;
import ch.epfl.data.squall.utilities.SystemParameters;
public class ThetaJoinComponentFactory {
public static JoinerComponent createThetaJoinOperator(int thetaJoinType,
Component firstParent, Component secondParent,
QueryBuilder queryBuilder) {
JoinerComponent result = null;
if (thetaJoinType == SystemParameters.STATIC_CIS) {
result = new ThetaJoinComponent(firstParent, secondParent, false);
} else if (thetaJoinType == SystemParameters.EPOCHS_CIS) {
result = new AdaptiveThetaJoinComponent(firstParent, secondParent);
} else if (thetaJoinType == SystemParameters.STATIC_CS) {
result = new ThetaJoinComponent(firstParent, secondParent, true);
} else if (thetaJoinType == SystemParameters.EPOCHS_CS) {
result = new AdaptiveThetaJoinComponent(firstParent, secondParent);
} else {
throw new RuntimeException("Unsupported Thtea Join Type");
}
queryBuilder.add(result);
return result;
}
} | apache-2.0 |
gdeignacio/sgtsic | sgtsic/src/main/java/es/caib/sgtsic/docx/MemoryPackagePartOutputStream.java | 1531 | package es.caib.sgtsic.docx;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Créé un flux de sortie pour les parties de type MemoryPackagePart.
*
* @author Julien Chable
*/
public final class MemoryPackagePartOutputStream extends OutputStream {
private MemoryPackagePart part;
private ByteArrayOutputStream buff;
public MemoryPackagePartOutputStream(MemoryPackagePart part) {
this.part = part;
buff = new ByteArrayOutputStream();
}
@Override
public void write(int b) throws IOException {
buff.write(b);
}
@Override
public void close() throws IOException {
this.flush();
}
@Override
public void flush() throws IOException {
buff.flush();
//Willy: i dont know why the following cause an error
//so i replace it with temporary solution that writes the data to part.data
//byte[] newArray = new byte[part.data.length + buff.size()];
//System.arraycopy(part.data, 0, newArray, 0, part.data.length);
//byte[] buffArr = buff.toByteArray();
//System
// .arraycopy(buffArr, 0, newArray, part.data.length,
// buffArr.length);
part.createArray(buff.size());
byte[] buffArr = buff.toByteArray();
System
.arraycopy(buffArr, 0, part.data, 0,
buffArr.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
buff.write(b, off, len);
}
@Override
public void write(byte[] b) throws IOException {
buff.write(b);
}
} | apache-2.0 |
shahramgdz/hibernate-validator | engine/src/test/java/org/hibernate/validator/test/internal/engine/methodvalidation/xml/SameMethodOrConstructorDefinedTwiceTest.java | 1580 | /*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.test.internal.engine.methodvalidation.xml;
import javax.validation.Configuration;
import javax.validation.ValidationException;
import org.testng.annotations.Test;
import org.hibernate.validator.testutil.TestForIssue;
import org.hibernate.validator.testutils.ValidatorUtil;
/**
* @author Hardy Ferentschik
*/
public class SameMethodOrConstructorDefinedTwiceTest {
@Test(expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "HV000137.*")
@TestForIssue(jiraKey = "HV-373")
public void testSameMethodSpecifiedMoreThanOnceThrowsException() {
final Configuration<?> configuration = ValidatorUtil.getConfiguration();
configuration.addMapping(
SameMethodOrConstructorDefinedTwiceTest.class.getResourceAsStream(
"same-method-defined-twice.xml"
)
);
configuration.buildValidatorFactory();
}
@Test(expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "HV000138.*")
@TestForIssue(jiraKey = "HV-373")
public void testSameConstructorSpecifiedMoreThanOnceThrowsException() {
final Configuration<?> configuration = ValidatorUtil.getConfiguration();
configuration.addMapping(
SameMethodOrConstructorDefinedTwiceTest.class.getResourceAsStream(
"same-constructor-defined-twice.xml"
)
);
configuration.buildValidatorFactory();
}
}
| apache-2.0 |
ascherbakoff/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/datastructures/IgniteLockAbstractSelfTest.java | 50903 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.datastructures;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteCondition;
import org.apache.ignite.IgniteCountDownLatch;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteInterruptedException;
import org.apache.ignite.IgniteLock;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.IgniteKernal;
import org.apache.ignite.internal.util.GridConcurrentHashSet;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.internal.util.typedef.PA;
import org.apache.ignite.lang.IgniteCallable;
import org.apache.ignite.lang.IgniteClosure;
import org.apache.ignite.lang.IgniteFuture;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.resources.LoggerResource;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.transactions.Transaction;
import org.jetbrains.annotations.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMode.LOCAL;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
/**
* Cache reentrant lock self test.
*/
public abstract class IgniteLockAbstractSelfTest extends IgniteAtomicsAbstractTest
implements Externalizable {
/** */
private static final int NODES_CNT = 4;
/** */
protected static final int THREADS_CNT = 5;
/** */
private static final Random RND = new Random();
/** */
@Rule
public final ExpectedException exception = ExpectedException.none();
/** {@inheritDoc} */
@Override protected int gridCount() {
return NODES_CNT;
}
/**
* @throws Exception If failed.
*/
@Test
public void testReentrantLock() throws Exception {
checkReentrantLock(false);
checkReentrantLock(true);
}
/**
* @throws Exception If failed.
*/
@Test
public void testFailover() throws Exception {
if (atomicsCacheMode() == LOCAL)
return;
checkFailover(true, false);
checkFailover(false, false);
checkFailover(true, true);
checkFailover(false, true);
}
/**
* Implementation of ignite data structures internally uses special system caches, need make sure
* that transaction on these system caches do not intersect with transactions started by user.
*
* @throws Exception If failed.
*/
@Test
public void testIsolation() throws Exception {
Ignite ignite = grid(0);
CacheConfiguration cfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
cfg.setName("myCache");
cfg.setAtomicityMode(TRANSACTIONAL);
cfg.setWriteSynchronizationMode(FULL_SYNC);
IgniteCache<Integer, Integer> cache = ignite.getOrCreateCache(cfg);
try {
IgniteLock lock = ignite.reentrantLock("lock", true, true, true);
try (Transaction tx = ignite.transactions().txStart()) {
cache.put(1, 1);
boolean success = lock.tryLock(1, MILLISECONDS);
assertTrue(success);
tx.rollback();
}
assertEquals(0, cache.size());
assertTrue(lock.isLocked());
lock.unlock();
assertFalse(lock.isLocked());
lock.close();
assertTrue(lock.removed());
}
finally {
ignite.destroyCache(cfg.getName());
}
}
/**
* @param failoverSafe Failover safe flag.
* @throws Exception If failed.
*/
private void checkFailover(final boolean failoverSafe, final boolean fair) throws Exception {
IgniteEx g = startGrid(NODES_CNT + 1);
// For vars locality.
{
// Ensure not exists.
assert g.reentrantLock("lock", failoverSafe, fair, false) == null;
IgniteLock lock = g.reentrantLock("lock", failoverSafe, fair, true);
lock.lock();
assert lock.tryLock();
assertEquals(2, lock.getHoldCount());
}
Ignite g0 = grid(0);
final IgniteLock lock0 = g0.reentrantLock("lock", false, fair, false);
assert !lock0.tryLock();
assertEquals(0, lock0.getHoldCount());
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
try {
lock0.lock();
info("Acquired in separate thread.");
// Lock is acquired silently only in failoverSafe mode.
assertTrue(failoverSafe);
lock0.unlock();
info("Released lock in separate thread.");
}
catch (IgniteException e) {
if (!failoverSafe)
info("Ignored expected exception: " + e);
else
throw e;
}
return null;
}
},
1);
Thread.sleep(100);
g.close();
fut.get(500);
lock0.close();
}
/**
* @throws Exception If failed.
*/
private void checkReentrantLock(final boolean fair) throws Exception {
// Test API.
checkLock(fair);
checkFailoverSafe(fair);
// Test main functionality.
IgniteLock lock1 = grid(0).reentrantLock("lock", true, fair, true);
assertFalse(lock1.isLocked());
lock1.lock();
IgniteFuture<Object> fut = grid(0).compute().callAsync(new IgniteCallable<Object>() {
@IgniteInstanceResource
private Ignite ignite;
@LoggerResource
private IgniteLogger log;
@Nullable @Override public Object call() throws Exception {
// Test reentrant lock in multiple threads on each node.
IgniteInternalFuture<?> fut = GridTestUtils.runMultiThreadedAsync(
new Callable<Object>() {
@Nullable @Override public Object call() throws Exception {
IgniteLock lock = ignite.reentrantLock("lock", true, fair, true);
assert lock != null;
log.info("Thread is going to wait on reentrant lock: " + Thread.currentThread().getName());
assert lock.tryLock(1, MINUTES);
log.info("Thread is again runnable: " + Thread.currentThread().getName());
lock.unlock();
return null;
}
},
5,
"test-thread"
);
fut.get();
return null;
}
});
Thread.sleep(3000);
assert lock1.isHeldByCurrentThread();
assert lock1.getHoldCount() == 1;
lock1.lock();
assert lock1.isHeldByCurrentThread();
assert lock1.getHoldCount() == 2;
lock1.unlock();
lock1.unlock();
// Ensure there are no hangs.
fut.get();
// Test operations on removed lock.
lock1.close();
checkRemovedReentrantLock(lock1);
}
/**
* @param lock IgniteLock.
* @throws Exception If failed.
*/
protected void checkRemovedReentrantLock(final IgniteLock lock) throws Exception {
assert GridTestUtils.waitForCondition(new PA() {
@Override public boolean apply() {
return lock.removed();
}
}, 5000);
assert lock.removed();
}
/**
* This method only checks if parameter of new reentrant lock is initialized properly.
* For tests considering failure recovery see @GridCachePartitionedNodeFailureSelfTest.
*
* @throws Exception Exception.
*/
private void checkFailoverSafe(final boolean fair) throws Exception {
// Checks only if reentrant lock is initialized properly
IgniteLock lock = createReentrantLock("rmv", true, fair);
assert lock.isFailoverSafe();
removeReentrantLock("rmv", fair);
IgniteLock lock1 = createReentrantLock("rmv1", false, fair);
assert !lock1.isFailoverSafe();
removeReentrantLock("rmv1", fair);
}
/**
* @throws Exception Exception.
*/
private void checkLock(final boolean fair) throws Exception {
// Check only 'false' cases here. Successful lock is tested over the grid.
final IgniteLock lock = createReentrantLock("acquire", false, fair);
lock.lock();
IgniteInternalFuture fut = GridTestUtils.runAsync(new Callable<Void>() {
@Override public Void call() throws Exception {
assertNotNull(lock);
assert !lock.tryLock();
assert !lock.tryLock(10, MICROSECONDS);
return null;
}
});
fut.get();
lock.unlock();
removeReentrantLock("acquire", fair);
}
/**
* @param lockName Reentrant lock name.
* @param failoverSafe FailoverSafe flag.
* @param fair Fairness flag.
* @return New distributed reentrant lock.
* @throws Exception If failed.
*/
private IgniteLock createReentrantLock(String lockName, boolean failoverSafe, boolean fair)
throws Exception {
IgniteLock lock = grid(RND.nextInt(NODES_CNT)).reentrantLock(lockName, failoverSafe, fair, true);
// Test initialization.
assert lockName.equals(lock.name());
assert !lock.isLocked();
assert lock.isFailoverSafe() == failoverSafe;
assert lock.isFair() == fair;
return lock;
}
/**
* @param lockName Reentrant lock name.
* @throws Exception If failed.
*/
private void removeReentrantLock(String lockName, final boolean fair)
throws Exception {
IgniteLock lock = grid(RND.nextInt(NODES_CNT)).reentrantLock(lockName, false, fair, true);
assert lock != null;
// Remove lock on random node.
IgniteLock lock0 = grid(RND.nextInt(NODES_CNT)).reentrantLock(lockName, false, fair, true);
assertNotNull(lock0);
lock0.close();
// Ensure reentrant lock is removed on all nodes.
for (Ignite g : G.allGrids())
assertNull(((IgniteKernal)g).context().dataStructures().reentrantLock(lockName, null, false, fair, false));
checkRemovedReentrantLock(lock);
}
/**
* @throws Exception If failed.
*/
@Test
public void testLockSerialization() throws Exception {
final IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
info("Lock created: " + lock);
lock.isFailoverSafe();
lock.isFair();
grid(ThreadLocalRandom.current().nextInt(G.allGrids().size())).compute().broadcast(new IgniteCallable<Object>() {
@Nullable @Override public Object call() throws Exception {
Thread.sleep(1000);
lock.lock();
try {
info("Inside lock: " + lock.getHoldCount());
}
finally {
lock.unlock();
}
return null;
}
});
}
/**
* @throws Exception If failed.
*/
@Test
public void testInitialization() throws Exception {
// Test #name() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertEquals("lock", lock.name());
lock.close();
}
// Test #isFailoverSafe() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
info("Lock created: " + lock);
assertTrue(lock.isFailoverSafe());
lock.close();
}
// Test #isFair() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertTrue(lock.isFair());
lock.close();
}
// Test #isBroken() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertFalse(lock.isBroken());
lock.close();
}
// Test #getOrCreateCondition(String ) method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertNotNull(lock.getOrCreateCondition("condition"));
lock.close();
}
// Test #getHoldCount() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertEquals(0, lock.getHoldCount());
lock.close();
}
// Test #isHeldByCurrentThread() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertFalse(lock.isHeldByCurrentThread());
lock.close();
}
// Test #isLocked() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertFalse(lock.isLocked());
lock.close();
}
// Test #hasQueuedThreads() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertFalse(lock.hasQueuedThreads());
lock.close();
}
// Test #hasQueuedThread(Thread ) method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertFalse(lock.hasQueuedThread(Thread.currentThread()));
lock.close();
}
// Test #hasWaiters(IgniteCondition ) method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
try {
IgniteCondition cond = grid(0).reentrantLock("lock2", true, true, true).getOrCreateCondition("cond");
lock.hasWaiters(cond);
fail("Condition not associated with this lock passed as argument.");
}
catch (IllegalArgumentException ignored) {
info("IllegalArgumentException thrown as it should be.");
}
try {
IgniteCondition cond = lock.getOrCreateCondition("condition");
lock.hasWaiters(cond);
fail("This method should throw exception when lock is not held.");
}
catch (IllegalMonitorStateException ignored) {
info("IllegalMonitorStateException thrown as it should be.");
}
lock.close();
}
// Test #getWaitQueueLength(IgniteCondition ) method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
try {
IgniteCondition cond = grid(0).reentrantLock("lock2", true, true, true).getOrCreateCondition("cond");
lock.getWaitQueueLength(cond);
fail("Condition not associated with this lock passed as argument.");
}
catch (IllegalArgumentException ignored) {
info("IllegalArgumentException thrown as it should be.");
}
try {
IgniteCondition cond = lock.getOrCreateCondition("condition");
lock.getWaitQueueLength(cond);
fail("This method should throw exception when lock is not held.");
}
catch (IllegalMonitorStateException ignored) {
info("IllegalMonitorStateException thrown as it should be.");
}
lock.close();
}
// Test #lock() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
lock.lock();
lock.unlock();
lock.close();
}
// Test #lockInterruptibly() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
lock.lockInterruptibly();
lock.unlock();
lock.close();
}
// Test #tryLock() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
boolean success = lock.tryLock();
assertTrue(success);
lock.unlock();
lock.close();
}
// Test #tryLock(long, TimeUnit) method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
boolean success = lock.tryLock(1, MILLISECONDS);
assertTrue(success);
lock.unlock();
lock.close();
}
// Test #unlock() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
try {
lock.unlock();
fail("This method should throw exception when lock is not held.");
}
catch (IllegalMonitorStateException ignored) {
info("IllegalMonitorStateException thrown as it should be.");
}
lock.close();
}
// Test #removed() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
assertFalse(lock.removed());
lock.close();
assertTrue(lock.removed());
}
// Test #close() method.
{
IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);
lock.close();
assertTrue(lock.removed());
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testReentrantLockMultinode1() throws Exception {
testReentrantLockMultinode1(false);
testReentrantLockMultinode1(true);
}
/**
* @throws Exception If failed.
*/
private void testReentrantLockMultinode1(final boolean fair) throws Exception {
if (gridCount() == 1)
return;
IgniteLock lock = grid(0).reentrantLock("s1", true, fair, true);
List<IgniteInternalFuture<?>> futs = new ArrayList<>();
for (int i = 0; i < gridCount(); i++) {
final Ignite ignite = grid(i);
futs.add(GridTestUtils.runAsync(new Callable<Void>() {
@Override public Void call() throws Exception {
IgniteLock lock = ignite.reentrantLock("s1", true, fair, false);
assertNotNull(lock);
IgniteCondition cond1 = lock.getOrCreateCondition("c1");
IgniteCondition cond2 = lock.getOrCreateCondition("c2");
try {
boolean wait = lock.tryLock(30_000, MILLISECONDS);
assertTrue(wait);
cond2.signal();
cond1.await();
}
finally {
lock.unlock();
}
return null;
}
}));
}
boolean done = false;
while (!done) {
done = true;
for (IgniteInternalFuture<?> fut : futs) {
if (!fut.isDone())
done = false;
}
try {
lock.lock();
lock.getOrCreateCondition("c1").signal();
lock.getOrCreateCondition("c2").await(10, MILLISECONDS);
}
finally {
lock.unlock();
}
}
for (IgniteInternalFuture<?> fut : futs)
fut.get(30_000);
}
/**
* @throws Exception If failed.
*/
@Test
public void testLockInterruptibly() throws Exception {
testLockInterruptibly(false);
testLockInterruptibly(true);
}
/**
* @throws Exception If failed.
*/
private void testLockInterruptibly(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 2;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
lock0.lock();
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
startedThreads.add(Thread.currentThread());
boolean isInterrupted = false;
try {
lock0.lockInterruptibly();
}
catch (IgniteInterruptedException ignored) {
assertFalse(Thread.currentThread().isInterrupted());
isInterrupted = true;
}
finally {
// Assert that thread was interrupted.
assertTrue(isInterrupted);
// Assert that locked is still owned by main thread.
assertTrue(lock0.isLocked());
// Assert that this thread doesn't own the lock.
assertFalse(lock0.isHeldByCurrentThread());
}
return null;
}
}, totalThreads);
// Wait for all threads to attempt to acquire lock.
while (startedThreads.size() != totalThreads) {
Thread.sleep(1000);
}
for (Thread t : startedThreads)
t.interrupt();
fut.get();
lock0.unlock();
assertFalse(lock0.isLocked());
for (Thread t : startedThreads)
assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
/**
* @throws Exception If failed.
*/
@Test
public void testLockInterruptiblyMultinode() throws Exception {
testLockInterruptiblyMultinode(false);
testLockInterruptiblyMultinode(true);
}
/**
* @throws Exception If failed.
*/
private void testLockInterruptiblyMultinode(final boolean fair) throws Exception {
if (gridCount() == 1)
return;
// Initialize reentrant lock.
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
lock0.lock();
// Number of threads, one per node.
final int threadCount = gridCount();
final AtomicLong threadCounter = new AtomicLong(0);
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
final int localNodeId = (int)threadCounter.getAndIncrement();
final Ignite grid = grid(localNodeId);
IgniteClosure<Ignite, Void> closure = new IgniteClosure<Ignite, Void>() {
@Override public Void apply(Ignite ignite) {
final IgniteLock l = ignite.reentrantLock("lock", true, true, true);
final AtomicReference<Thread> thread = new AtomicReference<>();
final AtomicBoolean done = new AtomicBoolean(false);
final AtomicBoolean exceptionThrown = new AtomicBoolean(false);
final IgniteCountDownLatch latch = ignite.countDownLatch("latch", threadCount, false, true);
IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Void>() {
@Override public Void call() throws Exception {
try {
thread.set(Thread.currentThread());
l.lockInterruptibly();
}
catch (IgniteInterruptedException ignored) {
exceptionThrown.set(true);
}
finally {
done.set(true);
}
return null;
}
});
// Wait until l.lock() has been called.
while (!l.hasQueuedThreads()){
// No-op.
}
latch.countDown();
latch.await();
thread.get().interrupt();
while (!done.get()){
// No-op.
}
try {
fut.get();
}
catch (IgniteCheckedException e) {
fail(e.getMessage());
throw new RuntimeException(e);
}
assertTrue(exceptionThrown.get());
return null;
}
};
closure.apply(grid);
return null;
}
}, threadCount);
fut.get();
lock0.unlock();
info("Checking if interrupted threads are removed from global waiting queue...");
// Check if interrupted threads are removed from global waiting queue.
boolean locked = lock0.tryLock(1000, MILLISECONDS);
info("Interrupted threads successfully removed from global waiting queue. ");
assertTrue(locked);
lock0.unlock();
assertFalse(lock0.isLocked());
lock0.close();
}
/**
* @throws Exception If failed.
*/
@Test
public void testLock() throws Exception {
testLock(false);
testLock(true);
}
/**
* @throws Exception If failed.
*/
private void testLock(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 2;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
lock0.lock();
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
startedThreads.add(Thread.currentThread());
boolean isInterrupted = false;
try {
lock0.lock();
}
catch (IgniteInterruptedException ignored) {
isInterrupted = true;
fail("Lock() method is uninterruptible.");
}
finally {
// Assert that thread was not interrupted.
assertFalse(isInterrupted);
// Assert that interrupted flag is set and clear it in order to call unlock().
assertTrue(Thread.interrupted());
// Assert that lock is still owned by this thread.
assertTrue(lock0.isLocked());
// Assert that this thread does own the lock.
assertTrue(lock0.isHeldByCurrentThread());
// Release lock.
lock0.unlock();
}
return null;
}
}, totalThreads);
// Wait for all threads to attempt to acquire lock.
while (startedThreads.size() != totalThreads) {
Thread.sleep(500);
}
for (Thread t : startedThreads)
t.interrupt();
lock0.unlock();
fut.get();
assertFalse(lock0.isLocked());
for (Thread t : startedThreads)
assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
/**
* @throws Exception If failed.
*/
@Test
public void testTryLock() throws Exception {
testTryLock(false);
testTryLock(true);
}
/**
* @throws Exception If failed.
*/
private void testTryLock(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 2;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
lock0.lock();
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
startedThreads.add(Thread.currentThread());
boolean isInterrupted = false;
boolean locked = false;
try {
locked = lock0.tryLock();
}
catch (IgniteInterruptedException ignored) {
isInterrupted = true;
fail("tryLock() method is uninterruptible.");
}
finally {
// Assert that thread was not interrupted.
assertFalse(isInterrupted);
// Assert that lock is locked.
assertTrue(lock0.isLocked());
// Assert that this thread does own the lock.
assertEquals(locked, lock0.isHeldByCurrentThread());
// Release lock.
if (locked)
lock0.unlock();
}
return null;
}
}, totalThreads);
// Wait for all threads to attempt to acquire lock.
while (startedThreads.size() != totalThreads) {
Thread.sleep(500);
}
for (Thread t : startedThreads)
t.interrupt();
fut.get();
lock0.unlock();
assertFalse(lock0.isLocked());
for (Thread t : startedThreads)
assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
/**
* @throws Exception If failed.
*/
@Test
public void testTryLockTimed() throws Exception {
testTryLockTimed(false);
testTryLockTimed(true);
}
/**
* @throws Exception If failed.
*/
private void testTryLockTimed(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 2;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
lock0.lock();
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
startedThreads.add(Thread.currentThread());
boolean isInterrupted = false;
boolean locked = false;
try {
locked = lock0.tryLock(100, TimeUnit.MILLISECONDS);
}
catch (IgniteInterruptedException ignored) {
isInterrupted = true;
}
finally {
// Assert that thread was not interrupted.
assertFalse(isInterrupted);
// Assert that tryLock returned false.
assertFalse(locked);
// Assert that lock is still owned by main thread.
assertTrue(lock0.isLocked());
// Assert that this thread doesn't own the lock.
assertFalse(lock0.isHeldByCurrentThread());
// Release lock.
if (locked)
lock0.unlock();
}
return null;
}
}, totalThreads);
fut.get();
lock0.unlock();
assertFalse(lock0.isLocked());
for (Thread t : startedThreads)
assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
/**
* @throws Exception If failed.
*/
@Test
public void testConditionAwaitUninterruptibly() throws Exception {
testConditionAwaitUninterruptibly(false);
testConditionAwaitUninterruptibly(true);
}
/**
* @throws Exception If failed.
*/
private void testConditionAwaitUninterruptibly(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 2;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
startedThreads.add(Thread.currentThread());
boolean isInterrupted = false;
lock0.lock();
IgniteCondition cond = lock0.getOrCreateCondition("cond");
try {
cond.awaitUninterruptibly();
}
catch (IgniteInterruptedException ignored) {
isInterrupted = true;
}
finally {
// Assert that thread was not interrupted.
assertFalse(isInterrupted);
// Assert that lock is still locked.
assertTrue(lock0.isLocked());
// Assert that this thread does own the lock.
assertTrue(lock0.isHeldByCurrentThread());
// Clear interrupt flag.
assertTrue(Thread.interrupted());
// Release lock.
if (lock0.isHeldByCurrentThread())
lock0.unlock();
}
return null;
}
}, totalThreads);
// Wait for all threads to attempt to acquire lock.
while (startedThreads.size() != totalThreads) {
Thread.sleep(500);
}
lock0.lock();
for (Thread t : startedThreads) {
t.interrupt();
lock0.getOrCreateCondition("cond").signal();
}
lock0.unlock();
fut.get();
assertFalse(lock0.isLocked());
for (Thread t : startedThreads)
assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
/**
* @throws Exception If failed.
*/
@Test
public void testConditionInterruptAwait() throws Exception {
testConditionInterruptAwait(false);
testConditionInterruptAwait(true);
}
/**
* @throws Exception If failed.
*/
private void testConditionInterruptAwait(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 2;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
startedThreads.add(Thread.currentThread());
boolean isInterrupted = false;
lock0.lock();
IgniteCondition cond = lock0.getOrCreateCondition("cond");
try {
cond.await();
}
catch (IgniteInterruptedException ignored) {
isInterrupted = true;
}
finally {
// Assert that thread was interrupted.
assertTrue(isInterrupted);
// Assert that lock is still locked.
assertTrue(lock0.isLocked());
// Assert that this thread does own the lock.
assertTrue(lock0.isHeldByCurrentThread());
// Release lock.
if (lock0.isHeldByCurrentThread())
lock0.unlock();
}
return null;
}
}, totalThreads);
// Wait for all threads to attempt to acquire lock.
while (startedThreads.size() != totalThreads) {
Thread.sleep(500);
}
for (Thread t : startedThreads)
t.interrupt();
fut.get();
assertFalse(lock0.isLocked());
for (Thread t : startedThreads)
assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
/**
* @throws Exception If failed.
*/
@Test
public void testHasQueuedThreads() throws Exception {
testHasQueuedThreads(false);
testHasQueuedThreads(true);
}
/**
* @throws Exception If failed.
*/
private void testHasQueuedThreads(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 5;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
final Set<Thread> finishedThreads = new GridConcurrentHashSet<>();
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
startedThreads.add(Thread.currentThread());
lock0.lock();
// Wait until every thread tries to lock.
do {
Thread.sleep(1000);
}
while (startedThreads.size() != totalThreads);
try {
info("Acquired in separate thread. ");
assertTrue(lock0.isHeldByCurrentThread());
assertFalse(lock0.hasQueuedThread(Thread.currentThread()));
finishedThreads.add(Thread.currentThread());
if (startedThreads.size() != finishedThreads.size()) {
assertTrue(lock0.hasQueuedThreads());
}
for (Thread t : startedThreads) {
assertTrue(lock0.hasQueuedThread(t) != finishedThreads.contains(t));
}
}
finally {
lock0.unlock();
assertFalse(lock0.isHeldByCurrentThread());
}
return null;
}
}, totalThreads);
fut.get();
assertFalse(lock0.hasQueuedThreads());
for (Thread t : startedThreads)
assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
/**
* @throws Exception If failed.
*/
@Test
public void testHasConditionQueuedThreads() throws Exception {
testHasConditionQueuedThreads(false);
testHasConditionQueuedThreads(true);
}
/**
* @throws Exception If failed.
*/
private void testHasConditionQueuedThreads(final boolean fair) throws Exception {
final IgniteLock lock0 = grid(0).reentrantLock("lock", true, fair, true);
assertEquals(0, lock0.getHoldCount());
assertFalse(lock0.hasQueuedThreads());
final int totalThreads = 5;
final Set<Thread> startedThreads = new GridConcurrentHashSet<>();
final Set<Thread> finishedThreads = new GridConcurrentHashSet<>();
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
assertFalse(lock0.isHeldByCurrentThread());
IgniteCondition cond = lock0.getOrCreateCondition("cond");
lock0.lock();
startedThreads.add(Thread.currentThread());
// Wait until every thread tries to lock.
do {
cond.await();
Thread.sleep(1000);
}
while (startedThreads.size() != totalThreads);
try {
info("Acquired in separate thread. Number of threads waiting on condition: "
+ lock0.getWaitQueueLength(cond));
assertTrue(lock0.isHeldByCurrentThread());
assertFalse(lock0.hasQueuedThread(Thread.currentThread()));
finishedThreads.add(Thread.currentThread());
if (startedThreads.size() != finishedThreads.size()) {
assertTrue(lock0.hasWaiters(cond));
}
for (Thread t : startedThreads) {
if (!finishedThreads.contains(t))
assertTrue(lock0.hasWaiters(cond));
}
assertTrue(lock0.getWaitQueueLength(cond) == (startedThreads.size() - finishedThreads.size()));
}
finally {
cond.signal();
lock0.unlock();
assertFalse(lock0.isHeldByCurrentThread());
}
return null;
}
}, totalThreads);
IgniteCondition cond = lock0.getOrCreateCondition("cond");
lock0.lock();
try {
// Wait until all threads are waiting on condition.
while (lock0.getWaitQueueLength(cond) != totalThreads) {
lock0.unlock();
Thread.sleep(1000);
lock0.lock();
}
// Signal once to get things started.
cond.signal();
}
finally {
lock0.unlock();
}
fut.get();
assertFalse(lock0.hasQueuedThreads());
for (Thread t : startedThreads)
assertFalse(lock0.hasQueuedThread(t));
lock0.close();
}
/**
* Tests that closed lock throws meaningful exception.
*/
@Test (expected = IgniteException.class)
public void testClosedLockThrowsIgniteException() {
final String lockName = "lock";
IgniteLock lock1 = grid(0).reentrantLock(lockName, false, false, true);
IgniteLock lock2 = grid(0).reentrantLock(lockName, false, false, true);
lock1.close();
try {
lock2.lock();
} catch (IgniteException e) {
String msg = String.format("Failed to find reentrant lock with given name: " + lockName);
assertEquals(msg, e.getMessage());
throw e;
}
}
/**
* Tests if lock is evenly acquired among nodes when fair flag is set on.
* Since exact ordering of lock acquisitions cannot be guaranteed because it also depends
* on the OS thread scheduling, certain deviation from uniform distribution is tolerated.
* @throws Exception If failed.
*/
@Test
public void testFairness() throws Exception {
if (gridCount() == 1)
return;
// Total number of ops.
final long opsCount = 10000;
// Allowed deviation from uniform distribution.
final double tolerance = 0.05;
// Shared counter.
final String OPS_COUNTER = "ops_counter";
// Number of threads, one per node.
final int threadCount = gridCount();
final AtomicLong threadCounter = new AtomicLong(0);
Ignite ignite = startGrid(gridCount());
// Initialize reentrant lock.
IgniteLock l = ignite.reentrantLock("lock", true, true, true);
// Initialize OPS_COUNTER.
ignite.getOrCreateCache(OPS_COUNTER).put(OPS_COUNTER, (long)0);
final Map<Integer, Long> counts = new ConcurrentHashMap<>();
IgniteInternalFuture<?> fut = multithreadedAsync(
new Callable<Object>() {
@Override public Object call() throws Exception {
final int localNodeId = (int)threadCounter.getAndIncrement();
final Ignite grid = grid(localNodeId);
IgniteClosure<Ignite, Long> closure = new IgniteClosure<Ignite, Long>() {
@Override public Long apply(Ignite ignite) {
IgniteLock l = ignite.reentrantLock("lock", true, true, true);
long localCount = 0;
IgniteCountDownLatch latch = ignite.countDownLatch("latch", threadCount, false, true);
latch.countDown();
latch.await();
while (true) {
l.lock();
try {
long opsCounter = (long) ignite.getOrCreateCache(OPS_COUNTER).get(OPS_COUNTER);
if (opsCounter == opsCount)
break;
ignite.getOrCreateCache(OPS_COUNTER).put(OPS_COUNTER, ++opsCounter);
localCount++;
if (localCount > 1000) {
assertTrue(localCount < (1 + tolerance) * opsCounter / threadCount);
assertTrue(localCount > (1 - tolerance) * opsCounter / threadCount);
}
if (localCount % 100 == 0) {
info("Node [id=" + ignite.cluster().localNode().id() + "] acquired " +
localCount + " times. " + "Total ops count: " +
opsCounter + "/" + opsCount + "]");
}
}
finally {
l.unlock();
}
}
return localCount;
}
};
long localCount = closure.apply(grid);
counts.put(localNodeId, localCount);
return null;
}
}, threadCount);
fut.get();
long totalSum = 0;
for (int i = 0; i < gridCount(); i++) {
totalSum += counts.get(i);
info("Node " + grid(i).localNode().id() + " acquired the lock " + counts.get(i) + " times. ");
}
assertEquals(totalSum, opsCount);
l.close();
ignite.close();
}
/** {@inheritDoc} */
@Override public void writeExternal(ObjectOutput out) throws IOException {
// No-op.
}
/** {@inheritDoc} */
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// No-op.
}
}
| apache-2.0 |
Sage-Bionetworks/bridge-base | src/main/java/org/sagebionetworks/bridge/worker/ThrowingConsumer.java | 445 | package org.sagebionetworks.bridge.worker;
/**
* Functional interface that consumes a single argument, returns no values, and can throw exceptions. This is generally
* used by the Bridge Worker Platform, and subprojects can just implement this interface.
*/
@FunctionalInterface
public interface ThrowingConsumer<T> {
/** Accepts the value of the given type and performs processing as needed. */
void accept(T t) throws Exception;
}
| apache-2.0 |
waans11/incubator-asterixdb | hyracks-fullstack/hyracks/hyracks-control/hyracks-control-common/src/main/java/org/apache/hyracks/control/common/utils/ThreadDumpHelper.java | 3919 | /*
* 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.hyracks.control.common.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ThreadDumpHelper {
private ThreadDumpHelper() {
}
public static String takeDumpJSON(ThreadMXBean threadMXBean) throws IOException {
ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true);
List<Map<String, Object>> threads = new ArrayList<>();
for (ThreadInfo thread : threadInfos) {
Map<String, Object> threadMap = new HashMap<>();
threadMap.put("name", thread.getThreadName());
threadMap.put("id", thread.getThreadId());
threadMap.put("state", thread.getThreadState().name());
List<String> stacktrace = new ArrayList<>();
for (StackTraceElement element : thread.getStackTrace()) {
stacktrace.add(element.toString());
}
threadMap.put("stack", stacktrace);
if (thread.getLockName() != null) {
threadMap.put("lock_name", thread.getLockName());
}
if (thread.getLockOwnerId() != -1) {
threadMap.put("lock_owner_id", thread.getLockOwnerId());
}
if (thread.getBlockedTime() > 0) {
threadMap.put("blocked_time", thread.getBlockedTime());
}
if (thread.getBlockedCount() > 0) {
threadMap.put("blocked_count", thread.getBlockedCount());
}
if (thread.getLockedMonitors().length > 0) {
threadMap.put("locked_monitors", thread.getLockedMonitors());
}
if (thread.getLockedSynchronizers().length > 0) {
threadMap.put("locked_synchronizers", thread.getLockedSynchronizers());
}
threads.add(threadMap);
}
ObjectMapper om = new ObjectMapper();
ObjectNode json = om.createObjectNode();
json.put("date", new Date().toString());
json.putPOJO("threads", threads);
long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
long[] monitorDeadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
if (deadlockedThreads != null && deadlockedThreads.length > 0) {
json.putPOJO("deadlocked_thread_ids", deadlockedThreads);
}
if (monitorDeadlockedThreads != null && monitorDeadlockedThreads.length > 0) {
json.putPOJO("monitor_deadlocked_thread_ids", monitorDeadlockedThreads);
}
om.enable(SerializationFeature.INDENT_OUTPUT);
return om.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}
}
| apache-2.0 |
apache/olingo-odata4 | lib/commons-core/src/test/java/org/apache/olingo/commons/core/edm/primitivetype/EdmDateTest.java | 4576 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.commons.core.edm.primitivetype;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.TimeZone;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.junit.Test;
public class EdmDateTest extends PrimitiveTypeBaseTest {
private final EdmPrimitiveType instance = EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Date);
@Test
public void toUriLiteral() throws Exception {
assertEquals("2009-12-26", instance.toUriLiteral("2009-12-26"));
assertEquals("-2009-12-26", instance.toUriLiteral("-2009-12-26"));
}
@Test
public void fromUriLiteral() throws Exception {
assertEquals("2009-12-26", instance.fromUriLiteral("2009-12-26"));
assertEquals("-2009-12-26", instance.fromUriLiteral("-2009-12-26"));
}
@Test
public void valueToString() throws Exception {
Calendar dateTime = Calendar.getInstance();
dateTime.clear();
setTimeZone(dateTime, "GMT-11:30");
dateTime.set(2012, 1, 29, 13, 0, 0);
assertEquals("2012-02-29", instance.valueToString(dateTime, null, null, null, null, null));
Long millis = 1330558323007L;
millis -= TimeZone.getDefault().getOffset(millis);
assertEquals("2012-02-29", instance.valueToString(millis, null, null, null, null, null));
assertEquals("1969-12-31", instance.valueToString(new java.util.Date(-43200000), null, null, null, null, null));
assertEquals("1969-12-31",
instance.valueToString(java.sql.Date.valueOf("1969-12-31"), null, null, null, null, null));
assertEquals("1969-12-31",
instance.valueToString(LocalDate.parse("1969-12-31"), null, null, null, null, null));
// TODO support for years beyond 9999
// dateTime.set(Calendar.YEAR, 12344);
// assertEquals("12344-02-29", instance.valueToString(dateTime, null, null, null, null, null));
expectTypeErrorInValueToString(instance, 0);
}
@Test
public void valueOfString() throws Exception {
Calendar dateTime = Calendar.getInstance();
dateTime.clear();
dateTime.set(2012, 1, 29);
assertEqualCalendar(dateTime,
instance.valueOfString("2012-02-29", null, null, null, null, null, Calendar.class));
assertEquals(Long.valueOf(dateTime.getTimeInMillis()),
instance.valueOfString("2012-02-29", null, null, null, null, null, Long.class));
assertEquals(dateTime.getTime(),
instance.valueOfString("2012-02-29", null, null, null, null, null, java.util.Date.class));
assertEquals(java.sql.Date.valueOf("2012-02-29"),
instance.valueOfString("2012-02-29", null, null, null, null, null, java.sql.Date.class));
assertEquals(LocalDate.parse("2012-02-29"),
instance.valueOfString("2012-02-29", null, null, null, null, null, LocalDate.class));
// TODO support for years beyond 9999
// dateTime.set(Calendar.YEAR, 12344);
// Calendar result = instance.valueOfString("12344-02-29", null, null, null,
// null, null, Calendar.class);
// this.assertEqualCalendar(dateTime, result);
// TODO: Clarify whether negative years are really needed.
// dateTime.set(-1, 1, 28);
// assertEquals(dateTime, instance.valueOfString("-0001-02-28", null,
// Calendar.class));
expectContentErrorInValueOfString(instance, "2012-02-29T23:32:02");
expectContentErrorInValueOfString(instance, "2012-02-30");
expectContentErrorInValueOfString(instance, "20120229");
expectContentErrorInValueOfString(instance, "2012-02-1");
expectContentErrorInValueOfString(instance, "2012-2-12");
expectContentErrorInValueOfString(instance, "123-02-03");
expectTypeErrorInValueOfString(instance, "2012-02-29");
}
}
| apache-2.0 |
hoko/hoko-android | hoko/src/main/java/com/hokolinks/deeplinking/annotations/DeeplinkDefaultRoute.java | 563 | package com.hokolinks.deeplinking.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use this annotation on one activity you wish to be default deeplinkable activity.
* <pre>{@code @DeeplinkDefaultRoute
* public class SplashActivity extends Activity { ... }
* }</pre>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DeeplinkDefaultRoute {
} | apache-2.0 |
betfair/cougar | cougar-framework/cougar-api/src/main/java/com/betfair/cougar/api/security/IdentityResolver.java | 1763 | /*
* 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 com.betfair.cougar.api.security;
import com.betfair.cougar.api.DehydratedExecutionContext;
import java.util.List;
/**
* The IdentityResolver resolves a set of credentials into an IdentityChain.
*
* @see IdentityChain
*
*/
public interface IdentityResolver {
/**
* Given a set of credentials, resolves those credentials into
* an IdentityChain. The identity chain to add the result(s) to is passed in.
* @param chain the identity chain to add resolved identities to
* @param ctx the execution context resolved so far including identity tokens resolved by the {@link IdentityTokenResolver} (IdentityChain on this context will be null).
* @throws InvalidCredentialsException
*/
public void resolve(IdentityChain chain, DehydratedExecutionContext ctx) throws InvalidCredentialsException;
/**
* Given an identity chain, resolve back into a set of writable tokens
* @param chain an identity chain
* @return a list of tokens that may be written, which may be null.
* @throws InvalidCredentialsException
*/
public List<IdentityToken> tokenise(IdentityChain chain);
}
| apache-2.0 |
iorala/grobid | grobid-core/src/test/java/org/grobid/core/tokenization/TaggingTokenSynchronizerTest.java | 2299 | package org.grobid.core.tokenization;
import org.grobid.core.GrobidModels;
import org.grobid.core.layout.LayoutToken;
import org.grobid.core.utilities.LayoutTokensUtil;
import org.grobid.core.utilities.Pair;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
/**
* Created by zholudev on 07/04/16.
* Testing synchronization
*/
public class TaggingTokenSynchronizerTest {
public static final String P = "<paragraph>";
public static final String F = "<figure>";
@Test
public void testBasic() {
TaggingTokenSynchronizer synchronizer = new TaggingTokenSynchronizer(GrobidModels.FULLTEXT,
generateResult(p("This", P), p("Figure", F)), toks("This", " ", "Figure")
);
int cnt = 0;
boolean spacesPresent = false;
for (LabeledTokensContainer el : synchronizer) {
String text = LayoutTokensUtil.toText(el.getLayoutTokens());
assertFalse(text.startsWith(" "));
if (text.contains(" ")) {
spacesPresent = true;
}
cnt++;
}
assertThat(cnt, is(2));
assertThat(spacesPresent, is(true));
}
@Test(expected = IllegalStateException.class)
public void testFailure() {
TaggingTokenSynchronizer synchronizer = new TaggingTokenSynchronizer(GrobidModels.FULLTEXT,
generateResult(p("This", P), p("Figure", F)), toks("This", " ", "Fig")
);
for (LabeledTokensContainer el : synchronizer) {
LayoutTokensUtil.toText(el.getLayoutTokens());
}
}
private static String generateResult(Pair<String, String>... tokens) {
StringBuilder res = new StringBuilder();
for (Pair<String, String> p : tokens) {
res.append(p.a).append("\t").append(p.b).append("\n");
}
return res.toString();
}
private static List<LayoutToken> toks(String... toks) {
List<LayoutToken> res = new ArrayList<>();
for (String t : toks) {
res.add(new LayoutToken(t));
}
return res;
}
private static Pair<String, String> p(String tok, String label) {
return new Pair<>(tok, label);
}
}
| apache-2.0 |
lemonJun/TakinMQ | takinmq-jafka/src/main/java/io/jafka/message/ByteBufferBackedInputStream.java | 1623 | /**
* 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 io.jafka.message;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
/**
* Convert ByteBuffer to InputStream
* @author adyliu (imxylz@gmail.com)
* @since 1.0
*/
class ByteBufferBackedInputStream extends InputStream {
private final ByteBuffer buffer;
public ByteBufferBackedInputStream(ByteBuffer buffer) {
this.buffer = buffer;
}
@Override
public int read() throws IOException {
return buffer.hasRemaining() ? (buffer.get() & 0xFF) : -1;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (buffer.hasRemaining()) {
int realLen = Math.min(len, buffer.remaining());
buffer.get(b, off, realLen);
return realLen;
}
return -1;
}
}
| apache-2.0 |
buehner/shogun2 | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/converter/PluginIdResolver.java | 649 | package de.terrestris.shoguncore.converter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import de.terrestris.shoguncore.dao.PluginDao;
import de.terrestris.shoguncore.model.Plugin;
import de.terrestris.shoguncore.service.PluginService;
/**
* @author Nils Buehner
*/
public class PluginIdResolver<E extends Plugin, D extends PluginDao<E>, S extends PluginService<E, D>> extends
PersistentObjectIdResolver<E, D, S> {
@Override
@Autowired
@Qualifier("pluginService")
public void setService(S service) {
this.service = service;
}
}
| apache-2.0 |
trivium-io/trivium-core | src/io/trivium/dep/com/google/common/util/concurrent/Striped.java | 19094 | /*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trivium.dep.com.google.common.util.concurrent;
import io.trivium.dep.com.google.common.annotations.Beta;
import io.trivium.dep.com.google.common.annotations.VisibleForTesting;
import io.trivium.dep.com.google.common.base.MoreObjects;
import io.trivium.dep.com.google.common.base.Preconditions;
import io.trivium.dep.com.google.common.base.Supplier;
import io.trivium.dep.com.google.common.collect.ImmutableList;
import io.trivium.dep.com.google.common.collect.Iterables;
import io.trivium.dep.com.google.common.collect.MapMaker;
import io.trivium.dep.com.google.common.math.IntMath;
import io.trivium.dep.com.google.common.primitives.Ints;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* A striped {@code Lock/Semaphore/ReadWriteLock}. This offers the underlying lock striping
* similar to that of {@code ConcurrentHashMap} in a reusable form, and extends it for
* semaphores and read-write locks. Conceptually, lock striping is the technique of dividing a lock
* into many <i>stripes</i>, increasing the granularity of a single lock and allowing independent
* operations to lock different stripes and proceed concurrently, instead of creating contention
* for a single lock.
*
* <p>The guarantee provided by this class is that equal keys lead to the same lock (or semaphore),
* i.e. {@code if (key1.equals(key2))} then {@code striped.get(key1) == striped.get(key2)}
* (assuming {@link Object#hashCode()} is correctly implemented for the keys). Note
* that if {@code key1} is <strong>not</strong> equal to {@code key2}, it is <strong>not</strong>
* guaranteed that {@code striped.get(key1) != striped.get(key2)}; the elements might nevertheless
* be mapped to the same lock. The lower the number of stripes, the higher the probability of this
* happening.
*
* <p>There are three flavors of this class: {@code Striped<Lock>}, {@code Striped<Semaphore>},
* and {@code Striped<ReadWriteLock>}. For each type, two implementations are offered:
* {@linkplain #lock(int) strong} and {@linkplain #lazyWeakLock(int) weak}
* {@code Striped<Lock>}, {@linkplain #semaphore(int, int) strong} and {@linkplain
* #lazyWeakSemaphore(int, int) weak} {@code Striped<Semaphore>}, and {@linkplain
* #readWriteLock(int) strong} and {@linkplain #lazyWeakReadWriteLock(int) weak}
* {@code Striped<ReadWriteLock>}. <i>Strong</i> means that all stripes (locks/semaphores) are
* initialized eagerly, and are not reclaimed unless {@code Striped} itself is reclaimable.
* <i>Weak</i> means that locks/semaphores are created lazily, and they are allowed to be reclaimed
* if nobody is holding on to them. This is useful, for example, if one wants to create a {@code
* Striped<Lock>} of many locks, but worries that in most cases only a small portion of these
* would be in use.
*
* <p>Prior to this class, one might be tempted to use {@code Map<K, Lock>}, where {@code K}
* represents the task. This maximizes concurrency by having each unique key mapped to a unique
* lock, but also maximizes memory footprint. On the other extreme, one could use a single lock
* for all tasks, which minimizes memory footprint but also minimizes concurrency. Instead of
* choosing either of these extremes, {@code Striped} allows the user to trade between required
* concurrency and memory footprint. For example, if a set of tasks are CPU-bound, one could easily
* create a very compact {@code Striped<Lock>} of {@code availableProcessors() * 4} stripes,
* instead of possibly thousands of locks which could be created in a {@code Map<K, Lock>}
* structure.
*
* @author Dimitris Andreou
* @since 13.0
*/
@Beta
public abstract class Striped<L> {
/**
* If there are at least this many stripes, we assume the memory usage of a ConcurrentMap will be
* smaller than a large array. (This assumes that in the lazy case, most stripes are unused. As
* always, if many stripes are in use, a non-lazy striped makes more sense.)
*/
private static final int LARGE_LAZY_CUTOFF = 1024;
private Striped() {}
/**
* Returns the stripe that corresponds to the passed key. It is always guaranteed that if
* {@code key1.equals(key2)}, then {@code get(key1) == get(key2)}.
*
* @param key an arbitrary, non-null key
* @return the stripe that the passed key corresponds to
*/
public abstract L get(Object key);
/**
* Returns the stripe at the specified index. Valid indexes are 0, inclusively, to
* {@code size()}, exclusively.
*
* @param index the index of the stripe to return; must be in {@code [0...size())}
* @return the stripe at the specified index
*/
public abstract L getAt(int index);
/**
* Returns the index to which the given key is mapped, so that getAt(indexFor(key)) == get(key).
*/
abstract int indexFor(Object key);
/**
* Returns the total number of stripes in this instance.
*/
public abstract int size();
/**
* Returns the stripes that correspond to the passed objects, in ascending (as per
* {@link #getAt(int)}) order. Thus, threads that use the stripes in the order returned
* by this method are guaranteed to not deadlock each other.
*
* <p>It should be noted that using a {@code Striped<L>} with relatively few stripes, and
* {@code bulkGet(keys)} with a relative large number of keys can cause an excessive number
* of shared stripes (much like the birthday paradox, where much fewer than anticipated birthdays
* are needed for a pair of them to match). Please consider carefully the implications of the
* number of stripes, the intended concurrency level, and the typical number of keys used in a
* {@code bulkGet(keys)} operation. See <a href="http://www.mathpages.com/home/kmath199.htm">Balls
* in Bins model</a> for mathematical formulas that can be used to estimate the probability of
* collisions.
*
* @param keys arbitrary non-null keys
* @return the stripes corresponding to the objects (one per each object, derived by delegating
* to {@link #get(Object)}; may contain duplicates), in an increasing index order.
*/
public Iterable<L> bulkGet(Iterable<?> keys) {
// Initially using the array to store the keys, then reusing it to store the respective L's
final Object[] array = Iterables.toArray(keys, Object.class);
if (array.length == 0) {
return ImmutableList.of();
}
int[] stripes = new int[array.length];
for (int i = 0; i < array.length; i++) {
stripes[i] = indexFor(array[i]);
}
Arrays.sort(stripes);
// optimize for runs of identical stripes
int previousStripe = stripes[0];
array[0] = getAt(previousStripe);
for (int i = 1; i < array.length; i++) {
int currentStripe = stripes[i];
if (currentStripe == previousStripe) {
array[i] = array[i - 1];
} else {
array[i] = getAt(currentStripe);
previousStripe = currentStripe;
}
}
/*
* Note that the returned Iterable holds references to the returned stripes, to avoid
* error-prone code like:
*
* Striped<Lock> stripedLock = Striped.lazyWeakXXX(...)'
* Iterable<Lock> locks = stripedLock.bulkGet(keys);
* for (Lock lock : locks) {
* lock.lock();
* }
* operation();
* for (Lock lock : locks) {
* lock.unlock();
* }
*
* If we only held the int[] stripes, translating it on the fly to L's, the original locks
* might be garbage collected after locking them, ending up in a huge mess.
*/
@SuppressWarnings("unchecked") // we carefully replaced all keys with their respective L's
List<L> asList = (List<L>) Arrays.asList(array);
return Collections.unmodifiableList(asList);
}
// Static factories
/**
* Creates a {@code Striped<Lock>} with eagerly initialized, strongly referenced locks.
* Every lock is reentrant.
*
* @param stripes the minimum number of stripes (locks) required
* @return a new {@code Striped<Lock>}
*/
public static Striped<Lock> lock(int stripes) {
return new CompactStriped<Lock>(stripes, new Supplier<Lock>() {
@Override public Lock get() {
return new PaddedLock();
}
});
}
/**
* Creates a {@code Striped<Lock>} with lazily initialized, weakly referenced locks.
* Every lock is reentrant.
*
* @param stripes the minimum number of stripes (locks) required
* @return a new {@code Striped<Lock>}
*/
public static Striped<Lock> lazyWeakLock(int stripes) {
return lazy(stripes, new Supplier<Lock>() {
@Override public Lock get() {
return new ReentrantLock(false);
}
});
}
private static <L> Striped<L> lazy(int stripes, Supplier<L> supplier) {
return stripes < LARGE_LAZY_CUTOFF
? new SmallLazyStriped<L>(stripes, supplier)
: new LargeLazyStriped<L>(stripes, supplier);
}
/**
* Creates a {@code Striped<Semaphore>} with eagerly initialized, strongly referenced semaphores,
* with the specified number of permits.
*
* @param stripes the minimum number of stripes (semaphores) required
* @param permits the number of permits in each semaphore
* @return a new {@code Striped<Semaphore>}
*/
public static Striped<Semaphore> semaphore(int stripes, final int permits) {
return new CompactStriped<Semaphore>(stripes, new Supplier<Semaphore>() {
@Override public Semaphore get() {
return new PaddedSemaphore(permits);
}
});
}
/**
* Creates a {@code Striped<Semaphore>} with lazily initialized, weakly referenced semaphores,
* with the specified number of permits.
*
* @param stripes the minimum number of stripes (semaphores) required
* @param permits the number of permits in each semaphore
* @return a new {@code Striped<Semaphore>}
*/
public static Striped<Semaphore> lazyWeakSemaphore(int stripes, final int permits) {
return lazy(stripes, new Supplier<Semaphore>() {
@Override public Semaphore get() {
return new Semaphore(permits, false);
}
});
}
/**
* Creates a {@code Striped<ReadWriteLock>} with eagerly initialized, strongly referenced
* read-write locks. Every lock is reentrant.
*
* @param stripes the minimum number of stripes (locks) required
* @return a new {@code Striped<ReadWriteLock>}
*/
public static Striped<ReadWriteLock> readWriteLock(int stripes) {
return new CompactStriped<ReadWriteLock>(stripes, READ_WRITE_LOCK_SUPPLIER);
}
/**
* Creates a {@code Striped<ReadWriteLock>} with lazily initialized, weakly referenced
* read-write locks. Every lock is reentrant.
*
* @param stripes the minimum number of stripes (locks) required
* @return a new {@code Striped<ReadWriteLock>}
*/
public static Striped<ReadWriteLock> lazyWeakReadWriteLock(int stripes) {
return lazy(stripes, READ_WRITE_LOCK_SUPPLIER);
}
// ReentrantReadWriteLock is large enough to make padding probably unnecessary
private static final Supplier<ReadWriteLock> READ_WRITE_LOCK_SUPPLIER =
new Supplier<ReadWriteLock>() {
@Override public ReadWriteLock get() {
return new ReentrantReadWriteLock();
}
};
private abstract static class PowerOfTwoStriped<L> extends Striped<L> {
/** Capacity (power of two) minus one, for fast mod evaluation */
final int mask;
PowerOfTwoStriped(int stripes) {
Preconditions.checkArgument(stripes > 0, "Stripes must be positive");
this.mask = stripes > Ints.MAX_POWER_OF_TWO ? ALL_SET : ceilToPowerOfTwo(stripes) - 1;
}
@Override final int indexFor(Object key) {
int hash = smear(key.hashCode());
return hash & mask;
}
@Override public final L get(Object key) {
return getAt(indexFor(key));
}
}
/**
* Implementation of Striped where 2^k stripes are represented as an array of the same length,
* eagerly initialized.
*/
private static class CompactStriped<L> extends PowerOfTwoStriped<L> {
/** Size is a power of two. */
private final Object[] array;
private CompactStriped(int stripes, Supplier<L> supplier) {
super(stripes);
Preconditions.checkArgument(stripes <= Ints.MAX_POWER_OF_TWO, "Stripes must be <= 2^30)");
this.array = new Object[mask + 1];
for (int i = 0; i < array.length; i++) {
array[i] = supplier.get();
}
}
@SuppressWarnings("unchecked") // we only put L's in the array
@Override public L getAt(int index) {
return (L) array[index];
}
@Override public int size() {
return array.length;
}
}
/**
* Implementation of Striped where up to 2^k stripes can be represented, using an
* AtomicReferenceArray of size 2^k. To map a user key into a stripe, we take a k-bit slice of the
* user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced.
*/
@VisibleForTesting static class SmallLazyStriped<L> extends PowerOfTwoStriped<L> {
final AtomicReferenceArray<ArrayReference<? extends L>> locks;
final Supplier<L> supplier;
final int size;
final ReferenceQueue<L> queue = new ReferenceQueue<L>();
SmallLazyStriped(int stripes, Supplier<L> supplier) {
super(stripes);
this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
this.locks = new AtomicReferenceArray<ArrayReference<? extends L>>(size);
this.supplier = supplier;
}
@Override public L getAt(int index) {
if (size != Integer.MAX_VALUE) {
Preconditions.checkElementIndex(index, size());
} // else no check necessary, all index values are valid
ArrayReference<? extends L> existingRef = locks.get(index);
L existing = existingRef == null ? null : existingRef.get();
if (existing != null) {
return existing;
}
L created = supplier.get();
ArrayReference<L> newRef = new ArrayReference<L>(created, index, queue);
while (!locks.compareAndSet(index, existingRef, newRef)) {
// we raced, we need to re-read and try again
existingRef = locks.get(index);
existing = existingRef == null ? null : existingRef.get();
if (existing != null) {
return existing;
}
}
drainQueue();
return created;
}
// N.B. Draining the queue is only necessary to ensure that we don't accumulate empty references
// in the array. We could skip this if we decide we don't care about holding on to Reference
// objects indefinitely.
private void drainQueue() {
Reference<? extends L> ref;
while ((ref = queue.poll()) != null) {
// We only ever register ArrayReferences with the queue so this is always safe.
ArrayReference<? extends L> arrayRef = (ArrayReference<? extends L>) ref;
// Try to clear out the array slot, n.b. if we fail that is fine, in either case the
// arrayRef will be out of the array after this step.
locks.compareAndSet(arrayRef.index, arrayRef, null);
}
}
@Override public int size() {
return size;
}
private static final class ArrayReference<L> extends WeakReference<L> {
final int index;
ArrayReference(L referent, int index, ReferenceQueue<L> queue) {
super(referent, queue);
this.index = index;
}
}
}
/**
* Implementation of Striped where up to 2^k stripes can be represented, using a ConcurrentMap
* where the key domain is [0..2^k). To map a user key into a stripe, we take a k-bit slice of the
* user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced.
*/
@VisibleForTesting static class LargeLazyStriped<L> extends PowerOfTwoStriped<L> {
final ConcurrentMap<Integer, L> locks;
final Supplier<L> supplier;
final int size;
LargeLazyStriped(int stripes, Supplier<L> supplier) {
super(stripes);
this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
this.supplier = supplier;
this.locks = new MapMaker().weakValues().makeMap();
}
@Override public L getAt(int index) {
if (size != Integer.MAX_VALUE) {
Preconditions.checkElementIndex(index, size());
} // else no check necessary, all index values are valid
L existing = locks.get(index);
if (existing != null) {
return existing;
}
L created = supplier.get();
existing = locks.putIfAbsent(index, created);
return MoreObjects.firstNonNull(existing, created);
}
@Override public int size() {
return size;
}
}
/**
* A bit mask were all bits are set.
*/
private static final int ALL_SET = ~0;
private static int ceilToPowerOfTwo(int x) {
return 1 << IntMath.log2(x, RoundingMode.CEILING);
}
/*
* This method was written by Doug Lea with assistance from members of JCP
* JSR-166 Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*
* As of 2010/06/11, this method is identical to the (package private) hash
* method in OpenJDK 7's java.util.HashMap class.
*/
// Copied from java/com/google/common/collect/Hashing.java
private static int smear(int hashCode) {
hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4);
}
private static class PaddedLock extends ReentrantLock {
/*
* Padding from 40 into 64 bytes, same size as cache line. Might be beneficial to add
* a fourth long here, to minimize chance of interference between consecutive locks,
* but I couldn't observe any benefit from that.
*/
@SuppressWarnings("unused")
long q1, q2, q3;
PaddedLock() {
super(false);
}
}
private static class PaddedSemaphore extends Semaphore {
// See PaddedReentrantLock comment
@SuppressWarnings("unused")
long q1, q2, q3;
PaddedSemaphore(int permits) {
super(permits, false);
}
}
}
| apache-2.0 |
dannil/scb-api | src/main/java/com/github/dannil/scbjavaclient/client/financialmarkets/shareholders/package-info.java | 172 | /**
* <p>Package which contains all clients for financial markets shareholders data.</p>
*/
package com.github.dannil.scbjavaclient.client.financialmarkets.shareholders;
| apache-2.0 |
shardingjdbc/sharding-jdbc | shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-sql92/src/main/java/org/apache/shardingsphere/sql/parser/sql92/lexer/SQL92Lexer.java | 1235 | /*
* 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.shardingsphere.sql.parser.sql92.lexer;
import org.antlr.v4.runtime.CharStream;
import org.apache.shardingsphere.sql.parser.api.lexer.SQLLexer;
import org.apache.shardingsphere.sql.parser.autogen.SQL92StatementLexer;
/**
* SQL lexer for SQL92.
*/
public final class SQL92Lexer extends SQL92StatementLexer implements SQLLexer {
public SQL92Lexer(final CharStream input) {
super(input);
}
}
| apache-2.0 |
apache/jena | jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/Base64.java | 11101 | /*
* 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.jena.ext.xerces.impl.dv.util;
/**
* This class provides encode/decode for RFC 2045 Base64 as
* defined by RFC 2045, N. Freed and N. Borenstein.
* RFC 2045: Multipurpose Internet Mail Extensions (MIME)
* Part One: Format of Internet Message Bodies. Reference
* 1996 Available at: http://www.ietf.org/rfc/rfc2045.txt
* This class is used by XML Schema binary format validation
*
* This implementation does not encode/decode streaming
* data. You need the data that you will encode/decode
* already on a byte arrray.
*
* {@literal @xerces.internal}
*
* @author Jeffrey Rodriguez
* @author Sandy Gao
* @version $Id: Base64.java 446747 2006-09-15 21:46:20Z mrglavas $
*/
public final class Base64 {
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int SIXBIT = 6;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static private final boolean fDebug = false;
static final private byte [] base64Alphabet = new byte[BASELENGTH];
static final private char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i-'A');
}
for (int i = 'z'; i>= 'a'; i--) {
base64Alphabet[i] = (byte) ( i-'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i-'0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i<=25; i++)
lookUpBase64Alphabet[i] = (char)('A'+i);
for (int i = 26, j = 0; i<=51; i++, j++)
lookUpBase64Alphabet[i] = (char)('a'+ j);
for (int i = 52, j = 0; i<=61; i++, j++)
lookUpBase64Alphabet[i] = (char)('0' + j);
lookUpBase64Alphabet[62] = '+';
lookUpBase64Alphabet[63] = '/';
}
protected static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
protected static boolean isPad(char octect) {
return (octect == PAD);
}
protected static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
protected static boolean isBase64(char octect) {
return (isWhiteSpace(octect) || isPad(octect) || isData(octect));
}
/**
* Encodes hex octects into Base64
*
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null)
return null;
int lengthDataBits = binaryData.length*EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets+1 : numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet*4];
byte k=0, l=0, b1=0,b2=0,b3=0;
int encodedIndex = 0;
int dataIndex = 0;
if (fDebug) {
System.out.println("number of triplets = " + numberTriplets );
}
for (int i=0; i<numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
if (fDebug) {
System.out.println( "b1= " + b1 +", b2= " + b2 + ", b3= " + b3 );
}
l = (byte)(b2 & 0x0f);
k = (byte)(b1 & 0x03);
byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc);
if (fDebug) {
System.out.println( "val2 = " + val2 );
System.out.println( "k4 = " + (k<<4));
System.out.println( "vak = " + (val2 | (k<<4)));
}
encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ];
encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) ( b1 &0x03 );
if (fDebug) {
System.out.println("b1=" + b1);
System.out.println("b1<<2 = " + (b1>>2) );
}
byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
encodedData[encodedIndex++] = lookUpBase64Alphabet[ k<<4 ];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex +1 ];
l = ( byte ) ( b2 &0x0f );
k = ( byte ) ( b1 &0x03 );
byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null)
return null;
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len%FOURBYTE != 0) {
return null;//should be divisible by four
}
int numberQuadruple = (len/FOURBYTE );
if (numberQuadruple == 0)
return new byte[0];
byte decodedData[] = null;
byte b1=0,b2=0,b3=0,b4=0;
char d1=0,d2=0,d3=0,d4=0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[ (numberQuadruple)*3];
for (; i<numberQuadruple-1; i++) {
if (!isData( (d1 = base64Data[dataIndex++]) )||
!isData( (d2 = base64Data[dataIndex++]) )||
!isData( (d3 = base64Data[dataIndex++]) )||
!isData( (d4 = base64Data[dataIndex++]) ))
return null;//if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ;
decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
}
if (!isData( (d1 = base64Data[dataIndex++]) ) ||
!isData( (d2 = base64Data[dataIndex++]) )) {
return null;//if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData( (d3 ) ) ||
!isData( (d4 ) )) {//Check if they are PAD characters
if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad]
if ((b2 & 0xf) != 0)//last 4 bits should be zero
return null;
byte[] tmp = new byte[ i*3 + 1 ];
System.arraycopy( decodedData, 0, tmp, 0, i*3 );
tmp[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ;
return tmp;
} else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad]
b3 = base64Alphabet[ d3 ];
if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
return null;
byte[] tmp = new byte[ i*3 + 2 ];
System.arraycopy( decodedData, 0, tmp, 0, i*3 );
tmp[encodedIndex++] = (byte)( b1 <<2 | b2>>4 );
tmp[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
return tmp;
} else {
return null;//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
}
} else { //No PAD e.g 3cQl
b3 = base64Alphabet[ d3 ];
b4 = base64Alphabet[ d4 ];
decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ;
decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data the byte array of base64 data (with WS)
* @return the new length
*/
protected static int removeWhiteSpace(char[] data) {
if (data == null)
return 0;
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i]))
data[newSize++] = data[i];
}
return newSize;
}
}
| apache-2.0 |
apache/james-postage | src/main/java/org/apache/james/postage/mail/MailAnalyzeStrategy.java | 3809 | /****************************************************************
* 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.james.postage.mail;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.james.postage.result.MailProcessingRecord;
import org.apache.james.postage.result.PostageRunnerResult;
/**
* handles the process of retrieving, analyzing, matching and finally (optionally) dismissing one
* received message.
*/
public abstract class MailAnalyzeStrategy {
protected static Log log = LogFactory.getLog(MailAnalyzeStrategy.class);
private String queue = null;
private PostageRunnerResult results = null;
public MailAnalyzeStrategy(String receivingQueueName, PostageRunnerResult results) {
this.queue = receivingQueueName;
this.results = results;
}
public void handle() throws Exception {
MailProcessingRecord mailProcessingRecord = prepareRecord();
MimeMessage message = loadMessage();
// do we _really_ have to handle this?
if (!MailMatchingUtils.isMatchCandidate(message)) return;
String id = MailMatchingUtils.getMailIdHeader(message);
try {
mailProcessingRecord.setByteReceivedTotal(message.getSize());
mailProcessingRecord.setMailId(id);
mailProcessingRecord.setSubject(message.getSubject());
mailProcessingRecord.setTimeFetchEnd(System.currentTimeMillis());
} catch (MessagingException e) {
log.info(queue + ": failed to process mail. remains on server");
return;
} finally {
MailProcessingRecord matchedAndMergedRecord = results.matchMailRecord(mailProcessingRecord);
if (matchedAndMergedRecord != null) {
MailMatchingUtils.validateMail(message, matchedAndMergedRecord);
results.recordValidatedMatch(matchedAndMergedRecord);
}
}
dismissMessage();
}
/**
* mandatory override to make the message available
*/
protected MimeMessage loadMessage() throws Exception {
return null;
}
/**
* optional override to delete the message.
*/
protected void dismissMessage() throws Exception {
; // empty body
}
private MailProcessingRecord prepareRecord() {
MailProcessingRecord mailProcessingRecord = new MailProcessingRecord();
mailProcessingRecord.setReceivingQueue(queue);
mailProcessingRecord.setTimeFetchStart(System.currentTimeMillis());
return mailProcessingRecord;
}
}
| apache-2.0 |
waitsavery/Selenium-Toyota-POC | src/main/java/com/orasi/utils/database/databaseImpl/OracleDatabase.java | 1007 | package com.orasi.utils.database.databaseImpl;
import com.orasi.utils.Constants;
import com.orasi.utils.database.Database;
public class OracleDatabase extends Database {
public OracleDatabase(String tnsName) {
setDbDriver("oracle.jdbc.driver.OracleDriver");
setDbConnectionString("jdbc:oracle:thin:@" + tnsName.toUpperCase());
}
public OracleDatabase(String host, String port, String sid) {
setDbDriver("oracle.jdbc.driver.OracleDriver");
setDbConnectionString("jdbc:oracle:thin:@" + host + ":" + port + ":"
+ sid);
}
@Override
protected void setDbDriver(String driver) {
super.strDriver = driver;
}
@Override
protected void setDbConnectionString(String connection) {
String tns = getClass()
.getResource(Constants.TNSNAMES_PATH + "tnsnames.ora")
.getPath().toString();
tns = tns.substring(0, tns.lastIndexOf("/"));
System.setProperty("oracle.net.tns_admin", tns);
super.strConnectionString = connection;
}
}
| apache-2.0 |
jexp/idea2 | platform/lang-impl/src/com/intellij/refactoring/openapi/impl/RefactoringFactoryImpl.java | 1424 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.openapi.impl;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.RefactoringFactory;
import com.intellij.refactoring.RenameRefactoring;
import com.intellij.refactoring.SafeDeleteRefactoring;
/**
* @author yole
*/
public class RefactoringFactoryImpl extends RefactoringFactory {
private final Project myProject;
public RefactoringFactoryImpl(final Project project) {
myProject = project;
}
public RenameRefactoring createRename(final PsiElement element, final String newName) {
return new RenameRefactoringImpl(myProject, element, newName, true, true);
}
public SafeDeleteRefactoring createSafeDelete(final PsiElement[] elements) {
return new SafeDeleteRefactoringImpl(myProject, elements);
}
}
| apache-2.0 |
leadwire-apm/leadwire-javaagent | leadwire-monitoring/src/kieker/monitoring/writer/filesystem/BinaryFileWriterPool.java | 4288 | /***************************************************************************
* Copyright 2015 Kieker Project (http://kieker-monitoring.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package kieker.monitoring.writer.filesystem;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import kieker.common.logging.Log;
import kieker.common.util.filesystem.FSUtil;
/**
* @author Christian Wulf (chw)
*
* @since 1.13
*/
class BinaryFileWriterPool extends WriterPool {
private final int maxEntriesPerFile;
private int numEntriesInCurrentFile;
// private int currentAmountOfFiles;
private final long maxBytesPerFile;
private final boolean shouldCompress;
private final String fileExtensionWithDot;
private final int maxAmountOfFiles;
private PooledFileChannel currentChannel;
private int currentFileNumber;
public BinaryFileWriterPool(final Log writerLog, final Path folder, final int maxEntriesPerFile, final boolean shouldCompress, final int maxAmountOfFiles,
final int maxMegaBytesPerFile) {
super(writerLog, folder);
this.maxEntriesPerFile = maxEntriesPerFile;
this.numEntriesInCurrentFile = maxEntriesPerFile; // triggers file creation
this.shouldCompress = shouldCompress;
this.maxAmountOfFiles = maxAmountOfFiles;
this.maxBytesPerFile = maxMegaBytesPerFile * 1024L * 1024L; // conversion from MB to Bytes
this.currentChannel = new PooledFileChannel(Channels.newChannel(new ByteArrayOutputStream())); // NullObject design pattern
this.fileExtensionWithDot = (shouldCompress) ? FSUtil.ZIP_FILE_EXTENSION : FSUtil.BINARY_FILE_EXTENSION; // NOCS
}
public PooledFileChannel getFileWriter(final ByteBuffer buffer) {
this.numEntriesInCurrentFile++;
// (buffer overflow aware comparison) means: numEntriesInCurrentFile > maxEntriesPerFile
if ((this.numEntriesInCurrentFile - this.maxEntriesPerFile) > 0) {
this.onThresholdExceeded(buffer);
}
if (this.currentChannel.getBytesWritten() > this.maxBytesPerFile) {
this.onThresholdExceeded(buffer);
}
if (this.logFiles.size() > this.maxAmountOfFiles) {
this.onMaxLogFilesExceeded();
}
return this.currentChannel;
}
private void onThresholdExceeded(final ByteBuffer buffer) {
this.currentChannel.close(buffer, this.writerLog);
// we expect this.folder to exist
this.currentFileNumber++;
final Path newFile = this.getNextFileName(this.currentFileNumber, this.fileExtensionWithDot);
try {
// use CREATE_NEW to fail if the file already exists
OutputStream outputStream = Files.newOutputStream(newFile, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
// stream is not buffered, since the byte buffer itself is the buffer
if (this.shouldCompress) {
// final GZIPOutputStream compressedOutputStream = new GZIPOutputStream(outputStream);
final ZipOutputStream compressedOutputStream = new ZipOutputStream(outputStream);
final ZipEntry newZipEntry = new ZipEntry(newFile.toString() + FSUtil.NORMAL_FILE_EXTENSION);
compressedOutputStream.putNextEntry(newZipEntry);
outputStream = compressedOutputStream;
}
this.currentChannel = new PooledFileChannel(Channels.newChannel(outputStream));
} catch (final IOException e) {
throw new IllegalStateException("This exception should not have been thrown.", e);
}
this.numEntriesInCurrentFile = 1;
}
public void close(final ByteBuffer buffer) {
this.currentChannel.close(buffer, this.writerLog);
}
}
| apache-2.0 |
hudson3-plugins/commons-jelly | src/java/org/apache/commons/jelly/tags/core/IfTag.java | 2216 | /*
* Copyright 2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.jelly.tags.core;
import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.MissingAttributeException;
import org.apache.commons.jelly.TagSupport;
import org.apache.commons.jelly.XMLOutput;
import org.apache.commons.jelly.expression.Expression;
import org.apache.commons.jelly.impl.TagScript;
/** A tag which conditionally evaluates its body based on some condition
*
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @version $Revision: 155420 $
*
* @deprecated
* Implemented as {@link TagScript} in {@link CoreTagLibrary}
*/
public class IfTag extends TagSupport {
/** The expression to evaluate. */
private Expression test;
public IfTag() {
}
// Tag interface
//-------------------------------------------------------------------------
public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException {
if (test != null) {
if (test.evaluateAsBoolean(context)) {
invokeBody(output);
}
}
else {
throw new MissingAttributeException( "test" );
}
}
// Properties
//-------------------------------------------------------------------------
/** Sets the Jelly expression to evaluate. If this returns true, the body of
* the tag is evaluated
*
* @param test the Jelly expression to evaluate
*/
public void setTest(Expression test) {
this.test = test;
}
}
| apache-2.0 |