gt
stringclasses 1
value | context
stringlengths 2.05k
161k
|
---|---|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.memory.utils;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.engine.*;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.jdi.*;
import com.intellij.debugger.settings.CaptureConfigurable;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.debugger.settings.NodeRendererSettings;
import com.intellij.debugger.settings.ThreadsViewSettings;
import com.intellij.debugger.ui.breakpoints.StackCapturingLineBreakpoint;
import com.intellij.debugger.ui.tree.render.ClassRenderer;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.CommonClassNames;
import com.intellij.ui.ColoredTextContainer;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.frame.*;
import com.intellij.xdebugger.frame.presentation.XStringValuePresentation;
import com.intellij.xdebugger.impl.frame.XDebuggerFramesList;
import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants;
import com.sun.jdi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class StackFrameItem {
private static final Logger LOG = Logger.getInstance(StackFrameItem.class);
private static final List<XNamedValue> VARS_CAPTURE_DISABLED = Collections.singletonList(
JavaStackFrame.createMessageNode(DebuggerBundle.message("message.node.local.variables.capture.disabled"), null));
private static final List<XNamedValue> VARS_NOT_CAPTURED = Collections.singletonList(
JavaStackFrame.createMessageNode(DebuggerBundle.message("message.node.local.variables.not.captured"),
XDebuggerUIConstants.INFORMATION_MESSAGE_ICON));
public static final XDebuggerTreeNodeHyperlink CAPTURE_SETTINGS_OPENER = new XDebuggerTreeNodeHyperlink(" settings") {
@Override
public void onClick(MouseEvent event) {
ShowSettingsUtil.getInstance().showSettingsDialog(
CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(event.getComponent())),
CaptureConfigurable.class);
event.consume();
}
};
private final Location myLocation;
private final List<XNamedValue> myVariables;
public StackFrameItem(@NotNull Location location, List<XNamedValue> variables) {
myLocation = location;
myVariables = variables;
}
@NotNull
public String path() {
return myLocation.declaringType().name();
}
@NotNull
public String method() {
return myLocation.method().name();
}
public int line() {
return DebuggerUtilsEx.getLineNumber(myLocation, false);
}
@NotNull
public static List<StackFrameItem> createFrames(@NotNull SuspendContextImpl suspendContext, boolean withVars) throws EvaluateException {
ThreadReferenceProxyImpl threadReferenceProxy = suspendContext.getThread();
if (threadReferenceProxy != null) {
List<StackFrameProxyImpl> frameProxies = threadReferenceProxy.forceFrames();
List<StackFrameItem> res = new ArrayList<>(frameProxies.size());
for (StackFrameProxyImpl frame : frameProxies) {
try {
List<XNamedValue> vars = null;
Location location = frame.location();
Method method = location.method();
if (withVars) {
if (!DebuggerSettings.getInstance().CAPTURE_VARIABLES) {
vars = VARS_CAPTURE_DISABLED;
}
else if (method.isNative() || method.isBridge() || DefaultSyntheticProvider.checkIsSynthetic(method)) {
vars = VARS_NOT_CAPTURED;
}
else {
vars = new ArrayList<>();
try {
ObjectReference thisObject = frame.thisObject();
if (thisObject != null) {
vars.add(createVariable(thisObject, "this", VariableItem.VarType.OBJECT));
}
}
catch (EvaluateException e) {
LOG.debug(e);
}
try {
for (LocalVariableProxyImpl v : frame.visibleVariables()) {
try {
VariableItem.VarType varType = v.getVariable().isArgument() ? VariableItem.VarType.PARAM : VariableItem.VarType.OBJECT;
vars.add(createVariable(frame.getValue(v), v.name(), varType));
}
catch (EvaluateException e) {
LOG.debug(e);
}
}
}
catch (EvaluateException e) {
if (e.getCause() instanceof AbsentInformationException) {
vars.add(JavaStackFrame.LOCAL_VARIABLES_INFO_UNAVAILABLE_MESSAGE_NODE);
// only args for frames w/o debug info for now
try {
for (Map.Entry<DecompiledLocalVariable, Value> entry : LocalVariablesUtil
.fetchValues(frame, suspendContext.getDebugProcess(), false).entrySet()) {
vars.add(createVariable(entry.getValue(), entry.getKey().getDisplayName(), VariableItem.VarType.PARAM));
}
}
catch (Exception ex) {
LOG.info(ex);
}
}
else {
LOG.debug(e);
}
}
}
}
StackFrameItem frameItem = new StackFrameItem(location, vars);
res.add(frameItem);
List<StackFrameItem> relatedStack = StackCapturingLineBreakpoint.getRelatedStack(frame, suspendContext);
if (!ContainerUtil.isEmpty(relatedStack)) {
res.add(null); // separator
res.addAll(relatedStack);
break;
}
}
catch (EvaluateException e) {
LOG.debug(e);
}
}
return res;
}
return Collections.emptyList();
}
private static VariableItem createVariable(Value value, String name, VariableItem.VarType varType) {
String type = null;
String valueText = "null";
if (value instanceof ObjectReference) {
valueText = value instanceof StringReference ? ((StringReference)value).value() : "";
type = value.type().name() + "@" + ((ObjectReference)value).uniqueID();
}
else if (value != null) {
valueText = value.toString();
}
return new VariableItem(name, type, valueText, varType);
}
@Override
public String toString() {
return myLocation.toString();
}
private static class VariableItem extends XNamedValue {
enum VarType {PARAM, OBJECT}
private final String myType;
private final String myValue;
private final VarType myVarType;
public VariableItem(String name, String type, String value, VarType varType) {
super(name);
myType = type;
myValue = value;
myVarType = varType;
}
@Override
public void computePresentation(@NotNull XValueNode node, @NotNull XValuePlace place) {
ClassRenderer classRenderer = NodeRendererSettings.getInstance().getClassRenderer();
String type = Registry.is("debugger.showTypes") ? classRenderer.renderTypeName(myType) : null;
Icon icon = myVarType == VariableItem.VarType.PARAM ? PlatformIcons.PARAMETER_ICON : AllIcons.Debugger.Value;
if (myType != null && myType.startsWith(CommonClassNames.JAVA_LANG_STRING + "@")) {
node.setPresentation(icon, new XStringValuePresentation(myValue) {
@Nullable
@Override
public String getType() {
return classRenderer.SHOW_STRINGS_TYPE ? type : null;
}
}, false);
return;
}
node.setPresentation(icon, type, myValue, false);
}
}
public CapturedStackFrame createFrame(DebugProcessImpl debugProcess) {
return new CapturedStackFrame(debugProcess, this);
}
public static class CapturedStackFrame extends XStackFrame implements JVMStackFrameInfoProvider,
XDebuggerFramesList.ItemWithSeparatorAbove {
private static final String ASYNC_STACKTRACE_MESSAGE = DebuggerBundle.message("frame.panel.async.stacktrace");
private final XSourcePosition mySourcePosition;
private final boolean myIsSynthetic;
private final boolean myIsInLibraryContent;
private final String myPath;
private final String myMethodName;
private final int myLineNumber;
private final List<XNamedValue> myVariables;
private volatile boolean myWithSeparator;
public CapturedStackFrame(DebugProcessImpl debugProcess, StackFrameItem item) {
DebuggerManagerThreadImpl.assertIsManagerThread();
myPath = item.path();
myMethodName = item.method();
myLineNumber = item.line();
myVariables = item.myVariables;
Location location = item.myLocation;
mySourcePosition = DebuggerUtilsEx.toXSourcePosition(debugProcess.getPositionManager().getSourcePosition(location));
myIsSynthetic = DebuggerUtils.isSynthetic(location.method());
myIsInLibraryContent =
DebuggerUtilsEx.isInLibraryContent(mySourcePosition != null ? mySourcePosition.getFile() : null, debugProcess.getProject());
}
@Nullable
@Override
public XSourcePosition getSourcePosition() {
return mySourcePosition;
}
public boolean isSynthetic() {
return myIsSynthetic;
}
public boolean isInLibraryContent() {
return myIsInLibraryContent;
}
@Override
public void customizePresentation(@NotNull ColoredTextContainer component) {
component.setIcon(JBUI.scale(EmptyIcon.create(6)));
component.append(String.format("%s:%d", myMethodName, myLineNumber), getAttributes());
ThreadsViewSettings settings = ThreadsViewSettings.getInstance();
if (settings.SHOW_CLASS_NAME) {
component.append(String.format(", %s", StringUtil.getShortName(myPath)), getAttributes());
String packageName = StringUtil.getPackageName(myPath);
if (settings.SHOW_PACKAGE_NAME && !packageName.trim().isEmpty()) {
component.append(String.format(" (%s)", packageName), SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES);
}
}
}
@Override
public void computeChildren(@NotNull XCompositeNode node) {
XValueChildrenList children = XValueChildrenList.EMPTY;
if (myVariables == VARS_CAPTURE_DISABLED) {
node.setMessage(DebuggerBundle.message("message.node.local.variables.capture.disabled"), null,
SimpleTextAttributes.REGULAR_ATTRIBUTES, CAPTURE_SETTINGS_OPENER);
}
else if (myVariables != null) {
children = new XValueChildrenList(myVariables.size());
myVariables.forEach(children::add);
}
node.addChildren(children, true);
}
private SimpleTextAttributes getAttributes() {
if (isSynthetic() || isInLibraryContent()) {
return SimpleTextAttributes.GRAYED_ATTRIBUTES;
}
return SimpleTextAttributes.REGULAR_ATTRIBUTES;
}
@Override
public String getCaptionAboveOf() {
return ASYNC_STACKTRACE_MESSAGE;
}
@Override
public boolean hasSeparatorAbove() {
return myWithSeparator;
}
public void setWithSeparator(boolean withSeparator) {
myWithSeparator = withSeparator;
}
@Override
public String toString() {
if (mySourcePosition != null) {
return mySourcePosition.getFile().getName() + ":" + (mySourcePosition.getLine() + 1);
}
return "<position unknown>";
}
}
}
|
|
package org.openfact.services.resources.admin;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.GET;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.jboss.logging.Logger;
import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.NoLogWebApplicationException;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.openfact.common.ClientConnection;
import org.openfact.models.AdminRoles;
import org.openfact.models.OpenfactSession;
import org.openfact.models.OrganizationModel;
import org.openfact.security.SecurityContextProvider;
import org.openfact.services.managers.OrganizationManager;
import org.openfact.services.resources.Cors;
import org.openfact.services.resources.admin.info.ServerInfoAdminResource;
/**
* @author [email protected]
*/
@Path("/admin")
public class AdminRoot {
protected static final Logger logger = Logger.getLogger(AdminRoot.class);
@Context
protected UriInfo uriInfo;
@Context
protected ClientConnection clientConnection;
@Context
protected HttpRequest request;
@Context
protected HttpResponse response;
@Context
protected OpenfactSession session;
public AdminRoot() {
}
public static UriBuilder adminBaseUrl(UriInfo uriInfo) {
return adminBaseUrl(uriInfo.getBaseUriBuilder());
}
public static UriBuilder adminBaseUrl(UriBuilder base) {
return base.path(AdminRoot.class);
}
/**
* Convenience path to master Organization admin console
*
* @exclude
* @return
*/
@GET
public Response masterOrganizationAdminConsoleRedirect() {
OrganizationModel master = new OrganizationManager(session).getOpenfactAdminstrationOrganization();
return Response.status(302).location(uriInfo.getBaseUriBuilder().path(AdminRoot.class)
.path(AdminRoot.class, "getAdminConsole").path("/").build(master.getName())).build();
}
/**
* Convenience path to master Organization admin console
*
* @exclude
* @return
*/
@GET
@Path("index.{html:html}")
public Response masterOrganizationAdminConsoleRedirectHtml() {
return masterOrganizationAdminConsoleRedirect();
}
protected OrganizationModel locateOrganization(String name, OrganizationManager organizationManager) {
OrganizationModel organization = organizationManager.getOrganizationByName(name);
if (organization == null) {
throw new NotFoundException("Organization not found. Did you type in a bad URL?");
}
session.getContext().setOrganization(organization);
return organization;
}
public static UriBuilder adminConsoleUrl(UriInfo uriInfo) {
return adminConsoleUrl(uriInfo.getBaseUriBuilder());
}
public static UriBuilder adminConsoleUrl(UriBuilder base) {
return adminBaseUrl(base).path(AdminRoot.class, "getAdminConsole");
}
/**
* path to Organization admin console ui
*
* @exclude
* @param name
* Organization name (not id!)
* @return
*/
@Path("{organization}/console")
public AdminConsole getAdminConsole(final @PathParam("organization") String name) {
OrganizationManager organizationManager = new OrganizationManager(session);
OrganizationModel organization = locateOrganization(name, organizationManager);
AdminConsole service = new AdminConsole(organization);
ResteasyProviderFactory.getInstance().injectProperties(service);
return service;
}
protected AdminAuth authenticateOrganizationAdminRequest(HttpHeaders headers) {
SecurityContextProvider authResult = session.getProvider(SecurityContextProvider.class);
String organizationName = authResult.getCurrentOrganizationName(headers);
OrganizationManager organizationManager = new OrganizationManager(session);
OrganizationModel organization = organizationManager.getOrganizationByName(organizationName);
if (organization == null) {
throw new NotAuthorizedException("Unknown organization in token");
}
session.getContext().setOrganization(organization);
return new AdminAuth(organization, authResult.getCurrentUser(headers));
}
public static UriBuilder organizationsUrl(UriInfo uriInfo) {
return organizationsUrl(uriInfo.getBaseUriBuilder());
}
public static UriBuilder organizationsUrl(UriBuilder base) {
return adminBaseUrl(base).path(AdminRoot.class, "getOrganizationsAdmin");
}
/**
* Base Path to Organization admin REST interface
*
* @param headers
* @return
*/
@Path("organizations")
public OrganizationsAdminResource getOrganizationsAdmin(@Context final HttpHeaders headers) {
handlePreflightRequest();
AdminAuth auth = authenticateOrganizationAdminRequest(headers);
if (auth != null) {
logger.debug("authenticated admin access for: " + auth.getUser().getUsername());
}
Cors.add(request).allowedOrigins("*").allowedMethods("GET", "PUT", "POST", "DELETE")
.exposedHeaders("Location").auth().build(response);
OrganizationsAdminResource adminResource = new OrganizationsAdminResource(auth);
ResteasyProviderFactory.getInstance().injectProperties(adminResource);
return adminResource;
}
/**
* General information about the server
*
* @param headers
* @return
*/
@Path("serverinfo")
public ServerInfoAdminResource getServerInfo(@Context final HttpHeaders headers) {
handlePreflightRequest();
AdminAuth auth = authenticateOrganizationAdminRequest(headers);
if (!isAdmin(auth)) {
throw new ForbiddenException();
}
if (auth != null) {
logger.debug("authenticated admin access for: " + auth.getUser().getUsername());
}
Cors.add(request).allowedOrigins("*").allowedMethods("GET", "PUT", "POST", "DELETE").auth()
.build(response);
ServerInfoAdminResource adminResource = new ServerInfoAdminResource();
ResteasyProviderFactory.getInstance().injectProperties(adminResource);
return adminResource;
}
protected boolean isAdmin(AdminAuth auth) {
OrganizationManager organizationManager = new OrganizationManager(session);
if (auth.getOrganization().equals(organizationManager.getOpenfactAdminstrationOrganization())) {
if (auth.hasOneOfOrganizationRole(AdminRoles.ADMIN, AdminRoles.CREATE_ORGANIZATION)) {
return true;
}
return false;
}
return false;
}
protected void handlePreflightRequest() {
if (request.getHttpMethod().equalsIgnoreCase("OPTIONS")) {
logger.debug("Cors admin pre-flight");
Response response = Cors.add(request, Response.ok()).preflight()
.allowedMethods("GET", "PUT", "POST", "DELETE").auth().build();
throw new NoLogWebApplicationException(response);
}
}
@Path("codes-catalog")
public CodesCatalogAdminResource getCodesCatalogResource(@Context final HttpHeaders headers) {
handlePreflightRequest();
AdminAuth auth = authenticateOrganizationAdminRequest(headers);
if (auth != null) {
logger.debug("authenticated admin access for: " + auth.getUser().getUsername());
}
Cors.add(request).allowedOrigins("*").allowedMethods("GET", "PUT", "POST", "DELETE")
.exposedHeaders("Location").auth().build(response);
CodesCatalogAdminResource catalogResource = new CodesCatalogAdminResource(auth);
ResteasyProviderFactory.getInstance().injectProperties(catalogResource);
return catalogResource;
}
@Path("commons")
public CommonsAdminResource getCommonsResource(@Context final HttpHeaders headers) {
handlePreflightRequest();
AdminAuth auth = authenticateOrganizationAdminRequest(headers);
if (auth != null) {
logger.debug("authenticated admin access for: " + auth.getUser().getUsername());
}
Cors.add(request).allowedOrigins("*").allowedMethods("GET", "PUT", "POST", "DELETE")
.exposedHeaders("Location").auth().build(response);
CommonsAdminResource commonsResource = new CommonsAdminResource(auth);
ResteasyProviderFactory.getInstance().injectProperties(commonsResource);
return commonsResource;
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.junit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.FileDeploymentManager;
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
import org.apache.activemq.artemis.core.config.impl.FileConfiguration;
import org.apache.activemq.artemis.core.remoting.impl.invm.InVMAcceptorFactory;
import org.apache.activemq.artemis.core.remoting.impl.invm.TransportConstants;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.BindingQueryResult;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.junit.rules.ExternalResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A JUnit Rule that embeds an ActiveMQ Artemis server into a test.
*
* This JUnit Rule is designed to simplify using embedded servers in unit tests. Adding the rule to a test will startup
* an embedded server, which can then be used by client applications.
*
* <pre><code>
* public class SimpleTest {
* @Rule
* public EmbeddedActiveMQResource server = new EmbeddedActiveMQResource();
*
* @Test
* public void testSomething() throws Exception {
* // Use the embedded server here
* }
* }
* </code></pre>
*/
public class EmbeddedActiveMQResource extends ExternalResource {
static final String SERVER_NAME = "embedded-server";
Logger log = LoggerFactory.getLogger(this.getClass());
boolean useDurableMessage = true;
boolean useDurableQueue = true;
long defaultReceiveTimeout = 50;
Configuration configuration;
EmbeddedActiveMQ server;
InternalClient internalClient;
/**
* Create a default EmbeddedActiveMQResource
*/
public EmbeddedActiveMQResource() {
configuration = new ConfigurationImpl().setName(SERVER_NAME).setPersistenceEnabled(false).setSecurityEnabled(false).addAcceptorConfiguration(new TransportConfiguration(InVMAcceptorFactory.class.getName())).addAddressesSetting("#", new AddressSettings().setDeadLetterAddress(SimpleString.toSimpleString("dla")).setExpiryAddress(SimpleString.toSimpleString("expiry")));
init();
}
/**
* Create a default EmbeddedActiveMQResource with the specified serverId
*
* @param serverId server id
*/
public EmbeddedActiveMQResource(int serverId) {
Map<String, Object> params = new HashMap<>();
params.put(TransportConstants.SERVER_ID_PROP_NAME, serverId);
TransportConfiguration transportConfiguration = new TransportConfiguration(InVMAcceptorFactory.class.getName(), params);
configuration = new ConfigurationImpl().setName(SERVER_NAME + "-" + serverId).setPersistenceEnabled(false).setSecurityEnabled(false).addAcceptorConfiguration(transportConfiguration);
init();
}
/**
* Creates an EmbeddedActiveMQResource using the specified configuration
*
* @param configuration ActiveMQServer configuration
*/
public EmbeddedActiveMQResource(Configuration configuration) {
this.configuration = configuration;
init();
}
/**
* Creates an EmbeddedActiveMQResource using the specified configuration file
*
* @param filename ActiveMQServer configuration file name
*/
public EmbeddedActiveMQResource(String filename) {
if (filename == null) {
throw new IllegalArgumentException("ActiveMQServer configuration file name cannot be null");
}
FileDeploymentManager deploymentManager = new FileDeploymentManager(filename);
FileConfiguration config = new FileConfiguration();
deploymentManager.addDeployable(config);
try {
deploymentManager.readConfiguration();
} catch (Exception ex) {
throw new EmbeddedActiveMQResourceException(String.format("Failed to read configuration file %s", filename), ex);
}
this.configuration = config;
init();
}
/**
* Adds properties to a ClientMessage
*
* @param message
* @param properties
*/
public static void addMessageProperties(ClientMessage message, Map<String, Object> properties) {
if (properties != null && properties.size() > 0) {
for (Map.Entry<String, Object> property : properties.entrySet()) {
message.putObjectProperty(property.getKey(), property.getValue());
}
}
}
private void init() {
if (server == null) {
server = new EmbeddedActiveMQ().setConfiguration(configuration);
}
}
/**
* Start the embedded ActiveMQ Artemis server.
*
* The server will normally be started by JUnit using the before() method. This method allows the server to
* be started manually to support advanced testing scenarios.
*/
public void start() {
try {
server.start();
} catch (Exception ex) {
throw new RuntimeException(String.format("Exception encountered starting %s: %s", server.getClass().getName(), this.getServerName()), ex);
}
configuration = server.getActiveMQServer().getConfiguration();
}
/**
* Stop the embedded ActiveMQ Artemis server
*
* The server will normally be stopped by JUnit using the after() method. This method allows the server to
* be stopped manually to support advanced testing scenarios.
*/
public void stop() {
if (internalClient != null) {
internalClient.stop();
internalClient = null;
}
if (server != null) {
try {
server.stop();
} catch (Exception ex) {
log.warn(String.format("Exception encountered stopping %s: %s", server.getClass().getSimpleName(), this.getServerName()), ex);
}
}
}
/**
* Invoked by JUnit to setup the resource - start the embedded ActiveMQ Artemis server
*/
@Override
protected void before() throws Throwable {
log.info("Starting {}: {}", this.getClass().getSimpleName(), getServerName());
this.start();
super.before();
}
/**
* Invoked by JUnit to tear down the resource - stops the embedded ActiveMQ Artemis server
*/
@Override
protected void after() {
log.info("Stopping {}: {}", this.getClass().getSimpleName(), getServerName());
this.stop();
super.after();
}
public boolean isUseDurableMessage() {
return useDurableMessage;
}
/**
* Disables/Enables creating durable messages. By default, durable messages are created
*
* @param useDurableMessage if true, durable messages will be created
*/
public void setUseDurableMessage(boolean useDurableMessage) {
this.useDurableMessage = useDurableMessage;
}
public boolean isUseDurableQueue() {
return useDurableQueue;
}
/**
* Disables/Enables creating durable queues. By default, durable queues are created
*
* @param useDurableQueue if true, durable messages will be created
*/
public void setUseDurableQueue(boolean useDurableQueue) {
this.useDurableQueue = useDurableQueue;
}
public long getDefaultReceiveTimeout() {
return defaultReceiveTimeout;
}
/**
* Sets the default timeout in milliseconds used when receiving messages. Defaults to 50 milliseconds
*
* @param defaultReceiveTimeout received timeout in milliseconds
*/
public void setDefaultReceiveTimeout(long defaultReceiveTimeout) {
this.defaultReceiveTimeout = defaultReceiveTimeout;
}
/**
* Get the EmbeddedActiveMQ server.
*
* This may be required for advanced configuration of the EmbeddedActiveMQ server.
*
* @return the embedded ActiveMQ broker
*/
public EmbeddedActiveMQ getServer() {
return server;
}
/**
* Get the name of the EmbeddedActiveMQ server
*
* @return name of the embedded server
*/
public String getServerName() {
String name = "unknown";
ActiveMQServer activeMQServer = server.getActiveMQServer();
if (activeMQServer != null) {
name = activeMQServer.getConfiguration().getName();
} else if (configuration != null) {
name = configuration.getName();
}
return name;
}
/**
* Get the VM URL for the embedded EmbeddedActiveMQ server
*
* @return the VM URL for the embedded server
*/
public String getVmURL() {
String vmURL = "vm://0";
for (TransportConfiguration transportConfiguration : configuration.getAcceptorConfigurations()) {
Map<String, Object> params = transportConfiguration.getParams();
if (params != null && params.containsKey(TransportConstants.SERVER_ID_PROP_NAME)) {
vmURL = "vm://" + params.get(TransportConstants.SERVER_ID_PROP_NAME);
}
}
return vmURL;
}
public long getMessageCount(String queueName) {
return getMessageCount(SimpleString.toSimpleString(queueName));
}
/**
* Get the number of messages in a specific queue.
*
* @param queueName the name of the queue
* @return the number of messages in the queue; -1 if queue is not found
*/
public long getMessageCount(SimpleString queueName) {
Queue queue = locateQueue(queueName);
if (queue == null) {
log.warn("getMessageCount(queueName) - queue {} not found; returning -1", queueName.toString());
return -1;
}
return queue.getMessageCount();
}
public Queue locateQueue(String queueName) {
return locateQueue(SimpleString.toSimpleString(queueName));
}
public Queue locateQueue(SimpleString queueName) {
return server.getActiveMQServer().locateQueue(queueName);
}
public List<Queue> getBoundQueues(String address) {
return getBoundQueues(SimpleString.toSimpleString(address));
}
public List<Queue> getBoundQueues(SimpleString address) {
if (address == null) {
throw new IllegalArgumentException("getBoundQueues( address ) - address cannot be null");
}
List<Queue> boundQueues = new java.util.LinkedList<>();
BindingQueryResult bindingQueryResult = null;
try {
bindingQueryResult = server.getActiveMQServer().bindingQuery(address);
} catch (Exception e) {
throw new EmbeddedActiveMQResourceException(String.format("getBoundQueues( %s ) - bindingQuery( %s ) failed", address.toString(), address.toString()));
}
if (bindingQueryResult.isExists()) {
for (SimpleString queueName : bindingQueryResult.getQueueNames()) {
boundQueues.add(server.getActiveMQServer().locateQueue(queueName));
}
}
return boundQueues;
}
public Queue createQueue(String name) {
return createQueue(SimpleString.toSimpleString(name), SimpleString.toSimpleString(name));
}
public Queue createQueue(String address, String name) {
return createQueue(SimpleString.toSimpleString(address), SimpleString.toSimpleString(name));
}
public Queue createQueue(SimpleString address, SimpleString name) {
Queue queue = null;
try {
queue = server.getActiveMQServer().createQueue(new QueueConfiguration(name).setAddress(address).setDurable(isUseDurableQueue()));
} catch (Exception ex) {
throw new EmbeddedActiveMQResourceException(String.format("Failed to create queue: queueName = %s, name = %s", address.toString(), name.toString()), ex);
}
return queue;
}
public void createSharedQueue(String name, String user) {
createSharedQueue(SimpleString.toSimpleString(name), SimpleString.toSimpleString(name), SimpleString.toSimpleString(user));
}
public void createSharedQueue(String address, String name, String user) {
createSharedQueue(SimpleString.toSimpleString(address), SimpleString.toSimpleString(name), SimpleString.toSimpleString(user));
}
public void createSharedQueue(SimpleString address, SimpleString name, SimpleString user) {
try {
server.getActiveMQServer().createSharedQueue(new QueueConfiguration(name).setAddress(address).setRoutingType(RoutingType.MULTICAST).setDurable(isUseDurableQueue()).setUser(user));
} catch (Exception ex) {
throw new EmbeddedActiveMQResourceException(String.format("Failed to create shared queue: queueName = %s, name = %s, user = %s", address.toString(), name.toString(), user.toString()), ex);
}
}
/**
* Create a ClientMessage
*
* If useDurableMessage is false, a non-durable message is created. Otherwise, a durable message is created
*
* @return a new ClientMessage
*/
public ClientMessage createMessage() {
getInternalClient();
return internalClient.createMessage(isUseDurableMessage());
}
/**
* Create a ClientMessage with the specified body
*
* If useDurableMessage is false, a non-durable message is created. Otherwise, a durable message is created
*
* @param body the body for the new message
* @return a new ClientMessage with the specified body
*/
public ClientMessage createMessage(byte[] body) {
getInternalClient();
ClientMessage message = internalClient.createMessage(isUseDurableMessage());
if (body != null) {
message.writeBodyBufferBytes(body);
}
return message;
}
/**
* Create a ClientMessage with the specified body
*
* If useDurableMessage is false, a non-durable message is created. Otherwise, a durable message is created
*
* @param body the body for the new message
* @return a new ClientMessage with the specified body
*/
public ClientMessage createMessage(String body) {
getInternalClient();
ClientMessage message = internalClient.createMessage(isUseDurableMessage());
if (body != null) {
message.writeBodyBufferString(body);
}
return message;
}
/**
* Create a ClientMessage with the specified message properties
*
* If useDurableMessage is false, a non-durable message is created. Otherwise, a durable message is created
*
* @param properties message properties for the new message
* @return a new ClientMessage with the specified message properties
*/
public ClientMessage createMessageWithProperties(Map<String, Object> properties) {
getInternalClient();
ClientMessage message = internalClient.createMessage(isUseDurableMessage());
addMessageProperties(message, properties);
return message;
}
/**
* Create a ClientMessage with the specified body and message properties
*
* If useDurableMessage is false, a non-durable message is created. Otherwise, a durable message is created
*
* @param body the body for the new message
* @param properties message properties for the new message
* @return a new ClientMessage with the specified body and message properties
*/
public ClientMessage createMessageWithProperties(byte[] body, Map<String, Object> properties) {
ClientMessage message = createMessage(body);
addMessageProperties(message, properties);
return message;
}
/**
* Create a ClientMessage with the specified body and message properties
*
* If useDurableMessage is false, a non-durable message is created. Otherwise, a durable message is created
*
* @param body the body for the new message
* @param properties message properties for the new message
* @return a new ClientMessage with the specified body and message properties
*/
public ClientMessage createMessageWithProperties(String body, Map<String, Object> properties) {
ClientMessage message = createMessage(body);
addMessageProperties(message, properties);
return message;
}
/**
* Send a message to an address
*
* @param address the target queueName for the message
* @param message the message to send
*/
public void sendMessage(String address, ClientMessage message) {
sendMessage(SimpleString.toSimpleString(address), message);
}
/**
* Create a new message with the specified body, and send the message to an address
*
* @param address the target queueName for the message
* @param body the body for the new message
* @return the message that was sent
*/
public ClientMessage sendMessage(String address, byte[] body) {
return sendMessage(SimpleString.toSimpleString(address), body);
}
/**
* Create a new message with the specified body, and send the message to an address
*
* @param address the target queueName for the message
* @param body the body for the new message
* @return the message that was sent
*/
public ClientMessage sendMessage(String address, String body) {
return sendMessage(SimpleString.toSimpleString(address), body);
}
/**
* Create a new message with the specified properties, and send the message to an address
*
* @param address the target queueName for the message
* @param properties message properties for the new message
* @return the message that was sent
*/
public ClientMessage sendMessageWithProperties(String address, Map<String, Object> properties) {
return sendMessageWithProperties(SimpleString.toSimpleString(address), properties);
}
/**
* Create a new message with the specified body and properties, and send the message to an address
*
* @param address the target queueName for the message
* @param body the body for the new message
* @param properties message properties for the new message
* @return the message that was sent
*/
public ClientMessage sendMessageWithProperties(String address, byte[] body, Map<String, Object> properties) {
return sendMessageWithProperties(SimpleString.toSimpleString(address), body, properties);
}
/**
* Create a new message with the specified body and properties, and send the message to an address
*
* @param address the target queueName for the message
* @param body the body for the new message
* @param properties message properties for the new message
* @return the message that was sent
*/
public ClientMessage sendMessageWithProperties(String address, String body, Map<String, Object> properties) {
return sendMessageWithProperties(SimpleString.toSimpleString(address), body, properties);
}
/**
* Send a message to an queueName
*
* @param address the target queueName for the message
* @param message the message to send
*/
public void sendMessage(SimpleString address, ClientMessage message) {
if (address == null) {
throw new IllegalArgumentException("sendMessage failure - queueName is required");
} else if (message == null) {
throw new IllegalArgumentException("sendMessage failure - a ClientMessage is required");
}
getInternalClient();
internalClient.sendMessage(address, message);
}
/**
* Create a new message with the specified body, and send the message to an queueName
*
* @param address the target queueName for the message
* @param body the body for the new message
* @return the message that was sent
*/
public ClientMessage sendMessage(SimpleString address, byte[] body) {
ClientMessage message = createMessage(body);
sendMessage(address, message);
return message;
}
/**
* Create a new message with the specified body, and send the message to an queueName
*
* @param address the target queueName for the message
* @param body the body for the new message
* @return the message that was sent
*/
public ClientMessage sendMessage(SimpleString address, String body) {
ClientMessage message = createMessage(body);
sendMessage(address, message);
return message;
}
/**
* Create a new message with the specified properties, and send the message to an queueName
*
* @param address the target queueName for the message
* @param properties message properties for the new message
* @return the message that was sent
*/
public ClientMessage sendMessageWithProperties(SimpleString address, Map<String, Object> properties) {
ClientMessage message = createMessageWithProperties(properties);
sendMessage(address, message);
return message;
}
/**
* Create a new message with the specified body and properties, and send the message to an queueName
*
* @param address the target queueName for the message
* @param body the body for the new message
* @param properties message properties for the new message
* @return the message that was sent
*/
public ClientMessage sendMessageWithProperties(SimpleString address, byte[] body, Map<String, Object> properties) {
ClientMessage message = createMessageWithProperties(body, properties);
sendMessage(address, message);
return message;
}
/**
* Create a new message with the specified body and properties, and send the message to an queueName
*
* @param address the target queueName for the message
* @param body the body for the new message
* @param properties message properties for the new message
* @return the message that was sent
*/
public ClientMessage sendMessageWithProperties(SimpleString address, String body, Map<String, Object> properties) {
ClientMessage message = createMessageWithProperties(body, properties);
sendMessage(address, message);
return message;
}
/**
* Receive a message from the specified queue using the default receive timeout
*
* @param queueName name of the source queue
* @return the received ClientMessage, null if the receive timed-out
*/
public ClientMessage receiveMessage(String queueName) {
return receiveMessage(SimpleString.toSimpleString(queueName));
}
/**
* Receive a message from the specified queue using the specified receive timeout
*
* @param queueName name of the source queue
* @param timeout receive timeout in milliseconds
* @return the received ClientMessage, null if the receive timed-out
*/
public ClientMessage receiveMessage(String queueName, long timeout) {
return receiveMessage(SimpleString.toSimpleString(queueName), timeout);
}
/**
* Receive a message from the specified queue using the default receive timeout
*
* @param queueName name of the source queue
* @return the received ClientMessage, null if the receive timed-out
*/
public ClientMessage receiveMessage(SimpleString queueName) {
final boolean browseOnly = false;
return getInternalClient().receiveMessage(queueName, defaultReceiveTimeout, browseOnly);
}
/**
* Receive a message from the specified queue using the specified receive timeout
*
* @param queueName name of the source queue
* @param timeout receive timeout in milliseconds
* @return the received ClientMessage, null if the receive timed-out
*/
public ClientMessage receiveMessage(SimpleString queueName, long timeout) {
final boolean browseOnly = false;
return getInternalClient().receiveMessage(queueName, timeout, browseOnly);
}
/**
* Browse a message (receive but do not consume) from the specified queue using the default receive timeout
*
* @param queueName name of the source queue
* @return the received ClientMessage, null if the receive timed-out
*/
public ClientMessage browseMessage(String queueName) {
return browseMessage(SimpleString.toSimpleString(queueName), defaultReceiveTimeout);
}
/**
* Browse a message (receive but do not consume) a message from the specified queue using the specified receive timeout
*
* @param queueName name of the source queue
* @param timeout receive timeout in milliseconds
* @return the received ClientMessage, null if the receive timed-out
*/
public ClientMessage browseMessage(String queueName, long timeout) {
return browseMessage(SimpleString.toSimpleString(queueName), timeout);
}
/**
* Browse a message (receive but do not consume) from the specified queue using the default receive timeout
*
* @param queueName name of the source queue
* @return the received ClientMessage, null if the receive timed-out
*/
public ClientMessage browseMessage(SimpleString queueName) {
final boolean browseOnly = true;
return getInternalClient().receiveMessage(queueName, defaultReceiveTimeout, browseOnly);
}
/**
* Browse a message (receive but do not consume) a message from the specified queue using the specified receive timeout
*
* @param queueName name of the source queue
* @param timeout receive timeout in milliseconds
* @return the received ClientMessage, null if the receive timed-out
*/
public ClientMessage browseMessage(SimpleString queueName, long timeout) {
final boolean browseOnly = true;
return getInternalClient().receiveMessage(queueName, timeout, browseOnly);
}
private InternalClient getInternalClient() {
if (internalClient == null) {
log.info("Creating Internal Client");
internalClient = new InternalClient();
internalClient.start();
}
return internalClient;
}
public static class EmbeddedActiveMQResourceException extends RuntimeException {
public EmbeddedActiveMQResourceException(String message) {
super(message);
}
public EmbeddedActiveMQResourceException(String message, Exception cause) {
super(message, cause);
}
}
private class InternalClient {
ServerLocator serverLocator;
ClientSessionFactory sessionFactory;
ClientSession session;
ClientProducer producer;
InternalClient() {
}
void start() {
log.info("Starting {}", this.getClass().getSimpleName());
try {
serverLocator = ActiveMQClient.createServerLocator(getVmURL());
sessionFactory = serverLocator.createSessionFactory();
} catch (RuntimeException runtimeEx) {
throw runtimeEx;
} catch (Exception ex) {
throw new EmbeddedActiveMQResourceException("Internal Client creation failure", ex);
}
try {
session = sessionFactory.createSession();
producer = session.createProducer((String) null);
session.start();
} catch (ActiveMQException amqEx) {
throw new EmbeddedActiveMQResourceException("Internal Client creation failure", amqEx);
}
}
void stop() {
if (producer != null) {
try {
producer.close();
} catch (ActiveMQException amqEx) {
log.warn("ActiveMQException encountered closing InternalClient ClientProducer - ignoring", amqEx);
} finally {
producer = null;
}
}
if (session != null) {
try {
session.close();
} catch (ActiveMQException amqEx) {
log.warn("ActiveMQException encountered closing InternalClient ClientSession - ignoring", amqEx);
} finally {
session = null;
}
}
if (sessionFactory != null) {
sessionFactory.close();
sessionFactory = null;
}
if (serverLocator != null) {
serverLocator.close();
serverLocator = null;
}
}
public ClientMessage createMessage(boolean durable) {
checkSession();
return session.createMessage(durable);
}
public void sendMessage(SimpleString address, ClientMessage message) {
checkSession();
if (producer == null) {
throw new IllegalStateException("ClientProducer is null - has the InternalClient been started?");
}
try {
producer.send(address, message);
} catch (ActiveMQException amqEx) {
throw new EmbeddedActiveMQResourceException(String.format("Failed to send message to %s", address.toString()), amqEx);
}
}
public ClientMessage receiveMessage(SimpleString address, long timeout, boolean browseOnly) {
checkSession();
ClientConsumer consumer = null;
try {
consumer = session.createConsumer(address, browseOnly);
} catch (ActiveMQException amqEx) {
throw new EmbeddedActiveMQResourceException(String.format("Failed to create consumer for %s", address.toString()), amqEx);
}
ClientMessage message = null;
if (timeout > 0) {
try {
message = consumer.receive(timeout);
} catch (ActiveMQException amqEx) {
throw new EmbeddedActiveMQResourceException(String.format("ClientConsumer.receive( timeout = %d ) for %s failed", timeout, address.toString()), amqEx);
}
} else if (timeout == 0) {
try {
message = consumer.receiveImmediate();
} catch (ActiveMQException amqEx) {
throw new EmbeddedActiveMQResourceException(String.format("ClientConsumer.receiveImmediate() for %s failed", address.toString()), amqEx);
}
} else {
try {
message = consumer.receive();
} catch (ActiveMQException amqEx) {
throw new EmbeddedActiveMQResourceException(String.format("ClientConsumer.receive() for %s failed", address.toString()), amqEx);
}
}
return message;
}
void checkSession() {
getInternalClient();
if (session == null) {
throw new IllegalStateException("ClientSession is null - has the InternalClient been started?");
}
}
}
}
|
|
package uk.co.boundedbuffer;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by robaustin on 31/01/2014.
*/
public class ConcurrentBlockingObjectQueueTest {
@Test
public void testTake() throws Exception {
final ConcurrentBlockingObjectQueue<Integer> queue = new ConcurrentBlockingObjectQueue<Integer>();
// writer thread
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
queue.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
final ArrayBlockingQueue<Integer> actual = new ArrayBlockingQueue<Integer>(1);
// reader thread
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
final int value;
try {
value = queue.take();
actual.add(value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
final Integer value = actual.poll(1, TimeUnit.SECONDS);
Assert.assertEquals((int) value, 1);
Thread.sleep(100);
}
@Test
public void testWrite() throws Exception {
}
@Test
public void testRead() throws Exception {
final ConcurrentBlockingObjectQueue<Integer> queue = new ConcurrentBlockingObjectQueue<Integer>();
queue.put(10);
final int value = queue.take();
junit.framework.Assert.assertEquals(10, value);
}
@Test
public void testRead2() throws Exception {
final ConcurrentBlockingObjectQueue<Integer> queue = new ConcurrentBlockingObjectQueue<Integer>();
queue.put(10);
queue.put(11);
final int value = queue.take();
junit.framework.Assert.assertEquals(10, value);
final int value1 = queue.take();
junit.framework.Assert.assertEquals(11, value1);
}
@Test
public void testReadLoop() throws Exception {
final ConcurrentBlockingObjectQueue<Integer> queue = new ConcurrentBlockingObjectQueue<Integer>();
for (int i = 1; i < 50; i++) {
queue.put(i);
final int value = queue.take();
junit.framework.Assert.assertEquals(i, value);
}
}
/**
* reader and add, reader and writers on different threads
*
* @throws Exception
*/
@Test
public void testWithFasterReader() throws Exception {
final ConcurrentBlockingObjectQueue<Integer> queue = new ConcurrentBlockingObjectQueue<Integer>();
final int max = 100;
final CountDownLatch countDown = new CountDownLatch(1);
final AtomicBoolean success = new AtomicBoolean(true);
new Thread(
new Runnable() {
@Override
public void run() {
for (int i = 1; i < max; i++) {
try {
queue.put(i);
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(
new Runnable() {
@Override
public void run() {
int value = 0;
for (int i = 1; i < max; i++) {
try {
final int newValue = queue.take();
junit.framework.Assert.assertEquals(i, newValue);
if (newValue != value + 1) {
success.set(false);
return;
}
value = newValue;
Thread.sleep((int) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
countDown.countDown();
}
}).start();
countDown.await();
Assert.assertTrue(success.get());
}
/**
* faster writer
*
* @throws Exception
*/
@Test
public void testWithFasterWriter() throws Exception {
final ConcurrentBlockingObjectQueue<Integer> queue = new ConcurrentBlockingObjectQueue<Integer>();
final int max = 200;
final CountDownLatch countDown = new CountDownLatch(1);
final AtomicBoolean success = new AtomicBoolean(true);
new Thread(
new Runnable() {
@Override
public void run() {
for (int i = 1; i < max; i++) {
try {
queue.put(i);
Thread.sleep((int) (Math.random() * 3));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(
new Runnable() {
@Override
public void run() {
int value = 0;
for (int i = 1; i < max; i++) {
try {
final int newValue = queue.take();
junit.framework.Assert.assertEquals(i, newValue);
if (newValue != value + 1) {
success.set(false);
return;
}
value = newValue;
Thread.sleep((int) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
countDown.countDown();
}
}).start();
countDown.await();
Assert.assertTrue(success.get());
}
@Test
@Ignore
public void testFlatOut() throws Exception {
testConcurrentBlockingObjectQueue(Integer.MAX_VALUE);
}
private void testConcurrentBlockingObjectQueue(final int nTimes) throws InterruptedException {
final ConcurrentBlockingObjectQueue<Integer> queue = new ConcurrentBlockingObjectQueue<Integer>(1024);
final CountDownLatch countDown = new CountDownLatch(1);
final AtomicBoolean success = new AtomicBoolean(true);
Thread writerThread = new Thread(
new Runnable() {
@Override
public void run() {
try {
for (int i = 1; i < nTimes; i++) {
queue.put(i);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
});
writerThread.setName("ConcurrentBlockingObjectQueue<Integer>-writer");
Thread readerThread = new Thread(
new Runnable() {
@Override
public void run() {
int value = 0;
for (int i = 1; i < nTimes; i++) {
final int newValue;
try {
newValue = queue.take();
if (newValue != value + 1) {
success.set(false);
return;
}
value = newValue;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
countDown.countDown();
}
});
readerThread.setName("ConcurrentBlockingObjectQueue<Integer>-reader");
writerThread.start();
readerThread.start();
countDown.await();
writerThread.stop();
readerThread.stop();
}
private void testArrayBlockingQueue(final int nTimes) throws InterruptedException {
final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1024);
final CountDownLatch countDown = new CountDownLatch(1);
final AtomicBoolean success = new AtomicBoolean(true);
Thread writerThread = new Thread(
new Runnable() {
@Override
public void run() {
try {
for (int i = 1; i < nTimes; i++) {
queue.put(i);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
});
writerThread.setName("ArrayBlockingQueue-writer");
Thread readerThread = new Thread(
new Runnable() {
@Override
public void run() {
int value = 0;
for (int i = 1; i < nTimes; i++) {
final int newValue;
try {
newValue = queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
if (newValue != value + 1) {
success.set(false);
return;
}
value = newValue;
}
countDown.countDown();
}
});
readerThread.setName("ArrayBlockingQueue-reader");
writerThread.start();
readerThread.start();
countDown.await();
writerThread.stop();
readerThread.stop();
}
@Test
public void testLatency() throws NoSuchFieldException, InterruptedException {
for (int pwr = 2; pwr < 200; pwr++) {
int i = (int) Math.pow(2, pwr);
final long arrayBlockingQueueStart = System.nanoTime();
testArrayBlockingQueue(i);
final double arrayBlockingDuration = System.nanoTime() - arrayBlockingQueueStart;
final long queueStart = System.nanoTime();
testConcurrentBlockingObjectQueue(i);
final double concurrentBlockingDuration = System.nanoTime() - queueStart;
System.out.printf("Performing %,d loops, ArrayBlockingQueue() took %.3f ms and calling ConcurrentBlockingObjectQueue<Integer> took %.3f ms on average, ratio=%.1f%n",
i, arrayBlockingDuration / 1000000.0, concurrentBlockingDuration / 1000000.0, (double) arrayBlockingDuration / (double) concurrentBlockingDuration);
/**
System.out.printf("%d\t%.3f\t%.3f\n",
i, arrayBlockingDuration / 1000000.0, concurrentBlockingDuration / 1000000.0, (double) arrayBlockingDuration / (double) concurrentBlockingDuration);
**/
}
}
}
|
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.memorydb.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Represents the output of a CreateParameterGroup operation. A parameter group represents a combination of specific
* values for the parameters that are passed to the engine software during startup.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/memorydb-2021-01-01/ParameterGroup" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ParameterGroup implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The name of the parameter group
* </p>
*/
private String name;
/**
* <p>
* The name of the parameter group family that this parameter group is compatible with.
* </p>
*/
private String family;
/**
* <p>
* A description of the parameter group
* </p>
*/
private String description;
/**
* <p>
* The Amazon Resource Name (ARN) of the parameter group
* </p>
*/
private String aRN;
/**
* <p>
* The name of the parameter group
* </p>
*
* @param name
* The name of the parameter group
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the parameter group
* </p>
*
* @return The name of the parameter group
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the parameter group
* </p>
*
* @param name
* The name of the parameter group
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ParameterGroup withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The name of the parameter group family that this parameter group is compatible with.
* </p>
*
* @param family
* The name of the parameter group family that this parameter group is compatible with.
*/
public void setFamily(String family) {
this.family = family;
}
/**
* <p>
* The name of the parameter group family that this parameter group is compatible with.
* </p>
*
* @return The name of the parameter group family that this parameter group is compatible with.
*/
public String getFamily() {
return this.family;
}
/**
* <p>
* The name of the parameter group family that this parameter group is compatible with.
* </p>
*
* @param family
* The name of the parameter group family that this parameter group is compatible with.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ParameterGroup withFamily(String family) {
setFamily(family);
return this;
}
/**
* <p>
* A description of the parameter group
* </p>
*
* @param description
* A description of the parameter group
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* A description of the parameter group
* </p>
*
* @return A description of the parameter group
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* A description of the parameter group
* </p>
*
* @param description
* A description of the parameter group
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ParameterGroup withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the parameter group
* </p>
*
* @param aRN
* The Amazon Resource Name (ARN) of the parameter group
*/
public void setARN(String aRN) {
this.aRN = aRN;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the parameter group
* </p>
*
* @return The Amazon Resource Name (ARN) of the parameter group
*/
public String getARN() {
return this.aRN;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the parameter group
* </p>
*
* @param aRN
* The Amazon Resource Name (ARN) of the parameter group
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ParameterGroup withARN(String aRN) {
setARN(aRN);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getFamily() != null)
sb.append("Family: ").append(getFamily()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getARN() != null)
sb.append("ARN: ").append(getARN());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ParameterGroup == false)
return false;
ParameterGroup other = (ParameterGroup) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getFamily() == null ^ this.getFamily() == null)
return false;
if (other.getFamily() != null && other.getFamily().equals(this.getFamily()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getARN() == null ^ this.getARN() == null)
return false;
if (other.getARN() != null && other.getARN().equals(this.getARN()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getFamily() == null) ? 0 : getFamily().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getARN() == null) ? 0 : getARN().hashCode());
return hashCode;
}
@Override
public ParameterGroup clone() {
try {
return (ParameterGroup) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.memorydb.model.transform.ParameterGroupMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
|
package ch.rasc.s4ws.tennis;
import java.util.Calendar;
public class TennisMatch {
private final Player player1;
private final Player player2;
private int player1Points;
private int player2Points;
private final String key;
private String title;
private boolean isSet1Finished = false;
private boolean isSet2Finished = false;
private boolean isSet3Finished = false;
private String serve;
private boolean isFinished = false;
private String liveComments;
public Player getPlayer1() {
return this.player1;
}
public Player getPlayer2() {
return this.player2;
}
public TennisMatch(String key, String title, Player player1, Player player2) {
this.key = key;
this.title = title;
this.player1 = player1;
this.player2 = player2;
this.serve = player1.getName();
this.liveComments = "Welcome to this match between " + player1.getName() + " and "
+ player2.getName() + ".";
}
public String getKey() {
return this.key;
}
public synchronized void reset() {
this.player1.reset();
this.player2.reset();
this.isSet1Finished = this.isSet2Finished = this.isSet3Finished = this.isFinished = false;
this.liveComments = "WELCOME to this match between " + this.player1.getName()
+ " and " + this.player2.getName() + ".";
}
public String getPlayer1Score() {
if (hasAdvantage() && this.player1Points > this.player2Points) {
addLiveComments("Advantage " + playerWithHighestScore());
return "AD";
}
if (isDeuce()) {
addLiveComments("Deuce");
return "40";
}
return translateScore(this.player1Points);
}
public String getPlayer2Score() {
if (hasAdvantage() && this.player2Points > this.player1Points) {
addLiveComments("Advantage " + playerWithHighestScore());
return "AD";
}
if (isDeuce()) {
return "40";
}
return translateScore(this.player2Points);
}
private boolean isDeuce() {
return this.player1Points >= 3 && this.player2Points == this.player1Points;
}
private String playerWithHighestScore() {
if (this.player1Points > this.player2Points) {
return this.player1.getName();
}
return this.player2.getName();
}
private String playerWithHighestGames() {
if (this.player1.getGamesInCurrentSet() > this.player2.getGamesInCurrentSet()) {
return this.player1.getName();
}
return this.player2.getName();
}
public String playerWithHighestSets() {
if (this.player1.getSets() > this.player2.getSets()) {
return this.player1.getName();
}
return this.player2.getName();
}
public boolean hasMatchWinner() {
if (this.isSet1Finished && this.isSet2Finished && (this.isSet3Finished
|| this.player1.getSets() != this.player2.getSets())) {
return true;
}
return false;
}
public boolean hasGameWinner() {
boolean hasGameWinner = false;
if (this.player2Points >= 4 && this.player2Points >= this.player1Points + 2) {
this.player2.incGamesInCurrentSet();
hasGameWinner = true;
}
if (this.player1Points >= 4 && this.player1Points >= this.player2Points + 2) {
this.player1.incGamesInCurrentSet();
hasGameWinner = true;
}
if (hasGameWinner) {
addLiveComments("Game " + playerWithHighestScore());
this.player2Points = 0;
this.player1Points = 0;
if (this.player1.getName().equals(this.serve)) {
this.serve = this.player2.getName();
}
else {
this.serve = this.player1.getName();
}
}
return hasGameWinner;
}
public boolean hasSetWinner() {
if (this.player1.getGamesInCurrentSet() >= 6
&& (this.player1
.getGamesInCurrentSet() >= this.player2.getGamesInCurrentSet() + 2
|| this.player1.getGamesInCurrentSet()
+ this.player2.getGamesInCurrentSet() == 13)
|| this.player2.getGamesInCurrentSet() >= 6 && (this.player2
.getGamesInCurrentSet() >= this.player1.getGamesInCurrentSet() + 2
|| this.player1.getGamesInCurrentSet()
+ this.player2.getGamesInCurrentSet() == 13)) {
if (!this.isSet1Finished) {
this.isSet1Finished = true;
this.player1.setSet1(this.player1.getGamesInCurrentSet());
this.player2.setSet1(this.player2.getGamesInCurrentSet());
}
else if (!this.isSet2Finished) {
this.isSet2Finished = true;
this.player1.setSet2(this.player1.getGamesInCurrentSet());
this.player2.setSet2(this.player2.getGamesInCurrentSet());
}
else {
this.isSet3Finished = true;
this.player1.setSet3(this.player1.getGamesInCurrentSet());
this.player2.setSet3(this.player2.getGamesInCurrentSet());
}
addLiveComments(playerWithHighestGames() + " wins this set !!");
if (this.player1.getGamesInCurrentSet() > this.player2
.getGamesInCurrentSet()) {
this.player1.incSets();
}
else {
this.player2.incSets();
}
this.player1.setGamesInCurrentSet(0);
this.player2.setGamesInCurrentSet(0);
// check if match is finished
if (hasMatchWinner()) {
this.isFinished = true;
addLiveComments(playerWithHighestGames() + " WINS the match !!");
}
return true;
}
return false;
}
private boolean hasAdvantage() {
if (this.player2Points >= 4 && this.player2Points == this.player1Points + 1) {
return true;
}
if (this.player1Points >= 4 && this.player1Points == this.player2Points + 1) {
return true;
}
return false;
}
public void playerOneScores() {
this.liveComments = "";
this.player1Points++;
if (hasGameWinner()) {
hasSetWinner();
}
}
public void playerTwoScores() {
this.liveComments = "";
this.player2Points++;
if (hasGameWinner()) {
hasSetWinner();
}
}
private static String translateScore(int score) {
switch (score) {
case 3:
return "40";
case 2:
return "30";
case 1:
return "15";
case 0:
return "0";
default:
return "40";
}
}
public boolean isSet1Finished() {
return this.isSet1Finished;
}
public boolean isSet2Finished() {
return this.isSet2Finished;
}
public boolean isSet3Finished() {
return this.isSet3Finished;
}
public String getLiveComments() {
return this.liveComments;
}
public void addLiveComments(String comments) {
Calendar cal = Calendar.getInstance();
int H = cal.get(Calendar.HOUR);
int m = cal.get(Calendar.MINUTE);
int s = cal.get(Calendar.SECOND);
this.liveComments = "\n" + H + ":" + m + ":" + s + " - " + comments;
}
public String getServe() {
return this.serve;
}
public void setServe(String serve) {
this.serve = serve;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isFinished() {
return this.isFinished;
}
public void setFinished(boolean isFinished) {
this.isFinished = isFinished;
}
}
|
|
/*
* Copyright (C) 2016 Octavian Hasna
*
* 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 ro.hasna.commons.weka.io;
import ro.hasna.commons.weka.type.ValidationResult;
import ro.hasna.commons.weka.util.WekaUtils;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* A CSV writer for the results of the model validation.
*
* @since 0.3
*/
public class CsvValidationResultWriter implements ValidationResultWriter {
private final Writer writer;
private final char columnDelimiter;
private final String rowDelimiter;
private final NumberFormat numberFormat;
private final List<String> sharedMetadataKeys;
private final List<String> resultMetadataKeys;
private final boolean writeConfusionMatrix;
private CsvValidationResultWriter(Builder builder) {
writer = builder.writer;
columnDelimiter = builder.columnDelimiter;
rowDelimiter = builder.rowDelimiter;
numberFormat = builder.numberFormat;
sharedMetadataKeys = builder.sharedMetadataColumns;
resultMetadataKeys = builder.resultMetadataColumns;
writeConfusionMatrix = builder.writeConfusionMatrix;
}
@Override
public void write(List<ValidationResult> results, Map<String, Object> sharedMetadata) throws IOException {
StringBuilder prefix = new StringBuilder();
for (String key : sharedMetadataKeys) {
Object obj = sharedMetadata.get(key);
if (obj instanceof Number) {
prefix.append(numberFormat.format(obj));
} else {
prefix.append(obj);
}
prefix.append(columnDelimiter);
}
for (ValidationResult item : results) {
StringBuilder sb = new StringBuilder();
sb.append(prefix);
for (String key : resultMetadataKeys) {
Object obj = item.getMetadataValue(key);
if (obj instanceof Number) {
sb.append(numberFormat.format(obj));
} else {
sb.append(obj);
}
sb.append(columnDelimiter);
}
sb.append(item.getTrainingTime());
sb.append(columnDelimiter);
sb.append(item.getTestingTime());
sb.append(columnDelimiter);
double[][] confusionMatrix = item.getConfusionMatrix();
sb.append(numberFormat.format(WekaUtils.getIncorrectPercentage(confusionMatrix)));
sb.append(columnDelimiter);
if (writeConfusionMatrix) {
for (double[] row : confusionMatrix) {
for (double value : row) {
sb.append(numberFormat.format(value));
sb.append(columnDelimiter);
}
}
}
sb.deleteCharAt(sb.length() - 1);
sb.append(rowDelimiter);
writer.write(sb.toString());
}
}
@Override
public void flush() throws IOException {
writer.flush();
}
@Override
public void close() throws IOException {
writer.close();
}
public static class Builder {
private final Path outputPath;
private Writer writer;
private char columnDelimiter;
private String rowDelimiter;
private NumberFormat numberFormat;
private List<String> sharedMetadataColumns;
private List<String> resultMetadataColumns;
private boolean writeConfusionMatrix;
private int numClasses;
private boolean writeHeader;
private boolean appendToFile;
public Builder(Path outputPath) {
this.outputPath = outputPath;
// default values
columnDelimiter = ',';
rowDelimiter = "\n";
numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH);
sharedMetadataColumns = Collections.emptyList();
resultMetadataColumns = Collections.emptyList();
writeConfusionMatrix = false;
numClasses = 0;
writeHeader = true;
appendToFile = false;
}
/**
* Configure the CSV column delimiter.
* The default value is ','.
*
* @param delimiter the column delimiter
* @return a reference to this {@code CsvValidationResultWriter.Builder} object to fulfill the "Builder" pattern
*/
public Builder columnDelimiter(char delimiter) {
this.columnDelimiter = delimiter;
return this;
}
/**
* Configure the CSV row delimiter.
* The default value is "\n".
*
* @param delimiter the row delimiter
* @return a reference to this {@code CsvValidationResultWriter.Builder} object to fulfill the "Builder" pattern
*/
public Builder rowDelimiter(String delimiter) {
this.rowDelimiter = delimiter;
return this;
}
/**
* Configure the number format to use for writing the numbers.
* The default format is the one for English language.
*
* @param numberFormat the number format
* @return a reference to this {@code CsvValidationResultWriter.Builder} object to fulfill the "Builder" pattern
*/
public Builder numberFormat(NumberFormat numberFormat) {
this.numberFormat = numberFormat;
return this;
}
/**
* Configure the list of columns from the shared metadata that will be written to the CSV file.
*
* @param columns the keys from the shared metadata map
* @return a reference to this {@code CsvValidationResultWriter.Builder} object to fulfill the "Builder" pattern
*/
public Builder sharedMetadataColumns(List<String> columns) {
this.sharedMetadataColumns = columns;
return this;
}
/**
* Configure the list of columns from the result metadata that will be written to the CSV file.
*
* @param columns the keys from the result metadata map
* @return a reference to this {@code CsvValidationResultWriter.Builder} object to fulfill the "Builder" pattern
*/
public Builder resultMetadataColumns(List<String> columns) {
this.resultMetadataColumns = columns;
return this;
}
/**
* Configure the CSV writer to write the confusion matrix.
* The confusion matrix will be represented as a one dimensional array.
* The default value is false.
*
* @param writeConfusionMatrix a boolean for writing or not the confusion matrix.
* @return a reference to this {@code CsvValidationResultWriter.Builder} object to fulfill the "Builder" pattern
*/
public Builder writeConfusionMatrix(boolean writeConfusionMatrix) {
this.writeConfusionMatrix = writeConfusionMatrix;
return this;
}
/**
* Configure the number of classes from the validation result(s).
* This number must be provided if the CSV writer needs to write the header and the confusion matrix.
*
* @param numClasses the number of classes
* @return a reference to this {@code CsvValidationResultWriter.Builder} object to fulfill the "Builder" pattern
*/
public Builder numClasses(int numClasses) {
if (numClasses <= 0) {
throw new IllegalArgumentException("numClasses must be strictly positive");
}
this.numClasses = numClasses;
return this;
}
/**
* Configure the CSV writer to write the CSV header.
* The default value is true.
*
* @param writeHeaders a boolean for writing or not the header
* @return a reference to this {@code CsvValidationResultWriter.Builder} object to fulfill the "Builder" pattern
*/
public Builder writeHeader(boolean writeHeaders) {
this.writeHeader = writeHeaders;
return this;
}
/**
* Configure the CSv writer to append to the file.
* The default value is false which means it (re)creates the output file.
*
* @param appendToFile a boolean to append or not the output file
* @return a reference to this {@code CsvValidationResultWriter.Builder} object to fulfill the "Builder" pattern
*/
public Builder appendToFile(boolean appendToFile) {
this.appendToFile = appendToFile;
return this;
}
public CsvValidationResultWriter build() throws IOException {
if (!appendToFile) {
writer = Files.newBufferedWriter(outputPath, StandardCharsets.UTF_8);
} else {
writer = Files.newBufferedWriter(outputPath, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
}
if (writeHeader) {
if (writeConfusionMatrix && numClasses == 0) {
throw new IllegalArgumentException("numClasses must be provided if writeHeader and writeConfusionMatrix are true");
}
StringBuilder sb = new StringBuilder();
for (String key : sharedMetadataColumns) {
sb.append(key);
sb.append(columnDelimiter);
}
for (String key : resultMetadataColumns) {
sb.append(key);
sb.append(columnDelimiter);
}
sb.append("training_time");
sb.append(columnDelimiter);
sb.append("testing_time");
sb.append(columnDelimiter);
sb.append("classification_error");
sb.append(columnDelimiter);
if (writeConfusionMatrix) {
for (int i = 1; i <= numClasses; i++) {
for (int j = 1; j <= numClasses; j++) {
sb.append(i);
sb.append('_');
sb.append(j);
sb.append(columnDelimiter);
}
}
}
sb.deleteCharAt(sb.length() - 1);
sb.append(rowDelimiter);
writer.write(sb.toString());
}
return new CsvValidationResultWriter(this);
}
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.config;
import java.beans.IntrospectionException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.introspector.MissingProperty;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.introspector.PropertyUtils;
public class YamlConfigurationLoader implements ConfigurationLoader
{
private static final Logger logger = LoggerFactory.getLogger(YamlConfigurationLoader.class);
private final static String DEFAULT_CONFIGURATION = "cassandra.yaml";
/**
* Inspect the classpath to find storage configuration file
*/
static URL getStorageConfigURL() throws ConfigurationException
{
String configUrl = System.getProperty("cassandra.config");
if (configUrl == null)
configUrl = DEFAULT_CONFIGURATION;
URL url;
try
{
url = new URL(configUrl);
url.openStream().close(); // catches well-formed but bogus URLs
}
catch (Exception e)
{
ClassLoader loader = DatabaseDescriptor.class.getClassLoader();
url = loader.getResource(configUrl);
if (url == null)
{
String required = "file:" + File.separator + File.separator;
if (!configUrl.startsWith(required))
throw new ConfigurationException(String.format(
"Expecting URI in variable: [cassandra.config]. Found[%s]. Please prefix the file with [%s%s] for local " +
"files and [%s<server>%s] for remote files. If you are executing this from an external tool, it needs " +
"to set Config.setClientMode(true) to avoid loading configuration.",
configUrl, required, File.separator, required, File.separator));
throw new ConfigurationException("Cannot locate " + configUrl + ". If this is a local file, please confirm you've provided " + required + File.separator + " as a URI prefix.");
}
}
return url;
}
@Override
public Config loadConfig() throws ConfigurationException
{
return loadConfig(getStorageConfigURL());
}
public Config loadConfig(URL url) throws ConfigurationException
{
try
{
logger.info("Loading settings from {}", url);
byte[] configBytes;
try (InputStream is = url.openStream())
{
configBytes = ByteStreams.toByteArray(is);
}
catch (IOException e)
{
// getStorageConfigURL should have ruled this out
throw new AssertionError(e);
}
logConfig(configBytes);
Constructor constructor = new CustomConstructor(Config.class);
MissingPropertiesChecker propertiesChecker = new MissingPropertiesChecker();
constructor.setPropertyUtils(propertiesChecker);
Yaml yaml = new Yaml(constructor);
Config result = yaml.loadAs(new ByteArrayInputStream(configBytes), Config.class);
propertiesChecker.check();
return result;
}
catch (YAMLException e)
{
throw new ConfigurationException("Invalid yaml: " + url, e);
}
}
static class CustomConstructor extends Constructor
{
CustomConstructor(Class<?> theRoot)
{
super(theRoot);
TypeDescription seedDesc = new TypeDescription(ParameterizedClass.class);
seedDesc.putMapPropertyType("parameters", String.class, String.class);
addTypeDescription(seedDesc);
}
@Override
protected List<Object> createDefaultList(int initSize)
{
return Lists.newCopyOnWriteArrayList();
}
@Override
protected Map<Object, Object> createDefaultMap()
{
return Maps.newConcurrentMap();
}
@Override
protected Set<Object> createDefaultSet(int initSize)
{
return Sets.newConcurrentHashSet();
}
@Override
protected Set<Object> createDefaultSet()
{
return Sets.newConcurrentHashSet();
}
}
private void logConfig(byte[] configBytes)
{
Map<Object, Object> configMap = new TreeMap<>((Map<?, ?>) new Yaml().load(new ByteArrayInputStream(configBytes)));
// these keys contain passwords, don't log them
for (String sensitiveKey : new String[] { "client_encryption_options", "server_encryption_options" })
{
if (configMap.containsKey(sensitiveKey))
{
configMap.put(sensitiveKey, "<REDACTED>");
}
}
logger.info("Node configuration:[{}]", Joiner.on("; ").join(configMap.entrySet()));
}
private static class MissingPropertiesChecker extends PropertyUtils
{
private final Set<String> missingProperties = new HashSet<>();
public MissingPropertiesChecker()
{
setSkipMissingProperties(true);
}
@Override
public Property getProperty(Class<? extends Object> type, String name) throws IntrospectionException
{
Property result = super.getProperty(type, name);
if (result instanceof MissingProperty)
{
missingProperties.add(result.getName());
}
return result;
}
public void check() throws ConfigurationException
{
if (!missingProperties.isEmpty())
{
throw new ConfigurationException("Invalid yaml. Please remove properties " + missingProperties + " from your cassandra.yaml");
}
}
}
}
|
|
package org.bouncycastle.math.ec.custom.sec;
import java.math.BigInteger;
import org.bouncycastle.math.raw.Interleave;
import org.bouncycastle.math.raw.Nat;
import org.bouncycastle.math.raw.Nat576;
public class SecT571Field
{
private static final long M59 = -1L >>> 5;
private static final long RM = 0xEF7BDEF7BDEF7BDEL;
private static final long[] ROOT_Z = new long[]{ 0x2BE1195F08CAFB99L, 0x95F08CAF84657C23L, 0xCAF84657C232BE11L, 0x657C232BE1195F08L,
0xF84657C2308CAF84L, 0x7C232BE1195F08CAL, 0xBE1195F08CAF8465L, 0x5F08CAF84657C232L, 0x784657C232BE119L };
public static void add(long[] x, long[] y, long[] z)
{
for (int i = 0; i < 9; ++i)
{
z[i] = x[i] ^ y[i];
}
}
private static void add(long[] x, int xOff, long[] y, int yOff, long[] z, int zOff)
{
for (int i = 0; i < 9; ++i)
{
z[zOff + i] = x[xOff + i] ^ y[yOff + i];
}
}
private static void addBothTo(long[] x, int xOff, long[] y, int yOff, long[] z, int zOff)
{
for (int i = 0; i < 9; ++i)
{
z[zOff + i] ^= x[xOff + i] ^ y[yOff + i];
}
}
public static void addExt(long[] xx, long[] yy, long[] zz)
{
for (int i = 0; i < 18; ++i)
{
zz[i] = xx[i] ^ yy[i];
}
}
public static void addOne(long[] x, long[] z)
{
z[0] = x[0] ^ 1L;
for (int i = 1; i < 9; ++i)
{
z[i] = x[i];
}
}
public static long[] fromBigInteger(BigInteger x)
{
long[] z = Nat576.fromBigInteger64(x);
reduce5(z, 0);
return z;
}
public static void invert(long[] x, long[] z)
{
if (Nat576.isZero64(x))
{
throw new IllegalStateException();
}
// Itoh-Tsujii inversion with bases { 2, 3, 5 }
long[] t0 = Nat576.create64();
long[] t1 = Nat576.create64();
long[] t2 = Nat576.create64();
square(x, t2);
// 5 | 570
square(t2, t0);
square(t0, t1);
multiply(t0, t1, t0);
squareN(t0, 2, t1);
multiply(t0, t1, t0);
multiply(t0, t2, t0);
// 3 | 114
squareN(t0, 5, t1);
multiply(t0, t1, t0);
squareN(t1, 5, t1);
multiply(t0, t1, t0);
// 2 | 38
squareN(t0, 15, t1);
multiply(t0, t1, t2);
// ! {2,3,5} | 19
squareN(t2, 30, t0);
squareN(t0, 30, t1);
multiply(t0, t1, t0);
// 3 | 9
squareN(t0, 60, t1);
multiply(t0, t1, t0);
squareN(t1, 60, t1);
multiply(t0, t1, t0);
// 3 | 3
squareN(t0, 180, t1);
multiply(t0, t1, t0);
squareN(t1, 180, t1);
multiply(t0, t1, t0);
multiply(t0, t2, z);
}
public static void multiply(long[] x, long[] y, long[] z)
{
long[] tt = Nat576.createExt64();
implMultiply(x, y, tt);
reduce(tt, z);
}
public static void multiplyAddToExt(long[] x, long[] y, long[] zz)
{
long[] tt = Nat576.createExt64();
implMultiply(x, y, tt);
addExt(zz, tt, zz);
}
public static void reduce(long[] xx, long[] z)
{
long xx09 = xx[9];
long u = xx[17], v = xx09;
xx09 = v ^ (u >>> 59) ^ (u >>> 57) ^ (u >>> 54) ^ (u >>> 49);
v = xx[8] ^ (u << 5) ^ (u << 7) ^ (u << 10) ^ (u << 15);
for (int i = 16; i >= 10; --i)
{
u = xx[i];
z[i - 8] = v ^ (u >>> 59) ^ (u >>> 57) ^ (u >>> 54) ^ (u >>> 49);
v = xx[i - 9] ^ (u << 5) ^ (u << 7) ^ (u << 10) ^ (u << 15);
}
u = xx09;
z[1] = v ^ (u >>> 59) ^ (u >>> 57) ^ (u >>> 54) ^ (u >>> 49);
v = xx[0] ^ (u << 5) ^ (u << 7) ^ (u << 10) ^ (u << 15);
long x08 = z[8];
long t = x08 >>> 59;
z[0] = v ^ t ^ (t << 2) ^ (t << 5) ^ (t << 10);
z[8] = x08 & M59;
}
public static void reduce5(long[] z, int zOff)
{
long z8 = z[zOff + 8], t = z8 >>> 59;
z[zOff ] ^= t ^ (t << 2) ^ (t << 5) ^ (t << 10);
z[zOff + 8] = z8 & M59;
}
public static void sqrt(long[] x, long[] z)
{
long[] evn = Nat576.create64(), odd = Nat576.create64();
int pos = 0;
for (int i = 0; i < 4; ++i)
{
long u0 = Interleave.unshuffle(x[pos++]);
long u1 = Interleave.unshuffle(x[pos++]);
evn[i] = (u0 & 0x00000000FFFFFFFFL) | (u1 << 32);
odd[i] = (u0 >>> 32) | (u1 & 0xFFFFFFFF00000000L);
}
{
long u0 = Interleave.unshuffle(x[pos]);
evn[4] = (u0 & 0x00000000FFFFFFFFL);
odd[4] = (u0 >>> 32);
}
multiply(odd, ROOT_Z, z);
add(z, evn, z);
}
public static void square(long[] x, long[] z)
{
long[] tt = Nat576.createExt64();
implSquare(x, tt);
reduce(tt, z);
}
public static void squareAddToExt(long[] x, long[] zz)
{
long[] tt = Nat576.createExt64();
implSquare(x, tt);
addExt(zz, tt, zz);
}
public static void squareN(long[] x, int n, long[] z)
{
// assert n > 0;
long[] tt = Nat576.createExt64();
implSquare(x, tt);
reduce(tt, z);
while (--n > 0)
{
implSquare(z, tt);
reduce(tt, z);
}
}
public static int trace(long[] x)
{
// Non-zero-trace bits: 0, 561, 569
return (int)(x[0] ^ (x[8] >>> 49) ^ (x[8] >>> 57)) & 1;
}
protected static void implMultiply(long[] x, long[] y, long[] zz)
{
// for (int i = 0; i < 9; ++i)
// {
// implMulwAcc(x, y[i], zz, i);
// }
/*
* Precompute table of all 4-bit products of y
*/
long[] T0 = new long[9 << 4];
System.arraycopy(y, 0, T0, 9, 9);
// reduce5(T0, 9);
int tOff = 0;
for (int i = 7; i > 0; --i)
{
tOff += 18;
Nat.shiftUpBit64(9, T0, tOff >>> 1, 0L, T0, tOff);
reduce5(T0, tOff);
add(T0, 9, T0, tOff, T0, tOff + 9);
}
/*
* Second table with all 4-bit products of B shifted 4 bits
*/
long[] T1 = new long[T0.length];
Nat.shiftUpBits64(T0.length, T0, 0, 4, 0L, T1, 0);
int MASK = 0xF;
/*
* Lopez-Dahab algorithm
*/
for (int k = 56; k >= 0; k -= 8)
{
for (int j = 1; j < 9; j += 2)
{
int aVal = (int)(x[j] >>> k);
int u = aVal & MASK;
int v = (aVal >>> 4) & MASK;
addBothTo(T0, 9 * u, T1, 9 * v, zz, j - 1);
}
Nat.shiftUpBits64(16, zz, 0, 8, 0L);
}
for (int k = 56; k >= 0; k -= 8)
{
for (int j = 0; j < 9; j += 2)
{
int aVal = (int)(x[j] >>> k);
int u = aVal & MASK;
int v = (aVal >>> 4) & MASK;
addBothTo(T0, 9 * u, T1, 9 * v, zz, j);
}
if (k > 0)
{
Nat.shiftUpBits64(18, zz, 0, 8, 0L);
}
}
}
protected static void implMulwAcc(long[] xs, long y, long[] z, int zOff)
{
long[] u = new long[32];
// u[0] = 0;
u[1] = y;
for (int i = 2; i < 32; i += 2)
{
u[i ] = u[i >>> 1] << 1;
u[i + 1] = u[i ] ^ y;
}
long l = 0;
for (int i = 0; i < 9; ++i)
{
long x = xs[i];
int j = (int)x;
l ^= u[j & 31];
long g, h = 0;
int k = 60;
do
{
j = (int)(x >>> k);
g = u[j & 31];
l ^= (g << k);
h ^= (g >>> -k);
}
while ((k -= 5) > 0);
for (int p = 0; p < 4; ++p)
{
x = (x & RM) >>> 1;
h ^= x & ((y << p) >> 63);
}
z[zOff + i] ^= l;
l = h;
}
z[zOff + 9] ^= l;
}
protected static void implSquare(long[] x, long[] zz)
{
for (int i = 0; i < 9; ++i)
{
Interleave.expand64To128(x[i], zz, i << 1);
}
}
}
|
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.siddhi.extension.table.rdbms;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.wso2.siddhi.core.ExecutionPlanRuntime;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.query.output.callback.QueryCallback;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.util.EventPrinter;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
public class UpdateFromRDBMSTestCase {
private static final Logger log = Logger.getLogger(UpdateFromRDBMSTestCase.class);
private DataSource dataSource = new BasicDataSource();
private int inEventCount;
private int removeEventCount;
private boolean eventArrived;
@Before
public void init() {
inEventCount = 0;
removeEventCount = 0;
eventArrived = false;
}
@Test
public void updateFromRDBMSTableTest1() throws InterruptedException {
log.info("updateFromTableTest1");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource);
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource, RDBMSTestConstants
.TABLE_NAME);
String streams = "" +
"define stream StockStream (symbol string, price float, volume long); " +
"define stream UpdateStockStream (symbol string, price float, volume long); " +
"@store(type = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' " +
", table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " +
"define table StockTable (symbol string, price float, volume long); ";
String query = "" +
"@info(name = 'query1') " +
"from StockStream " +
"insert into StockTable ;" +
"" +
"@info(name = 'query2') " +
"from UpdateStockStream " +
"update StockTable " +
" on StockTable.symbol == symbol ;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream");
InputHandler updateStockStream = executionPlanRuntime.getInputHandler("UpdateStockStream");
executionPlanRuntime.start();
stockStream.send(new Object[]{"WSO2", 55.6f, 100l});
stockStream.send(new Object[]{"IBM", 75.6f, 100l});
stockStream.send(new Object[]{"WSO2", 57.6f, 100l});
updateStockStream.send(new Object[]{"IBM", 57.6f, 100l});
Thread.sleep(1000);
long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource);
Assert.assertEquals("Update failed", 3, totalRowsInTable);
executionPlanRuntime.shutdown();
}
} catch (SQLException e) {
log.info("Test case ignored due to DB connection unavailability");
}
}
@Test
public void updateFromRDBMSTableTest2() throws InterruptedException {
log.info("updateFromTableTest2");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource);
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource, RDBMSTestConstants
.TABLE_NAME);
String streams = "" +
"define stream StockStream (symbol string, price float, volume long); " +
"define stream UpdateStockStream (symbol string, price float, volume long); " +
"@store(type = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' " +
", table.name = '" + RDBMSTestConstants.TABLE_NAME + "', cache='lru', cache.size='1000') " +
"define table StockTable (symbol string, price float, volume long); ";
String query = "" +
"@info(name = 'query1') " +
"from StockStream " +
"insert into StockTable ;" +
"" +
"@info(name = 'query2') " +
"from UpdateStockStream " +
"update StockTable " +
" on StockTable.symbol == symbol ;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream");
InputHandler updateStockStream = executionPlanRuntime.getInputHandler("UpdateStockStream");
executionPlanRuntime.start();
stockStream.send(new Object[]{"WSO2", 55.6f, 100l});
stockStream.send(new Object[]{"IBM", 75.6f, 100l});
stockStream.send(new Object[]{"WSO2", 57.6f, 100l});
updateStockStream.send(new Object[]{"IBM", 57.6f, 100l});
Thread.sleep(1000);
long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource);
Assert.assertEquals("Update failed", 3, totalRowsInTable);
executionPlanRuntime.shutdown();
}
} catch (SQLException e) {
log.info("Test case ignored due to DB connection unavailability");
}
}
@Test
public void updateFromTableTest3() throws InterruptedException {
log.info("updateFromTableTest3");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource);
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource, RDBMSTestConstants
.TABLE_NAME);
String streams = "" +
"define stream StockStream (symbol string, price float, volume long); " +
"define stream CheckStockStream (symbol string, volume long); " +
"@store(type = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' " +
", table.name = '" + RDBMSTestConstants.TABLE_NAME + "', cache='lru', cache.size='1000') " +
"define table StockTable (symbol string, price float, volume long); ";
String query = "" +
"@info(name = 'query1') " +
"from StockStream " +
"insert into StockTable ;" +
"" +
"@info(name = 'query2') " +
"from CheckStockStream[(StockTable.symbol==symbol) in StockTable] " +
"insert into OutStream;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
executionPlanRuntime.addCallback("query2", new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
if (inEvents != null) {
for (Event event : inEvents) {
inEventCount++;
}
eventArrived = true;
}
}
});
InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream");
InputHandler checkStockStream = executionPlanRuntime.getInputHandler("CheckStockStream");
executionPlanRuntime.start();
stockStream.send(new Object[]{"WSO2", 55.6f, 100l});
stockStream.send(new Object[]{"IBM", 55.6f, 100l});
checkStockStream.send(new Object[]{"IBM", 100l});
checkStockStream.send(new Object[]{"WSO2", 100l});
checkStockStream.send(new Object[]{"IBM", 100l});
Thread.sleep(1000);
Assert.assertEquals("Number of success events", 3, inEventCount);
Assert.assertEquals("Event arrived", true, eventArrived);
executionPlanRuntime.shutdown();
}
} catch (SQLException e) {
log.info("Test case ignored due to DB connection unavailability");
}
}
@Test
public void updateFromTableTest4() throws InterruptedException {
log.info("updateFromTableTest4");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource);
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource, RDBMSTestConstants
.TABLE_NAME);
String streams = "" +
"define stream StockStream (symbol string, price float, volume long); " +
"define stream CheckStockStream (symbol string, volume long); " +
"@store(type = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' " +
", table.name = '" + RDBMSTestConstants.TABLE_NAME + "' , bloom.filters = 'enable') " +
"define table StockTable (symbol string, price float, volume long); ";
String query = "" +
"@info(name = 'query1') " +
"from StockStream " +
"insert into StockTable ;" +
"" +
"@info(name = 'query2') " +
"from CheckStockStream[(StockTable.symbol==symbol) in StockTable] " +
"insert into OutStream;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
executionPlanRuntime.addCallback("query2", new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
if (inEvents != null) {
for (Event event : inEvents) {
inEventCount++;
}
eventArrived = true;
}
}
});
InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream");
InputHandler checkStockStream = executionPlanRuntime.getInputHandler("CheckStockStream");
executionPlanRuntime.start();
stockStream.send(new Object[]{"WSO2", 55.6f, 100l});
stockStream.send(new Object[]{"IBM", 55.6f, 100l});
checkStockStream.send(new Object[]{"IBM", 100l});
checkStockStream.send(new Object[]{"WSO2", 100l});
checkStockStream.send(new Object[]{"IBM", 100l});
Thread.sleep(1000);
Assert.assertEquals("Number of success events", 3, inEventCount);
Assert.assertEquals("Event arrived", true, eventArrived);
executionPlanRuntime.shutdown();
}
} catch (SQLException e) {
log.info("Test case ignored due to DB connection unavailability");
}
}
@Test
public void updateFromTableTest5() throws InterruptedException {
log.info("updateFromTableTest5");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource);
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource, RDBMSTestConstants
.TABLE_NAME);
String streams = "" +
"define stream StockStream (symbol string, price float, volume long); " +
"define stream CheckStockStream (symbol string, volume long); " +
"@store(type = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' " +
", table.name = '" + RDBMSTestConstants.TABLE_NAME + "' , bloom.filters = 'enable') " +
"define table StockTable (symbol string, price float, volume long); ";
String query = "" +
"@info(name = 'query1') " +
"from StockStream " +
"insert into StockTable ;" +
"" +
"@info(name = 'query2') " +
"from CheckStockStream[(StockTable.symbol==symbol) in StockTable] " +
"insert into OutStream;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
executionPlanRuntime.addCallback("query2", new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
if (inEvents != null) {
for (Event event : inEvents) {
inEventCount++;
}
eventArrived = true;
}
}
});
InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream");
InputHandler checkStockStream = executionPlanRuntime.getInputHandler("CheckStockStream");
executionPlanRuntime.start();
stockStream.send(new Object[]{"WSO2", 55.6f, 100l});
stockStream.send(new Object[]{"IBM", 55.6f, 100l});
checkStockStream.send(new Object[]{"BSD", 100l});
checkStockStream.send(new Object[]{"WSO2", 100l});
checkStockStream.send(new Object[]{"IBM", 100l});
Thread.sleep(1000);
Assert.assertEquals("Number of success events", 2, inEventCount);
Assert.assertEquals("Event arrived", true, eventArrived);
executionPlanRuntime.shutdown();
}
} catch (SQLException e) {
log.info("Test case ignored due to DB connection unavailability");
}
}
@Test
public void updateFromTableTest6() throws InterruptedException {
log.info("updateFromTableTest6");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource);
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource, RDBMSTestConstants
.TABLE_NAME);
String streams = "" +
"define stream StockStream (symbol string, price float, volume long); " +
"define stream CheckStockStream (symbol string, volume long); " +
"@store(type = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' " +
", table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " +
"define table StockTable (symbol string, price float, volume long); ";
String query = "" +
"@info(name = 'query1') " +
"from StockStream " +
"insert into StockTable ;" +
"" +
"@info(name = 'query2') " +
"from CheckStockStream[(StockTable.symbol==symbol) in StockTable] " +
"insert into OutStream;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
executionPlanRuntime.addCallback("query2", new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
if (inEvents != null) {
for (Event event : inEvents) {
inEventCount++;
}
eventArrived = true;
}
}
});
InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream");
InputHandler checkStockStream = executionPlanRuntime.getInputHandler("CheckStockStream");
executionPlanRuntime.start();
stockStream.send(new Object[]{"WSO2", 55.6f, 100l});
stockStream.send(new Object[]{"IBM", 55.6f, 100l});
checkStockStream.send(new Object[]{"IBM", 100l});
checkStockStream.send(new Object[]{"WSO2", 100l});
checkStockStream.send(new Object[]{"IBM", 100l});
Thread.sleep(1000);
Assert.assertEquals("Number of success events", 3, inEventCount);
Assert.assertEquals("Event arrived", true, eventArrived);
executionPlanRuntime.shutdown();
}
} catch (SQLException e) {
log.info("Test case ignored due to DB connection unavailability");
}
}
@Test
public void updateFromTableTest7() throws InterruptedException {
log.info("updateFromTableTest7");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource);
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource, RDBMSTestConstants
.TABLE_NAME);
String streams = "" +
"define stream StockStream (symbol string, price float, volume long); " +
"define stream CheckStockStream (symbol string, price float, volume long); " +
"define stream UpdateStockStream (comp string, prc float); " +
"@store(type = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' " +
", table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " +
"define table StockTable (symbol string, price float, volume long); ";
String query = "" +
"@info(name = 'query1') " +
"from StockStream " +
"insert into StockTable ;" +
"" +
"@info(name = 'query2') " +
"from UpdateStockStream " +
"select comp as symbol, prc as price " +
"update StockTable " +
" on StockTable.symbol==symbol;" +
"" +
"@info(name = 'query3') " +
"from CheckStockStream[(symbol==StockTable.symbol and volume==StockTable.volume and " +
"price<StockTable.price) in StockTable] " +
"insert into OutStream;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
executionPlanRuntime.addCallback("query3", new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
if (inEvents != null) {
for (Event event : inEvents) {
inEventCount++;
switch (inEventCount) {
case 1:
Assert.assertArrayEquals(new Object[]{"IBM", 150.6f, 100l}, event.getData());
break;
case 2:
Assert.assertArrayEquals(new Object[]{"IBM", 190.6f, 100l}, event.getData());
break;
default:
Assert.assertSame(2, inEventCount);
}
}
eventArrived = true;
}
if (removeEvents != null) {
removeEventCount = removeEventCount + removeEvents.length;
}
eventArrived = true;
}
});
InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream");
InputHandler checkStockStream = executionPlanRuntime.getInputHandler("CheckStockStream");
InputHandler updateStockStream = executionPlanRuntime.getInputHandler("UpdateStockStream");
executionPlanRuntime.start();
stockStream.send(new Object[]{"WSO2", 55.6f, 100l});
stockStream.send(new Object[]{"IBM", 185.6f, 100l});
checkStockStream.send(new Object[]{"IBM", 150.6f, 100l});
checkStockStream.send(new Object[]{"WSO2", 175.6f, 100l});
updateStockStream.send(new Object[]{"IBM", 200f});
checkStockStream.send(new Object[]{"IBM", 190.6f, 100l});
checkStockStream.send(new Object[]{"WSO2", 155.6f, 100l});
Thread.sleep(2000);
Assert.assertEquals("Number of success events", 2, inEventCount);
Assert.assertEquals("Number of remove events", 0, removeEventCount);
Assert.assertEquals("Event arrived", true, eventArrived);
executionPlanRuntime.shutdown();
}
} catch (SQLException e) {
log.info("Test case ignored due to DB connection unavailability");
}
}
@Test
public void updateFromRDBMSTableTest3() throws InterruptedException {
log.info("updateFromRDBMSTableTest3");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource);
try {
if (dataSource.getConnection() != null) {
DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource, RDBMSTestConstants
.TABLE_NAME);
String streams = "" +
"define stream StockStream (symbol string, price float, volume long); " +
"define stream UpdateStockStream (symbol string, price float, volume long); " +
"@store(type = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' " +
", table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " +
"define table StockTable (symbol string, price float, volume long); ";
String query = "" +
"@info(name = 'query1') " +
"from StockStream " +
"insert into StockTable ;" +
"" +
"@info(name = 'query2') " +
"from UpdateStockStream " +
"update StockTable " +
" on StockTable.volume == volume ;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream");
InputHandler updateStockStream = executionPlanRuntime.getInputHandler("UpdateStockStream");
executionPlanRuntime.start();
stockStream.send(new Object[]{"WSO2", 55.6f, 100l});
stockStream.send(new Object[]{"IBM", 75.6f, 100l});
stockStream.send(new Object[]{"WSO2", 57.6f, 100l});
updateStockStream.send(new Object[]{"IBM", 57.6f, 100l});
Thread.sleep(1000);
long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource);
Assert.assertEquals("Update failed", 3, totalRowsInTable);
executionPlanRuntime.shutdown();
}
} catch (SQLException e) {
log.info("Test case ignored due to DB connection unavailability");
}
}
@Test
public void updateFromRDBMSTableTest4() throws InterruptedException {
log.info("updateFromRDBMSTableTest4");
SiddhiManager siddhiManager = new SiddhiManager();
siddhiManager.setDataSource(RDBMSTestConstants.DATA_SOURCE_NAME, dataSource);
try {
if (dataSource.getConnection() != null) {
DBConnectionHelper.getDBConnectionHelperInstance().clearDatabaseTable(dataSource, RDBMSTestConstants
.TABLE_NAME);
String streams = "" +
"define stream StockStream (symbol string, price float, volume long); " +
"define stream UpdateStockStream (symbol string, price float, volume long); " +
"@store(type = 'rdbms' ,datasource.name = '" + RDBMSTestConstants.DATA_SOURCE_NAME + "' " +
", table.name = '" + RDBMSTestConstants.TABLE_NAME + "') " +
"define table StockTable (symbol string, price float, volume long); ";
String query = "" +
"@info(name = 'query1') " +
"from StockStream " +
"insert into StockTable ;" +
"" +
"@info(name = 'query2') " +
"from UpdateStockStream " +
"update StockTable " +
" on StockTable.volume == 100 ;";
ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
InputHandler stockStream = executionPlanRuntime.getInputHandler("StockStream");
InputHandler updateStockStream = executionPlanRuntime.getInputHandler("UpdateStockStream");
executionPlanRuntime.start();
stockStream.send(new Object[]{"WSO2", 55.6f, 100l});
stockStream.send(new Object[]{"IBM", 75.6f, 100l});
stockStream.send(new Object[]{"WSO2", 57.6f, 100l});
updateStockStream.send(new Object[]{"IBM", 57.6f, 100l});
Thread.sleep(1000);
long totalRowsInTable = DBConnectionHelper.getDBConnectionHelperInstance().getRowsInTable(dataSource);
Assert.assertEquals("Update failed", 3, totalRowsInTable);
executionPlanRuntime.shutdown();
}
} catch (SQLException e) {
log.info("Test case ignored due to DB connection unavailability");
}
}
}
|
|
package com.algorelpublic.zambia.activities;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import com.algorelpublic.zambia.R;
import com.algorelpublic.zambia.Shimmer.Shimmer;
import com.algorelpublic.zambia.Shimmer.ShimmerRadioButton;
import com.algorelpublic.zambia.Zambia;
import com.algorelpublic.zambia.fragments.AboutUsFragment;
import com.algorelpublic.zambia.fragments.AdvanceSearchFragment;
import com.algorelpublic.zambia.fragments.ContactUsFragment;
import com.algorelpublic.zambia.fragments.FavouriteFragment;
import com.algorelpublic.zambia.fragments.GuidelinesFragment;
import com.algorelpublic.zambia.fragments.HelpLineFragment;
import com.algorelpublic.zambia.fragments.MedicineFragment;
import com.algorelpublic.zambia.fragments.SearchResultFragment;
import com.algorelpublic.zambia.fragments.ToolsFragment;
import com.algorelpublic.zambia.utils.Constants;
public class ZambiaMain extends BaseActivity implements View.OnClickListener {
private Toolbar toolbar;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
public static CheckBox favouriteCheckBox;
public static AppCompatActivity activity;
private ShimmerRadioButton advance_search, guideline, medicines,
about, tools, add_favorite, helpline, contact_us, share, sync;
private ShimmerRadioButton[] radioButtons = {advance_search, guideline, medicines,
about, tools, add_favorite, helpline, contact_us, share, sync};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zambia_main);
setToolbar();
activity = ZambiaMain.this;
}
public void setToolbar() {
favouriteCheckBox = (CheckBox) findViewById(R.id.group_chk_box);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitleTextColor(Color.BLACK);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Consolidated Guidelines</font>"));
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
toolbar.setNavigationIcon(R.drawable.ic_view_headline_black_24dp);
drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
@Override
public void onDrawerOpened(View v) {
}
@Override
public void onDrawerClosed(View drawerView) {
}
@Override
public void onDrawerStateChanged(int newState) {
}
});
setItems();
}
private void setItems() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View view = navigationView.getHeaderView(0);
radioButtons[0] = (ShimmerRadioButton) view.findViewById(R.id.advance_search);
radioButtons[1] = (ShimmerRadioButton) view.findViewById(R.id.guideline);
radioButtons[2] = (ShimmerRadioButton) view.findViewById(R.id.about);
radioButtons[3] = (ShimmerRadioButton) view.findViewById(R.id.tools);
radioButtons[4] = (ShimmerRadioButton) view.findViewById(R.id.add_favorite);
radioButtons[5] = (ShimmerRadioButton) view.findViewById(R.id.medicines);
radioButtons[6] = (ShimmerRadioButton) view.findViewById(R.id.helpline);
radioButtons[7] = (ShimmerRadioButton) view.findViewById(R.id.contact_us);
radioButtons[8] = (ShimmerRadioButton) view.findViewById(R.id.share);
radioButtons[9] = (ShimmerRadioButton) view.findViewById(R.id.sync);
for (int loop = 0; loop < radioButtons.length; loop++) {
radioButtons[loop].setOnClickListener(this);
}
Shimmer shimmer = new Shimmer();
shimmer.start(radioButtons[0]);
radioButtons[0].setShimmering(true);
callFragmentWithReplace(R.id.container, GuidelinesFragment.newInstance(), null);
}
private void clearBackStack() {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
private void shareIntent() {
String message = getString(R.string.app_name);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(share, getString(R.string.app_name)));
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
@Override
public void onBackPressed() {
final SearchResultFragment fragment = (SearchResultFragment) getSupportFragmentManager().findFragmentByTag("SearchResultFragment");
if (fragment != null) {
fragment.allowBackPressed();
} else {
super.onBackPressed();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.medicines:
resetMenu(v);
callFragmentWithReplace(R.id.container, MedicineFragment.newInstance(), null);
break;
case R.id.guideline:
resetMenu(v);
callFragmentWithReplace(R.id.container, GuidelinesFragment.newInstance(), null);
break;
case R.id.advance_search:
resetMenu(v);
callFragmentWithReplace(R.id.container, AdvanceSearchFragment.newInstance(), null);
break;
case R.id.tools:
resetMenu(v);
callFragmentWithReplace(R.id.container, ToolsFragment.newInstance(), null);
break;
case R.id.add_favorite:
resetMenu(v);
callFragmentWithReplace(R.id.container, FavouriteFragment.newInstance(), null);
break;
case R.id.helpline:
resetMenu(v);
callFragmentWithReplace(R.id.container, HelpLineFragment.newInstance(), null);
break;
case R.id.contact_us:
resetMenu(v);
callFragmentWithReplace(R.id.container, ContactUsFragment.newInstance(), null);
break;
case R.id.about:
resetMenu(v);
callFragmentWithReplace(R.id.container, AboutUsFragment.newInstance(), null);
break;
case R.id.share:
resetMenu(v);
shareIntent();
break;
case R.id.sync:
resetMenu(v);
Zambia.db.putInt(Constants.PROGRESS_LOAD_APP, 0);
showDialog();
apiHandler.postDelayed(loadAboutUs, API_TIME);
break;
}
drawer.closeDrawers();
}
private void resetMenu(View v) {
for (int loop = 0; loop < radioButtons.length; loop++) {
radioButtons[loop].setChecked(false);
}
((RadioButton) v).setChecked(true);
}
}
|
|
/*
*
* Copyright 2012-2015 The MITRE Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.opensextant.extractors.xcoord;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.opensextant.util.TextUtils;
/**
* MGRS Filters include ignoring these patterns:
* <ul>
* <li>1234</li>
* <li>123456</li>
* <li>12345678</li>
* <li>1234567890
* </li>
* <li>Recent calendar dates of the form ddMMMyyyy, "14DEC1990" (MGRS:
* 14D EC 19 90</li>
* <li>Recent calendar dates with time, ddMMHHmm,
* "14DEC1200" Noon on 14DEC.</li>
* <li></li>
* </ul>
*
* @author ubaldino
*/
public class MGRSFilter implements GeocoordMatchFilter {
/**
* DateFormat used to check for dates that look like MGRS i.e. ddMMMyyyy
*/
public List<DateFormat> df = new ArrayList<>();
/** The today. */
public Date today = new Date();
/** The max years ago. */
public static int MAX_YEARS_AGO = 80; // If valid date/year found -- what is worth filtering?
/** The cal. */
public Calendar cal = null;
/** The current year. */
public int CURRENT_YEAR = 0;
/** The current yy. */
public int CURRENT_YY = 0;
/** The ignore seq. */
public Set<String> IGNORE_SEQ = new HashSet<>();
/**
* Instantiates a new MGRS filter.
*/
public MGRSFilter() {
DateFormat _df = new java.text.SimpleDateFormat("ddMMMyyyy");
// turn off lenient date parsing
_df.setLenient(false);
df.add(_df);
DateFormat _df2a = new java.text.SimpleDateFormat("dMMMyyhhmm");
// turn off lenient date parsing
_df2a.setLenient(true);
df.add(_df2a);
DateFormat _df2b = new java.text.SimpleDateFormat("ddMMMyyhhmm");
// turn off lenient date parsing
_df2b.setLenient(true);
df.add(_df2b);
DateFormat _df2 = new java.text.SimpleDateFormat("dMMMyy");
// turn off lenient date parsing
_df2.setLenient(true);
df.add(_df2);
// Patterns like 15 EST 2012
DateFormat _df3 = new java.text.SimpleDateFormat("HHZZZyyyy");
// turn off lenient date parsing
_df3.setLenient(true);
df.add(_df3);
cal = Calendar.getInstance();
cal.setTime(today);
CURRENT_YEAR = cal.get(Calendar.YEAR);
CURRENT_YY = CURRENT_YEAR - 2000;
IGNORE_SEQ.add("1234");
IGNORE_SEQ.add("123456");
IGNORE_SEQ.add("12345678");
IGNORE_SEQ.add("1234567890");
}
/**
* pass a match.
*
* @param m the m
* @return true, if successful
*/
@Override
public boolean pass(GeocoordMatch m) {
return !stop(m);
}
/** The Constant eol. */
final static Pattern eol = Pattern.compile("[\r\n]");
/**
* TODO: Document rules.
* stop a match
* Note, use of case sensitivity filter is really limited to MGRS. UTM might
* have the "m" units designation on matches; MGRS typically does not.
*
* @param m the m
* @return true, if successful
*/
@Override
public boolean stop(GeocoordMatch m) {
// Simple case filter. 44ger7780 is not really an MGRS.
//
if (!TextUtils.isUpper(m.getText())) {
return true;
}
int len = m.coord_text.length();
if (len < 6) {
return true;
}
String eolTest = m.getText().substring(0, 5);
if (eol.matcher(eolTest).find()) {
return true;
}
// IGNORE numeric sequences
//
String mgrs_offsets = m.coord_text.substring(5);
if (IGNORE_SEQ.contains(mgrs_offsets)) {
return true;
}
String _text = m.getText();
// IGNORE rates or ratios spelled out:
// # PER #
// e.g., 4 PER 100
//
String[] found = _text.split(" ");
if (found.length > 2) {
if ("per".equalsIgnoreCase(found[1])) {
return true;
}
// Units of measure: 'sec' or 'Sec'; the term sec is more a word than an MGRS
// quad here.
//
// 'dd sec ...' fail, filter out.
// 'dd Sec ...' fail, filter out.
// 'dd SEC dd ' pass
// 'ddSEC...' pass
//
if ("sec".equalsIgnoreCase(found[1])) {
return true;
}
}
// Eliminate easy to match DATE + TIME formats commonly used
//
for (DateFormat format : df) {
if (isValidDate(m.coord_text, len, format)) {
return true;
}
}
// Nothing found.
return false;
}
/**
* TODO: exploit XTemp to make light work of date/time normalization
* .... however this filtering is very specific.
*
* @param txt
* @param len
* @param fmt
* @return
*/
private boolean isValidDate(String txt, int len, DateFormat fmt) {
try {
String dt;
if (len > 10) {
dt = txt.substring(0, 10);
} else {
dt = txt;
}
Date D = fmt.parse(dt);
// 30JAN2010 -- date 2 years ago, that is a valid MGRS pattern.
// Filter out.
cal.setTime(D);
int yr = cal.get(Calendar.YEAR);
// Reformat 2-digit year into current millenium.
// And then try...
if (yr <= CURRENT_YY) {
yr += 2000;
} else if (yr <= 100) {
yr += 1900;
}
/*
* Filter out only recent years, not future years.
*/
int pastYearDelta = CURRENT_YEAR - yr;
if (pastYearDelta < MAX_YEARS_AGO && pastYearDelta > 0) {
// Looks like a valid, recent year
return true;
}
String hh = txt.substring(5, 7);
String mm = txt.substring(7, 9);
int hours = Integer.parseInt(hh);
int minutes = Integer.parseInt(mm);
if (hours < 24 && minutes < 60) {
// Looks like a valid HHMM time of day.
return true;
}
} catch (Exception err) {
// NOT a date.
}
return false;
}
}
|
|
/**
* This file is part of SIMPL4(http://simpl4.org).
*
* Copyright [2017] [Manfred Sattler] <[email protected]>
*
* 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.ms123.common.camel.components;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.lang.reflect.Field;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.impl.bpmn.behavior.BpmnActivityBehavior;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.pvm.PvmProcessDefinition;
import org.activiti.engine.impl.pvm.delegate.ActivityBehavior;
import org.activiti.engine.impl.pvm.delegate.ActivityExecution;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.camel.ExchangeUtils;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.MessageHistory;
import org.apache.camel.Message;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.spi.Registry;
import org.apache.camel.core.osgi.OsgiDefaultCamelContext;
import org.apache.camel.core.osgi.OsgiServiceRegistry;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.SimpleRegistry;
import org.apache.camel.impl.CompositeRegistry;
import org.apache.camel.processor.interceptor.Tracer;
import org.apache.camel.processor.interceptor.Tracer;
import org.ms123.common.permission.api.PermissionService;
import org.ms123.common.datamapper.DatamapperService;
import org.ms123.common.data.api.DataLayer;
import org.ms123.common.camel.api.CamelService;
import org.ms123.common.camel.CamelContextBuilder;
import org.ms123.common.camel.trace.*;
import org.ms123.common.camel.components.activiti.ActivitiEndpoint;
import org.ms123.common.camel.components.activiti.ActivitiProducer;
import org.ms123.common.camel.GroovyRegistry;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import groovy.lang.GroovyShell;
import flexjson.*;
import static org.apache.commons.text.StringEscapeUtils.unescapeJava;
import org.apache.commons.beanutils.*;
/**
*/
@SuppressWarnings({"unchecked","deprecation"})
public abstract class BaseCamelBehavior extends BpmnActivityBehavior implements ActivityBehavior {
private Expression variablesmapping;
private Expression resultvar;
public static String PROCESSVAR = "processvar";
public static String CAMELVAR = "camelvar";
public static String DESTINATION = "destination";
public static String DESTINATION_BODY = "body";
public static String DESTINATION_PROP = "property";
public static String DESTINATION_HEADER = "header";
public static String DESTINATION_ROUTING = "routing";
public static String ITEMS = "items";
public static String DOT = "\\.";
String m_tenant, m_processDefinitionKey;
public Class m_routeBuilderClass = null;
private static final long serialVersionUID = 1L;
protected JSONDeserializer m_ds = new JSONDeserializer();
protected JSONSerializer m_js = new JSONSerializer();
protected String m_camelActivitiKey;
protected CamelContext m_camelContext;
protected ActivityExecution m_execution;
protected Map m_mapRouting;
/**
* @deprecated overriding deprecated method
*/
public void execute(ActivityExecution execution) throws Exception {
m_js.prettyPrint(true);
m_execution = execution;
debug("BaseCamelBehavior.execution:" + isASync(execution));
Map mapBody = getVarMapping(execution, variablesmapping,DESTINATION_BODY);
debug("MappingBody:" + m_js.deepSerialize(mapBody));
Map mapProp = getVarMapping(execution, variablesmapping,DESTINATION_PROP);
debug("MappingProp:" + m_js.deepSerialize(mapProp));
Map mapHeader = getVarMapping(execution, variablesmapping,DESTINATION_HEADER);
debug("MappingHeader:" + m_js.deepSerialize(mapHeader));
m_mapRouting = getVarMapping(execution, variablesmapping,DESTINATION_ROUTING);
debug("MappingRouting:" + m_js.deepSerialize(m_mapRouting));
setTenantAndName(execution);
m_camelContext = createCamelContext(m_tenant);
createRouteBuilderClazz();
addRoute(m_camelContext, execution);
m_camelContext.start();
final ActivitiEndpoint endpoint = createEndpoint(execution);
final Exchange exchange = createExchange(execution, endpoint);
exchange.setProperty("activitikey", m_camelActivitiKey);
copyVariablesToProperties( mapProp, exchange);
copyVariablesToHeader( mapHeader, exchange);
copyVariablesToBodyAsMap( mapBody, exchange);
final CamelService camelService = (CamelService)m_camelContext.getRegistry().lookupByName(CamelService.class.getName());
if (isASync(execution)) {
FutureTask<Void> future = new FutureTask<Void>(new Callable<Void>() {
public Void call() {
try {
endpoint.process(exchange);
} catch (Exception e) {
throw new RuntimeException("Unable to process camel endpoint asynchronously.");
}finally{
Exception camelException = exchange.getException();
info("camelException:"+camelException);
printHistory(exchange);
camelService.saveHistory(exchange);
try{
info("Context stop");
m_camelContext.stop();
}catch(Exception e){
e.printStackTrace();
}
}
return null;
}
});
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(future);
handleCamelException(exchange);
} else {
try{
endpoint.process(exchange);
handleCamelException(exchange);
debug(ExchangeUtils.prepareVariables(exchange, endpoint)+"");
String rs = null;
if( resultvar != null){
rs = resultvar.getValue(execution).toString();
}
if(isEmpty(rs)){
execution.setVariables(ExchangeUtils.prepareVariables(exchange, endpoint));
}else{
execution.setVariable(rs, ExchangeUtils.prepareVariables(exchange, endpoint));
}
}finally{
printHistory(exchange);
camelService.saveHistory(exchange);
m_camelContext.stop();
}
}
performDefaultOutgoingBehavior(execution);
}
public static void printHistory(Exchange exchange){
info("printHistoryX");
List<MessageHistory> list = exchange.getProperty(Exchange.MESSAGE_HISTORY, List.class);
ExchangeFormatter formatter = new ExchangeFormatter();
formatter.setShowExchangeId(true);
formatter.setMultiline(true);
formatter.setShowHeaders(true);
formatter.setStyle(ExchangeFormatter.OutputStyle.Fixed);
String routeStackTrace = MessageHelper.dumpMessageHistoryStacktrace(exchange, formatter, true);
info(routeStackTrace);
}
private Map<String, Object> getVarMapping(DelegateExecution execution, Expression variablesmapping, String destination) throws Exception {
if (variablesmapping == null) {
return new HashMap();
}
String vm = variablesmapping.getValue(execution).toString();
debug("getVarMapping:"+vm);
if (vm.trim().length() == 0){
return new HashMap();
}
Map map = (Map) m_ds.deserialize(vm);
debug("getVarMapping.Map:"+map);
List<Map> varmap = (List<Map>) map.get(ITEMS);
Map<String, Object> values = new HashMap();
for (Map<String, String> m : varmap) {
String processVar = m.get(PROCESSVAR);
if( isEmpty(processVar)){
continue;
}
String dest = m.get(DESTINATION);
if(!destination.equals(dest)){
continue;
}
Object o = null;
if( processVar.startsWith("#")){
o = processVar.substring(1);
}else{
o = getValue(execution, processVar);
}
String camelVar = m.get(CAMELVAR);
if( isEmpty(camelVar)){
camelVar = processVar;
}
values.put(camelVar, o);
}
return values;
}
private boolean isEmpty(String s) {
return (s == null || "".equals(s.trim()));
}
private Object getValue(DelegateExecution execution, String processVar) throws Exception {
if (processVar.indexOf(".") == -1) {
return execution.getVariable(processVar);
}
String[] parts = processVar.split(DOT);
Object o = execution.getVariable(parts[0]);
for (int i = 1; i < parts.length; i++) {
String part = parts[i];
o = PropertyUtils.getProperty(o, part);
}
return o;
}
protected Map getRoutingVariables(){
info("getRoutingVariables:"+m_mapRouting);
return m_mapRouting;
}
protected ActivitiEndpoint createEndpoint(ActivityExecution execution) {
String uri = "activiti://" + getProcessDefinitionKey(execution) + ":" + execution.getActivity().getId();
info("createEndpoint:" + uri);
return getEndpoint(uri);
}
protected ActivitiEndpoint getEndpoint(String key) {
for (Endpoint e : m_camelContext.getEndpoints()) {
info("Endpoint:" + e + "|" + e.getEndpointKey());
//if (e.getEndpointKey().equals(key) && (e instanceof ActivitiEndpoint)) {
if (e instanceof ActivitiEndpoint) {
return (ActivitiEndpoint) e;
}
}
throw new RuntimeException("Activiti endpoint not defined for " + key);
}
protected Exchange createExchange(ActivityExecution activityExecution, ActivitiEndpoint endpoint) {
Exchange ex = new DefaultExchange(m_camelContext);
ex.setProperty(ActivitiProducer.PROCESS_ID_PROPERTY, activityExecution.getProcessInstanceId());
return ex;
}
protected void handleCamelException(Exchange exchange) {
Exception camelException = exchange.getException();
boolean notHandledByCamel = exchange.isFailed() && camelException != null;
if (notHandledByCamel) {
//throw new ActivitiException("Unhandled exception on camel route", camelException);
info("Unhandled exception on camel route:"+ camelException);
}
}
protected String getProcessDefinitionKey(ActivityExecution execution) {
PvmProcessDefinition processDefinition = execution.getActivity().getProcessDefinition();
return processDefinition.getKey();
}
protected boolean isASync(ActivityExecution execution) {
return execution.getActivity().isAsync();
}
protected String getStringFromField(Expression expression, DelegateExecution execution) {
if (expression != null) {
Object value = expression.getValue(execution);
if (value != null) {
return value.toString();
}
}
return null;
}
public boolean isCopyCamelBodyToBodyAsString() {
return true;
}
public boolean isCopyVariablesFromHeader() {
return true;
}
protected void copyVariablesToProperties(Map<String, Object> variables, Exchange exchange) {
if( variables.entrySet().size() == 0) return;
for (Map.Entry<String, Object> var : variables.entrySet()) {
exchange.setProperty(var.getKey(), var.getValue());
}
}
protected void copyVariablesToHeader(Map<String, Object> variables, Exchange exchange) {
if( variables.entrySet().size() == 0) return;
for (Map.Entry<String, Object> var : variables.entrySet()) {
exchange.getIn().setHeader(var.getKey(), var.getValue());
}
}
protected void copyVariablesToBodyAsMap(Map<String, Object> variables, Exchange exchange) {
if( variables.entrySet().size() == 0) return;
exchange.getIn().setBody(new HashMap<String,Object>(variables));
}
protected void copyVariablesToBody(Map<String, Object> variables, Exchange exchange) {
if( variables.entrySet().size() == 0) return;
Object camelBody = variables.get(ExchangeUtils.CAMELBODY);
if(camelBody != null) {
exchange.getIn().setBody(camelBody);
}
}
protected synchronized void createRouteBuilderClazz() {
if (m_routeBuilderClass != null)
return;
String routing = unescapeJava(getRoutingDSL());
List<String> paramNames = getParameterNames();
paramNames.addAll(getRoutingVariables().keySet());
String script = buildScript(routing, paramNames);
GroovyShell gs = new GroovyShell();
m_routeBuilderClass = (Class) gs.evaluate(script);
}
private String buildScript(String camelDSL, List<String> paramNames) {
String script = "import org.apache.camel.*\n";
script += "import org.apache.camel.impl.*\n";
script += "import org.apache.camel.builder.*\n";
script += "import org.apache.camel.model.dataformat.*\n";
script += "import java.util.*\n";
script += "class DynRouteBuilder extends org.apache.camel.builder.RouteBuilder implements org.ms123.common.workflow.stencil.StencilRouteBuilder{\n";
for (String fName : paramNames) {
script += "String " + fName + ";";
}
script += "def void init(Map params) {\n";
for (String fName : paramNames) {
script += fName + "=params." + fName + ";\n";
}
script += "}\n";
script += "def void configure() {\n";
script += camelDSL;
script += "}}\n";
script += "return DynRouteBuilder.class\n";
return script;
}
protected RouteBuilder newRouteBuilder() {
try {
RouteBuilder rb = (RouteBuilder) m_routeBuilderClass.newInstance();
return rb;
} catch (Exception e) {
throw new RuntimeException("BaseCamelBehavior.newRouteBuilder", e);
}
}
public abstract void addRoute(CamelContext cc, ActivityExecution execution) throws Exception;
public abstract String getRoutingDSL();
public abstract List<String> getParameterNames();
protected synchronized CamelContext createCamelContext(String namespace) throws Exception {
Map beans = Context.getProcessEngineConfiguration().getBeans();
BundleContext bc = (BundleContext) beans.get("bundleContext");
Registry gr = new GroovyRegistry( BaseCamelBehavior.class.getClassLoader(), bc, namespace);
CamelContext camelContext = CamelContextBuilder.createCamelContext(namespace,gr, bc,false);
return camelContext;
}
protected void setTenantAndName(ActivityExecution execution) {
Map beans = Context.getProcessEngineConfiguration().getBeans();
ProcessEngine pe = (ProcessEngine) beans.get("processEngine");
String processDefinitionId = ((ExecutionEntity) execution).getProcessDefinitionId();
RepositoryService repositoryService = pe.getRepositoryService();
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
m_tenant = processDefinition.getTenantId();
m_processDefinitionKey = processDefinition.getKey();
info("TENANT:" + m_tenant);
info("EID:" + execution.getId());
info("PID:" + execution.getProcessInstanceId());
info("AID:" + execution.getCurrentActivityId());
info("ANAME:" + execution.getCurrentActivityName());
m_camelActivitiKey = m_tenant +"/"+processDefinition.getName()+"/"+execution.getId()+"/"+execution.getCurrentActivityId();
info("m_camelActivitiKey:" + m_camelActivitiKey);
}
protected void debug(String msg) {
m_logger.debug(msg);
}
protected static void info(String msg) {
m_logger.info(msg);
}
private static final org.slf4j.Logger m_logger = org.slf4j.LoggerFactory.getLogger(BaseCamelBehavior.class);
}
|
|
package com.eas.grid;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.eas.bound.ModelDecoratorBox;
import com.eas.core.Utils;
import com.eas.grid.columns.ModelColumn;
import com.eas.grid.columns.header.CheckHeaderNode;
import com.eas.grid.columns.header.HeaderNode;
import com.eas.grid.columns.header.ModelHeaderNode;
import com.eas.grid.columns.header.RadioHeaderNode;
import com.eas.grid.columns.header.ServiceHeaderNode;
import com.eas.ui.PublishedColor;
import com.eas.ui.PublishedFont;
import com.eas.ui.UiReader;
import com.eas.ui.UiWidgetReader;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
public class GridFactory implements UiWidgetReader{
public UIObject readWidget(Element anElement, final UiReader aFactory) throws Exception {
String type = anElement.getTagName();
switch (type) {
case "mg":
case "ModelGrid": {
ModelGrid grid = new ModelGrid();
GridPublisher.publish(grid);
aFactory.readGeneralProps(anElement, grid);
int frozenColumns = Utils.getIntegerAttribute(anElement, "frc", "frozenColumns", 0);
int frozenRows = Utils.getIntegerAttribute(anElement, "frr", "frozenRows", 0);
boolean insertable = Utils.getBooleanAttribute(anElement, "ie", "insertable", Boolean.TRUE);
boolean deletable = Utils.getBooleanAttribute(anElement, "de", "deletable", Boolean.TRUE);
boolean editable = Utils.getBooleanAttribute(anElement, "e", "editable", Boolean.TRUE);
boolean headerVisible = Utils.getBooleanAttribute(anElement, "hv", "headerVisible", Boolean.TRUE);
boolean draggableRows = Utils.getBooleanAttribute(anElement, "dr", "draggableRows", Boolean.FALSE);
boolean showHorizontalLines = Utils.getBooleanAttribute(anElement, "shl", "showHorizontalLines", Boolean.TRUE);
boolean showVerticalLines = Utils.getBooleanAttribute(anElement, "svl", "showVerticalLines", Boolean.TRUE);
boolean showOddRowsInOtherColor = Utils.getBooleanAttribute(anElement, "soc", "showOddRowsInOtherColor", Boolean.TRUE);
int rowsHeight = Utils.getIntegerAttribute(anElement, "rh", "rowsHeight", 30);
grid.setHeaderVisible(headerVisible);
grid.setDraggableRows(draggableRows);
grid.setRowsHeight(rowsHeight);
grid.setShowOddRowsInOtherColor(showOddRowsInOtherColor);
grid.setShowVerticalLines(showVerticalLines);
grid.setShowHorizontalLines(showHorizontalLines);
grid.setEditable(editable);
grid.setDeletable(deletable);
grid.setInsertable(insertable);
grid.setFrozenColumns(frozenColumns);
grid.setFrozenRows(frozenRows);
if (Utils.hasAttribute(anElement, "orc", "oddRowsColor")) {
String oddRowsColorDesc = Utils.getAttribute(anElement, "orc", "oddRowsColor", null);
grid.setOddRowsColor(PublishedColor.parse(oddRowsColorDesc));
}
if (Utils.hasAttribute(anElement, "gc", "gridColor")) {
String gridColorDesc = Utils.getAttribute(anElement, "gc", "gridColor", null);
grid.setGridColor(PublishedColor.parse(gridColorDesc));
}
if (Utils.hasAttribute(anElement, "pf", "parentField")) {
String parentFieldPath = Utils.getAttribute(anElement, "pf", "parentField", null);
grid.setParentField(parentFieldPath);
}
if (Utils.hasAttribute(anElement, "cf", "childrenField")) {
String childrenFieldPath = Utils.getAttribute(anElement, "cf", "childrenField", null);
grid.setChildrenField(childrenFieldPath);
}
List<HeaderNode<JavaScriptObject>> roots = readColumns(anElement, aFactory);
grid.setHeader(roots);
if (Utils.hasAttribute(anElement, "d", "data")) {
String entityName = Utils.getAttribute(anElement, "d", "data", null);
try {
grid.setData(aFactory.resolveEntity(entityName));
} catch (Exception ex) {
Logger.getLogger(GridFactory.class.getName()).log(Level.SEVERE,
"While setting data to named model's property " + entityName + " to widget " + grid.getJsName() + " exception occured: " + ex.getMessage());
}
}
if (Utils.hasAttribute(anElement, "f", "field")) {
String dataPropertyPath = Utils.getAttribute(anElement, "f", "field", null);
grid.setField(dataPropertyPath);
}
return grid;
}
default:
return null;
}
}
private static List<HeaderNode<JavaScriptObject>> readColumns(Element aColumnsElement, UiReader aFactory) throws Exception {
List<HeaderNode<JavaScriptObject>> nodes = new ArrayList<>();
Node childNode = aColumnsElement.getFirstChild();
while (childNode != null) {
if (childNode instanceof Element) {
Element childTag = (Element) childNode;
String columnType = childTag.getTagName();
switch (columnType) {
case "cgc":
case "CheckGridColumn": {
CheckHeaderNode column = new CheckHeaderNode();
GridPublisher.publish(column);
readColumnNode(column, childTag, aFactory);
nodes.add(column);
List<HeaderNode<JavaScriptObject>> children = readColumns(childTag, aFactory);
for (int i = 0; i < children.size(); i++) {
column.addColumnNode(children.get(i));
}
break;
}
case "rgc":
case "RadioGridColumn": {
RadioHeaderNode column = new RadioHeaderNode();
GridPublisher.publish(column);
readColumnNode(column, childTag, aFactory);
nodes.add(column);
List<HeaderNode<JavaScriptObject>> children = readColumns(childTag, aFactory);
for (int i = 0; i < children.size(); i++) {
column.addColumnNode(children.get(i));
}
break;
}
case "sgc":
case "ServiceGridColumn": {
ServiceHeaderNode column = new ServiceHeaderNode();
GridPublisher.publish(column);
readColumnNode(column, childTag, aFactory);
nodes.add(column);
List<HeaderNode<JavaScriptObject>> children = readColumns(childTag, aFactory);
for (int i = 0; i < children.size(); i++) {
column.addColumnNode(children.get(i));
}
break;
}
case "mgc":
case "ModelGridColumn": {
ModelHeaderNode column = new ModelHeaderNode();
GridPublisher.publish(column);
readColumnNode(column, childTag, aFactory);
if (Utils.hasAttribute(childTag, "f", "field")) {
column.setField(Utils.getAttribute(childTag, "f", "field", null));
}
if (Utils.hasAttribute(childTag, "sf", "sortField")) {
column.setSortField(Utils.getAttribute(childTag, "sf", "sortField", null));
}
Node _childNode = childTag.getFirstChild();
while (_childNode != null) {
if (_childNode instanceof Element) {
Element _childTag = (Element) _childNode;
UIObject editorComp = aFactory.readWidget(_childTag);
if (editorComp instanceof ModelDecoratorBox<?>) {
ModelColumn col = (ModelColumn) column.getColumn();
col.setEditor((ModelDecoratorBox<Object>) editorComp);
// ModelWidget viewComp = (ModelWidget)
// readWidget((Element) _childNode);
// col.setView(viewComp);
break;
}
}
_childNode = _childNode.getNextSibling();
}
nodes.add(column);
List<HeaderNode<JavaScriptObject>> children = readColumns(childTag, aFactory);
for (int i = 0; i < children.size(); i++) {
column.addColumnNode(children.get(i));
}
break;
}
}
}
childNode = childNode.getNextSibling();
}
return nodes;
}
private static void readColumnNode(ModelHeaderNode aNode, Element anElement, UiReader aFactory) throws Exception {
aNode.setJsName(Utils.getAttribute(anElement, "n", "name", null));
if (Utils.hasAttribute(anElement, "tl", "title")) {
aNode.setTitle(Utils.getAttribute(anElement, "tl", "title", null));
}
if (Utils.hasAttribute(anElement, "bg", "background")) {
PublishedColor background = PublishedColor.parse(Utils.getAttribute(anElement, "bg", "background", null));
aNode.setBackground(background);
}
if (Utils.hasAttribute(anElement, "fg", "foreground")) {
PublishedColor foreground = PublishedColor.parse(Utils.getAttribute(anElement, "fg", "foreground", null));
aNode.setForeground(foreground);
}
aNode.setReadonly(Utils.getBooleanAttribute(anElement, "ro", "readonly", Boolean.FALSE));
// aNode.setEnabled(Utils.getBooleanAttribute(anElement, "en", "enabled",
// Boolean.TRUE));
PublishedFont font = aFactory.readFont(anElement);
if (font != null) {
aNode.setFont(font);
}
if (Utils.hasAttribute(anElement, "mw", "minWidth")) {
String minWidth = Utils.getAttribute(anElement, "mw", "minWidth", null);
if (minWidth.length() > 2 && minWidth.endsWith("px")) {
aNode.setMinWidth(Integer.parseInt(minWidth.substring(0, minWidth.length() - 2)));
}
}
if (Utils.hasAttribute(anElement, "mxw", "maxWidth")) {
String maxWidth = Utils.getAttribute(anElement, "mxw", "maxWidth", null);
if (maxWidth.length() > 2 && maxWidth.endsWith("px")) {
aNode.setMaxWidth(Integer.parseInt(maxWidth.substring(0, maxWidth.length() - 2)));
}
}
if (Utils.hasAttribute(anElement, "prw", "preferredWidth")) {
String preferredWidth = Utils.getAttribute(anElement, "prw", "preferredWidth", null);
if (preferredWidth.length() > 2 && preferredWidth.endsWith("px")) {
aNode.setPreferredWidth(Integer.parseInt(preferredWidth.substring(0, preferredWidth.length() - 2)));
}
}
aNode.setMoveable(Utils.getBooleanAttribute(anElement, "m", "movable", Boolean.TRUE));
aNode.setResizable(Utils.getBooleanAttribute(anElement, "rs", "resizable", aNode instanceof CheckHeaderNode || aNode instanceof RadioHeaderNode || aNode instanceof ServiceHeaderNode ? Boolean.FALSE
: Boolean.TRUE));
// aNode.setSelectOnly(Utils.getBooleanAttribute(anElement, "so",
// "selectOnly", Boolean.FALSE));
aNode.setSortable(Utils.getBooleanAttribute(anElement, "s", "sortable", Boolean.TRUE));
aNode.setVisible(Utils.getBooleanAttribute(anElement, "v", "visible", Boolean.TRUE));
}
}
|
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.09.07 at 08:01:35 PM IST
//
package com.mozu.qbintegration.model.qbmodel.allgen;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}TxnID"/>
* <element ref="{}TxnType"/>
* <element ref="{}APAccountRef"/>
* <element ref="{}TxnDate"/>
* <element name="RefNumber" minOccurs="0">
* <simpleType>
* <restriction base="{}STRTYPE">
* <maxLength value="20"/>
* </restriction>
* </simpleType>
* </element>
* <element ref="{}DueDate" minOccurs="0"/>
* <element ref="{}AmountDue"/>
* <element ref="{}CurrencyRef" minOccurs="0"/>
* <element ref="{}ExchangeRate" minOccurs="0"/>
* <element ref="{}AmountDueInHomeCurrency" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"txnID",
"txnType",
"apAccountRef",
"txnDate",
"refNumber",
"dueDate",
"amountDue",
"currencyRef",
"exchangeRate",
"amountDueInHomeCurrency"
})
@XmlRootElement(name = "BillToPay")
public class BillToPay {
@XmlElement(name = "TxnID", required = true)
protected String txnID;
@XmlElement(name = "TxnType", required = true)
protected String txnType;
@XmlElement(name = "APAccountRef", required = true)
protected APAccountRef apAccountRef;
@XmlElement(name = "TxnDate", required = true)
protected String txnDate;
@XmlElement(name = "RefNumber")
protected String refNumber;
@XmlElement(name = "DueDate")
protected String dueDate;
@XmlElement(name = "AmountDue", required = true)
protected String amountDue;
@XmlElement(name = "CurrencyRef")
protected CurrencyRef currencyRef;
@XmlElement(name = "ExchangeRate")
protected String exchangeRate;
@XmlElement(name = "AmountDueInHomeCurrency")
protected String amountDueInHomeCurrency;
/**
* Gets the value of the txnID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTxnID() {
return txnID;
}
/**
* Sets the value of the txnID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTxnID(String value) {
this.txnID = value;
}
/**
* Gets the value of the txnType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTxnType() {
return txnType;
}
/**
* Sets the value of the txnType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTxnType(String value) {
this.txnType = value;
}
/**
* Gets the value of the apAccountRef property.
*
* @return
* possible object is
* {@link APAccountRef }
*
*/
public APAccountRef getAPAccountRef() {
return apAccountRef;
}
/**
* Sets the value of the apAccountRef property.
*
* @param value
* allowed object is
* {@link APAccountRef }
*
*/
public void setAPAccountRef(APAccountRef value) {
this.apAccountRef = value;
}
/**
* Gets the value of the txnDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTxnDate() {
return txnDate;
}
/**
* Sets the value of the txnDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTxnDate(String value) {
this.txnDate = value;
}
/**
* Gets the value of the refNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRefNumber() {
return refNumber;
}
/**
* Sets the value of the refNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRefNumber(String value) {
this.refNumber = value;
}
/**
* Gets the value of the dueDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDueDate() {
return dueDate;
}
/**
* Sets the value of the dueDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDueDate(String value) {
this.dueDate = value;
}
/**
* Gets the value of the amountDue property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAmountDue() {
return amountDue;
}
/**
* Sets the value of the amountDue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAmountDue(String value) {
this.amountDue = value;
}
/**
* Gets the value of the currencyRef property.
*
* @return
* possible object is
* {@link CurrencyRef }
*
*/
public CurrencyRef getCurrencyRef() {
return currencyRef;
}
/**
* Sets the value of the currencyRef property.
*
* @param value
* allowed object is
* {@link CurrencyRef }
*
*/
public void setCurrencyRef(CurrencyRef value) {
this.currencyRef = value;
}
/**
* Gets the value of the exchangeRate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getExchangeRate() {
return exchangeRate;
}
/**
* Sets the value of the exchangeRate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExchangeRate(String value) {
this.exchangeRate = value;
}
/**
* Gets the value of the amountDueInHomeCurrency property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAmountDueInHomeCurrency() {
return amountDueInHomeCurrency;
}
/**
* Sets the value of the amountDueInHomeCurrency property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAmountDueInHomeCurrency(String value) {
this.amountDueInHomeCurrency = value;
}
}
|
|
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.jabber;
import java.io.*;
import java.util.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.thumbnail.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.FileTransfer;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.filetransfer.*;
/**
* Jabber implementation of the incoming file transfer request
*
* @author Nicolas Riegel
* @author Yana Stamcheva
*/
public class IncomingFileTransferRequestJabberImpl
implements IncomingFileTransferRequest
{
/**
* The logger for this class.
*/
private static final Logger logger =
Logger.getLogger(IncomingFileTransferRequestJabberImpl.class);
private String id;
/**
* The Jabber file transfer request.
*/
private final FileTransferRequest fileTransferRequest;
private final OperationSetFileTransferJabberImpl fileTransferOpSet;
private final ProtocolProviderServiceJabberImpl jabberProvider;
private Contact sender;
private String thumbnailCid;
private byte[] thumbnail;
/**
* Creates an <tt>IncomingFileTransferRequestJabberImpl</tt> based on the
* given <tt>fileTransferRequest</tt>, coming from the Jabber protocol.
*
* @param jabberProvider the protocol provider
* @param fileTransferOpSet file transfer operation set
* @param fileTransferRequest the request coming from the Jabber protocol
*/
public IncomingFileTransferRequestJabberImpl(
ProtocolProviderServiceJabberImpl jabberProvider,
OperationSetFileTransferJabberImpl fileTransferOpSet,
FileTransferRequest fileTransferRequest)
{
this.jabberProvider = jabberProvider;
this.fileTransferOpSet = fileTransferOpSet;
this.fileTransferRequest = fileTransferRequest;
String fromUserID
= fileTransferRequest.getRequestor();
OperationSetPersistentPresenceJabberImpl opSetPersPresence
= (OperationSetPersistentPresenceJabberImpl)
jabberProvider
.getOperationSet(OperationSetPersistentPresence.class);
sender = opSetPersPresence.findContactByID(fromUserID);
if(sender == null)
{
ChatRoom privateContactRoom = null;
OperationSetMultiUserChatJabberImpl mucOpSet =
(OperationSetMultiUserChatJabberImpl)jabberProvider
.getOperationSet(OperationSetMultiUserChat.class);
if(mucOpSet != null)
privateContactRoom = mucOpSet
.getChatRoom(StringUtils.parseBareAddress(fromUserID));
if(privateContactRoom != null)
{
sender = ((OperationSetPersistentPresenceJabberImpl)
jabberProvider.getOperationSet(
OperationSetPersistentPresence.class))
.createVolatileContact(fromUserID, true);
privateContactRoom.updatePrivateContactPresenceStatus(sender);
}
}
this.id = String.valueOf( System.currentTimeMillis())
+ String.valueOf(hashCode());
}
/**
* Returns the <tt>Contact</tt> making this request.
*
* @return the <tt>Contact</tt> making this request
*/
public Contact getSender()
{
return sender;
}
/**
* Returns the description of the file corresponding to this request.
*
* @return the description of the file corresponding to this request
*/
public String getFileDescription()
{
return fileTransferRequest.getDescription();
}
/**
* Returns the name of the file corresponding to this request.
*
* @return the name of the file corresponding to this request
*/
public String getFileName()
{
return fileTransferRequest.getFileName();
}
/**
* Returns the size of the file corresponding to this request.
*
* @return the size of the file corresponding to this request
*/
public long getFileSize()
{
return fileTransferRequest.getFileSize();
}
/**
* Accepts the file and starts the transfer.
*
* @return a boolean : <code>false</code> if the transfer fails,
* <code>true</code> otherwise
*/
public FileTransfer acceptFile(File file)
{
AbstractFileTransfer incomingTransfer = null;
IncomingFileTransfer jabberTransfer = fileTransferRequest.accept();
try
{
incomingTransfer
= new IncomingFileTransferJabberImpl(
id, sender, file, jabberTransfer);
FileTransferCreatedEvent event
= new FileTransferCreatedEvent(incomingTransfer, new Date());
fileTransferOpSet.fireFileTransferCreated(event);
jabberTransfer.recieveFile(file);
new OperationSetFileTransferJabberImpl
.FileTransferProgressThread(
jabberTransfer, incomingTransfer, getFileSize()).start();
}
catch (XMPPException e)
{
if (logger.isDebugEnabled())
logger.debug("Receiving file failed.", e);
}
return incomingTransfer;
}
/**
* Refuses the file transfer request.
*/
public void rejectFile()
{
fileTransferRequest.reject();
fileTransferOpSet.fireFileTransferRequestRejected(
new FileTransferRequestEvent(fileTransferOpSet, this, new Date()));
}
/**
* The unique id.
* @return the id.
*/
public String getID()
{
return id;
}
/**
* Returns the thumbnail contained in this request.
*
* @return the thumbnail contained in this request
*/
public byte[] getThumbnail()
{
return thumbnail;
}
/**
* Sets the thumbnail content-ID.
* @param cid the thumbnail content-ID
*/
public void createThumbnailListeners(String cid)
{
this.thumbnailCid = cid;
if (jabberProvider.getConnection() != null)
{
jabberProvider.getConnection().addPacketListener(
new ThumbnailResponseListener(),
new AndFilter( new PacketTypeFilter(IQ.class),
new IQTypeFilter(IQ.Type.RESULT)));
}
}
/**
* The <tt>ThumbnailResponseListener</tt> listens for events triggered by
* the reception of a <tt>ThumbnailIQ</tt> packet. The packet is examined
* and a file transfer request event is fired when the thumbnail is
* extracted.
*/
private class ThumbnailResponseListener implements PacketListener
{
public void processPacket(Packet packet)
{
// If this is not an IQ packet, we're not interested.
if (!(packet instanceof ThumbnailIQ))
return;
if (logger.isDebugEnabled())
logger.debug("Thumbnail response received.");
ThumbnailIQ thumbnailResponse = (ThumbnailIQ) packet;
if (thumbnailResponse.getCid() != null
&& thumbnailResponse.getCid().equals(thumbnailCid))
{
thumbnail = thumbnailResponse.getData();
// Create an event associated to this global request.
FileTransferRequestEvent fileTransferRequestEvent
= new FileTransferRequestEvent(
fileTransferOpSet,
IncomingFileTransferRequestJabberImpl.this,
new Date());
// Notify the global listener that a request has arrived.
fileTransferOpSet.fireFileTransferRequest(
fileTransferRequestEvent);
}
else
{
//TODO: RETURN <item-not-found/>
}
if (jabberProvider.getConnection() != null)
{
jabberProvider.getConnection()
.removePacketListener(this);
}
}
}
}
|
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.openvr;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* <h3>Layout</h3>
*
* <pre><code>
* struct IntersectionMaskCircle_t {
* float m_flCenterX;
* float m_flCenterY;
* float m_flRadius;
* }</code></pre>
*/
@NativeType("struct IntersectionMaskCircle_t")
public class IntersectionMaskCircle extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
M_FLCENTERX,
M_FLCENTERY,
M_FLRADIUS;
static {
Layout layout = __struct(
__member(4),
__member(4),
__member(4)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
M_FLCENTERX = layout.offsetof(0);
M_FLCENTERY = layout.offsetof(1);
M_FLRADIUS = layout.offsetof(2);
}
/**
* Creates a {@code IntersectionMaskCircle} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public IntersectionMaskCircle(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** @return the value of the {@code m_flCenterX} field. */
public float m_flCenterX() { return nm_flCenterX(address()); }
/** @return the value of the {@code m_flCenterY} field. */
public float m_flCenterY() { return nm_flCenterY(address()); }
/** @return the value of the {@code m_flRadius} field. */
public float m_flRadius() { return nm_flRadius(address()); }
/** Sets the specified value to the {@code m_flCenterX} field. */
public IntersectionMaskCircle m_flCenterX(float value) { nm_flCenterX(address(), value); return this; }
/** Sets the specified value to the {@code m_flCenterY} field. */
public IntersectionMaskCircle m_flCenterY(float value) { nm_flCenterY(address(), value); return this; }
/** Sets the specified value to the {@code m_flRadius} field. */
public IntersectionMaskCircle m_flRadius(float value) { nm_flRadius(address(), value); return this; }
/** Initializes this struct with the specified values. */
public IntersectionMaskCircle set(
float m_flCenterX,
float m_flCenterY,
float m_flRadius
) {
m_flCenterX(m_flCenterX);
m_flCenterY(m_flCenterY);
m_flRadius(m_flRadius);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public IntersectionMaskCircle set(IntersectionMaskCircle src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code IntersectionMaskCircle} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static IntersectionMaskCircle malloc() {
return wrap(IntersectionMaskCircle.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code IntersectionMaskCircle} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static IntersectionMaskCircle calloc() {
return wrap(IntersectionMaskCircle.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code IntersectionMaskCircle} instance allocated with {@link BufferUtils}. */
public static IntersectionMaskCircle create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(IntersectionMaskCircle.class, memAddress(container), container);
}
/** Returns a new {@code IntersectionMaskCircle} instance for the specified memory address. */
public static IntersectionMaskCircle create(long address) {
return wrap(IntersectionMaskCircle.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static IntersectionMaskCircle createSafe(long address) {
return address == NULL ? null : wrap(IntersectionMaskCircle.class, address);
}
/**
* Returns a new {@link IntersectionMaskCircle.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static IntersectionMaskCircle.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link IntersectionMaskCircle.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static IntersectionMaskCircle.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link IntersectionMaskCircle.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static IntersectionMaskCircle.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link IntersectionMaskCircle.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static IntersectionMaskCircle.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static IntersectionMaskCircle.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
// -----------------------------------
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static IntersectionMaskCircle mallocStack() { return malloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static IntersectionMaskCircle callocStack() { return calloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static IntersectionMaskCircle mallocStack(MemoryStack stack) { return malloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static IntersectionMaskCircle callocStack(MemoryStack stack) { return calloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static IntersectionMaskCircle.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static IntersectionMaskCircle.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static IntersectionMaskCircle.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static IntersectionMaskCircle.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); }
/**
* Returns a new {@code IntersectionMaskCircle} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static IntersectionMaskCircle malloc(MemoryStack stack) {
return wrap(IntersectionMaskCircle.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code IntersectionMaskCircle} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static IntersectionMaskCircle calloc(MemoryStack stack) {
return wrap(IntersectionMaskCircle.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link IntersectionMaskCircle.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static IntersectionMaskCircle.Buffer malloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link IntersectionMaskCircle.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static IntersectionMaskCircle.Buffer calloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #m_flCenterX}. */
public static float nm_flCenterX(long struct) { return UNSAFE.getFloat(null, struct + IntersectionMaskCircle.M_FLCENTERX); }
/** Unsafe version of {@link #m_flCenterY}. */
public static float nm_flCenterY(long struct) { return UNSAFE.getFloat(null, struct + IntersectionMaskCircle.M_FLCENTERY); }
/** Unsafe version of {@link #m_flRadius}. */
public static float nm_flRadius(long struct) { return UNSAFE.getFloat(null, struct + IntersectionMaskCircle.M_FLRADIUS); }
/** Unsafe version of {@link #m_flCenterX(float) m_flCenterX}. */
public static void nm_flCenterX(long struct, float value) { UNSAFE.putFloat(null, struct + IntersectionMaskCircle.M_FLCENTERX, value); }
/** Unsafe version of {@link #m_flCenterY(float) m_flCenterY}. */
public static void nm_flCenterY(long struct, float value) { UNSAFE.putFloat(null, struct + IntersectionMaskCircle.M_FLCENTERY, value); }
/** Unsafe version of {@link #m_flRadius(float) m_flRadius}. */
public static void nm_flRadius(long struct, float value) { UNSAFE.putFloat(null, struct + IntersectionMaskCircle.M_FLRADIUS, value); }
// -----------------------------------
/** An array of {@link IntersectionMaskCircle} structs. */
public static class Buffer extends StructBuffer<IntersectionMaskCircle, Buffer> implements NativeResource {
private static final IntersectionMaskCircle ELEMENT_FACTORY = IntersectionMaskCircle.create(-1L);
/**
* Creates a new {@code IntersectionMaskCircle.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link IntersectionMaskCircle#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected IntersectionMaskCircle getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return the value of the {@code m_flCenterX} field. */
public float m_flCenterX() { return IntersectionMaskCircle.nm_flCenterX(address()); }
/** @return the value of the {@code m_flCenterY} field. */
public float m_flCenterY() { return IntersectionMaskCircle.nm_flCenterY(address()); }
/** @return the value of the {@code m_flRadius} field. */
public float m_flRadius() { return IntersectionMaskCircle.nm_flRadius(address()); }
/** Sets the specified value to the {@code m_flCenterX} field. */
public IntersectionMaskCircle.Buffer m_flCenterX(float value) { IntersectionMaskCircle.nm_flCenterX(address(), value); return this; }
/** Sets the specified value to the {@code m_flCenterY} field. */
public IntersectionMaskCircle.Buffer m_flCenterY(float value) { IntersectionMaskCircle.nm_flCenterY(address(), value); return this; }
/** Sets the specified value to the {@code m_flRadius} field. */
public IntersectionMaskCircle.Buffer m_flRadius(float value) { IntersectionMaskCircle.nm_flRadius(address(), value); return this; }
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.resourceresolver.impl;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.collections.BidiMap;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.resourceresolver.impl.console.ResourceResolverWebConsolePlugin;
import org.apache.sling.resourceresolver.impl.helper.ResourceDecoratorTracker;
import org.apache.sling.resourceresolver.impl.helper.ResourceResolverControl;
import org.apache.sling.resourceresolver.impl.mapping.MapConfigurationProvider;
import org.apache.sling.resourceresolver.impl.mapping.MapEntries;
import org.apache.sling.resourceresolver.impl.mapping.Mapping;
import org.apache.sling.resourceresolver.impl.providers.ResourceProviderTracker;
import org.apache.sling.spi.resource.provider.ResourceProvider;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>CommonResourceResolverFactoryImpl</code> is a singleton
* implementing the shared/common functionality of all resource
* resolver factories.
*/
public class CommonResourceResolverFactoryImpl implements ResourceResolverFactory, MapConfigurationProvider {
/** Helper for the resource resolver. */
private MapEntries mapEntries = MapEntries.EMPTY;
/** The web console plugin. */
private ResourceResolverWebConsolePlugin plugin;
/** The activator */
private final ResourceResolverFactoryActivator activator;
/**
* Thread local holding the resource resolver stack
*/
private ThreadLocal<Stack<WeakReference<ResourceResolver>>> resolverStackHolder = new ThreadLocal<Stack<WeakReference<ResourceResolver>>>();
/** Flag indicating whether this factory is still active. */
private final AtomicBoolean isActive = new AtomicBoolean(true);
/** The reference queue to handle disposing of resource resolver instances. */
private final ReferenceQueue<ResourceResolver> resolverReferenceQueue = new ReferenceQueue<ResourceResolver>();
/** All weak references for the resource resolver instances. */
private final Map<Integer, ResolverWeakReference> refs = new ConcurrentHashMap<Integer, CommonResourceResolverFactoryImpl.ResolverWeakReference>();
/** Background thread handling disposing of resource resolver instances. */
private final Thread refQueueThread;
private boolean logResourceResolverClosing = false;
/**
* Create a new common resource resolver factory.
*/
public CommonResourceResolverFactoryImpl(final ResourceResolverFactoryActivator activator) {
this.activator = activator;
this.logResourceResolverClosing = activator.shouldLogResourceResolverClosing();
this.refQueueThread = new Thread("Apache Sling Resource Resolver Finalizer Thread") {
@Override
public void run() {
while ( isActive.get() ) {
try {
final ResolverWeakReference ref = (ResolverWeakReference) resolverReferenceQueue.remove();
try {
ref.close();
} catch ( final Throwable t ) {
// we ignore everything from there to not stop this thread
}
refs.remove(ref.control.hashCode());
} catch ( final InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
for(final ResolverWeakReference ref : refs.values()) {
ref.close();
}
refs.clear();
}
};
this.refQueueThread.setDaemon(true);
this.refQueueThread.start();
}
// ---------- Resource Resolver Factory ------------------------------------
/**
* @see org.apache.sling.api.resource.ResourceResolverFactory#getAdministrativeResourceResolver(java.util.Map)
*/
@Override
public ResourceResolver getAdministrativeResourceResolver(final Map<String, Object> passedAuthenticationInfo)
throws LoginException {
if ( !isActive.get() ) {
throw new LoginException("ResourceResolverFactory is deactivated.");
}
// create a copy of the passed authentication info as we modify the map
final Map<String, Object> authenticationInfo = new HashMap<String, Object>();
authenticationInfo.put(ResourceProvider.AUTH_ADMIN, Boolean.TRUE);
if ( passedAuthenticationInfo != null ) {
authenticationInfo.putAll(passedAuthenticationInfo);
// make sure there is no leaking of service bundle and info props
authenticationInfo.remove(ResourceProvider.AUTH_SERVICE_BUNDLE);
authenticationInfo.remove(SUBSERVICE);
}
return getResourceResolverInternal(authenticationInfo, true);
}
/**
* @see org.apache.sling.api.resource.ResourceResolverFactory#getResourceResolver(java.util.Map)
*/
@Override
public ResourceResolver getResourceResolver(final Map<String, Object> passedAuthenticationInfo)
throws LoginException {
if ( !isActive.get() ) {
throw new LoginException("ResourceResolverFactory is deactivated.");
}
// create a copy of the passed authentication info as we modify the map
final Map<String, Object> authenticationInfo = new HashMap<String, Object>();
if ( passedAuthenticationInfo != null ) {
authenticationInfo.putAll(passedAuthenticationInfo);
// make sure there is no leaking of service bundle and info props
authenticationInfo.remove(ResourceProvider.AUTH_SERVICE_BUNDLE);
authenticationInfo.remove(SUBSERVICE);
}
final ResourceResolver result = getResourceResolverInternal(authenticationInfo, false);
Stack<WeakReference<ResourceResolver>> resolverStack = resolverStackHolder.get();
if ( resolverStack == null ) {
resolverStack = new Stack<WeakReference<ResourceResolver>>();
resolverStackHolder.set(resolverStack);
}
resolverStack.push(new WeakReference<ResourceResolver>(result));
return result;
}
/**
* @see org.apache.sling.api.resource.ResourceResolverFactory#getThreadResourceResolver()
*/
@Override
public ResourceResolver getThreadResourceResolver() {
if ( !isActive.get() ) {
return null;
}
ResourceResolver result = null;
final Stack<WeakReference<ResourceResolver>> resolverStack = resolverStackHolder.get();
if ( resolverStack != null) {
while ( result == null && !resolverStack.isEmpty() ) {
result = resolverStack.peek().get();
if ( result == null ) {
resolverStack.pop();
}
}
}
return result;
}
// ---------- Implementation helpers --------------------------------------
/**
* Inform about a new resource resolver instance.
* We create a weak reference to be able to close the resolver if close on the
* resource resolver is never called.
* @param resolver The resource resolver
* @param ctrl The resource resolver control
*/
public void register(final ResourceResolver resolver,
final ResourceResolverControl ctrl) {
// create new weak reference
refs.put(ctrl.hashCode(), new ResolverWeakReference(resolver, this.resolverReferenceQueue, ctrl));
}
/**
* Inform about a closed resource resolver.
* Make sure to remove it from the current thread context.
* @param resourceResolverImpl The resource resolver
* @param ctrl The resource resolver control
*/
public void unregister(final ResourceResolver resourceResolverImpl,
final ResourceResolverControl ctrl) {
// close the context
ctrl.close();
// remove it from the set of weak references.
refs.remove(ctrl.hashCode());
// on shutdown, the factory might already be closed before the resolvers close
// therefore we have to check for null
final ThreadLocal<Stack<WeakReference<ResourceResolver>>> tl = resolverStackHolder;
if ( tl != null ) {
final Stack<WeakReference<ResourceResolver>> resolverStack = tl.get();
if ( resolverStack != null ) {
final Iterator<WeakReference<ResourceResolver>> i = resolverStack.iterator();
while ( i.hasNext() ) {
final WeakReference<ResourceResolver> ref = i.next();
if ( ref.get() == null || ref.get() == resourceResolverImpl ) {
i.remove();
}
}
if ( resolverStack.isEmpty() ) {
tl.remove();
}
}
}
}
/**
* Create a new ResourceResolver
* @param authenticationInfo The authentication map
* @param isAdmin is an administrative resolver requested?
* @return A resource resolver
* @throws LoginException if login to any of the required resource providers fails.
*/
public ResourceResolver getResourceResolverInternal(final Map<String, Object> authenticationInfo,
final boolean isAdmin)
throws LoginException {
if ( !isActive.get() ) {
throw new LoginException("ResourceResolverFactory is deactivated.");
}
return new ResourceResolverImpl(this, isAdmin, authenticationInfo);
}
public MapEntries getMapEntries() {
return mapEntries;
}
/** Activates this component */
protected void activate(final BundleContext bundleContext) {
final Logger logger = LoggerFactory.getLogger(getClass());
try {
plugin = new ResourceResolverWebConsolePlugin(bundleContext, this, this.activator.getRuntimeService());
} catch (final Throwable ignore) {
// an exception here probably means the web console plugin is not
// available
logger.debug("activate: unable to setup web console plugin.", ignore);
}
// set up the map entries from configuration
try {
mapEntries = new MapEntries(this, bundleContext, this.activator.getEventAdmin());
} catch (final Exception e) {
logger.error("activate: Cannot access repository, failed setting up Mapping Support", e);
}
}
/**
* Deactivates this component
*/
protected void deactivate() {
isActive.set(false);
this.refQueueThread.interrupt();
if (plugin != null) {
plugin.dispose();
plugin = null;
}
if (mapEntries != null) {
mapEntries.dispose();
mapEntries = MapEntries.EMPTY;
}
resolverStackHolder = null;
}
public ResourceDecoratorTracker getResourceDecoratorTracker() {
return this.activator.getResourceDecoratorTracker();
}
public String[] getSearchPath() {
return this.activator.getSearchPath();
}
public boolean isMangleNamespacePrefixes() {
return this.activator.isMangleNamespacePrefixes();
}
@Override
public String getMapRoot() {
return this.activator.getMapRoot();
}
@Override
public Mapping[] getMappings() {
return this.activator.getMappings();
}
@Override
public BidiMap getVirtualURLMap() {
return this.activator.getVirtualURLMap();
}
@Override
public int getDefaultVanityPathRedirectStatus() {
return this.activator.getDefaultVanityPathRedirectStatus();
}
/**
* get's the ServiceTracker of the ResourceAccessSecurity service
*/
public ResourceAccessSecurityTracker getResourceAccessSecurityTracker () {
return this.activator.getResourceAccessSecurityTracker();
}
@Override
public ResourceResolver getServiceResourceResolver(
final Map<String, Object> authenticationInfo) throws LoginException {
throw new IllegalStateException("This method is not implemented.");
}
@Override
public boolean isVanityPathEnabled() {
return this.activator.isVanityPathEnabled();
}
@Override
public long getMaxCachedVanityPathEntries() {
return this.activator.getMaxCachedVanityPathEntries();
}
@Override
public boolean isMaxCachedVanityPathEntriesStartup() {
return this.activator.isMaxCachedVanityPathEntriesStartup();
}
@Override
public int getVanityBloomFilterMaxBytes() {
return this.activator.getVanityBloomFilterMaxBytes();
}
@Override
public boolean isOptimizeAliasResolutionEnabled() {
return this.activator.isOptimizeAliasResolutionEnabled();
}
@Override
public boolean hasVanityPathPrecedence() {
return this.activator.hasVanityPathPrecedence();
}
@Override
public List<VanityPathConfig> getVanityPathConfig() {
final String[] includes = this.activator.getVanityPathWhiteList();
final String[] excludes = this.activator.getVanityPathBlackList();
if ( includes == null && excludes == null ) {
return null;
}
final List<VanityPathConfig> configs = new ArrayList<VanityPathConfig>();
if ( includes != null ) {
for(final String val : includes) {
configs.add(new VanityPathConfig(val, false));
}
}
if ( excludes != null ) {
for(final String val : excludes) {
configs.add(new VanityPathConfig(val, true));
}
}
Collections.sort(configs);
return configs;
}
/**
* Is this factory still alive?
*/
public boolean isLive() {
return this.isActive.get();
}
public boolean shouldLogResourceResolverClosing() {
return logResourceResolverClosing;
}
public ResourceProviderTracker getResourceProviderTracker() {
return activator.getResourceProviderTracker();
}
/**
* Extension of a weak reference to be able to get the control object
* that is used for cleaning up.
*/
private static final class ResolverWeakReference extends WeakReference<ResourceResolver> {
private final ResourceResolverControl control;
public ResolverWeakReference(final ResourceResolver referent,
final ReferenceQueue<? super ResourceResolver> q,
final ResourceResolverControl ctrl) {
super(referent, q);
this.control = ctrl;
}
public void close() {
this.control.close();
}
}
}
|
|
/*
Copyright 2012 Selenium committers
Copyright 2012 Software Freedom Conservancy
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.openqa.selenium.server.mock;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.logging.Log;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.openqa.jetty.log.LogFactory;
import org.openqa.selenium.server.DefaultRemoteCommand;
import org.openqa.selenium.server.InjectionHelper;
import org.openqa.selenium.server.RemoteCommand;
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import org.openqa.selenium.server.WindowClosedException;
import org.openqa.selenium.server.browserlaunchers.BrowserLauncherFactory;
import org.openqa.selenium.remote.server.log.LoggingManager;
import org.openqa.selenium.remote.server.log.LoggingOptions;
import org.openqa.selenium.remote.server.log.StdOutHandler;
import org.openqa.selenium.remote.server.log.TerseFormatter;
import java.io.File;
import java.util.logging.Handler;
import java.util.logging.Logger;
public class MockPIFrameUnitTest {
static final Log LOGGER = LogFactory.getLog(MockPIFrameUnitTest.class);
@Rule public TestName name = new TestName();
private static final String DRIVER_URL = "http://localhost:4444/selenium-server/driver/";
private static int timeoutInSeconds = 10;
private String sessionId;
private SeleniumServer server;
@Before
public void setUp() throws Exception {
configureLogging();
RemoteControlConfiguration configuration = new RemoteControlConfiguration();
configuration.setTimeoutInSeconds(timeoutInSeconds);
configuration.setProxyInjectionModeArg(true);
server = new SeleniumServer(false, configuration);
server.start();
BrowserLauncherFactory.addBrowserLauncher("dummy", DummyBrowserLauncher.class);
InjectionHelper.setFailOnError(false);
LOGGER.info("Starting " + name.getMethodName());
}
private LoggingOptions configureLogging() throws Exception {
// SeleniumServer.setDebugMode(true);
LoggingOptions configuration = new LoggingOptions();
File target = new File("target");
if (target.exists() && target.isDirectory()) {
configuration.setLogOutFile(new File(target, "mockpiframe.log"));
} else {
configuration.setLogOutFile(new File("mockpiframe.log"));
}
LoggingManager.configureLogging(configuration, false);
Logger logger = Logger.getLogger("");
for (Handler handler : logger.getHandlers()) {
if (handler instanceof StdOutHandler) {
handler.setFormatter(new TerseFormatter(true));
break;
}
}
return configuration;
}
@After
public void tearDown() {
server.stop();
LoggingManager.configureLogging(new LoggingOptions(), false);
DummyBrowserLauncher.clearSessionId();
InjectionHelper.setFailOnError(true);
}
/**
* start a basic browser session
*/
@Test
public void testStartSession() {
startSession();
}
/**
* start a basic browser session
*
* @return the currently running MockPIFrame
*/
public MockPIFrame startSession() {
// 1. driver requests new session
DriverRequest driverRequest = sendCommand("getNewBrowserSession", "*dummy", "http://x");
// 2. server generates new session, awaits browser launch
sessionId = waitForSessionId(driverRequest);
LOGGER.debug("browser starting session " + sessionId);
// 3. browser starts, requests work
MockPIFrame frame = new MockPIFrame(DRIVER_URL, sessionId, "frame1");
LOGGER.debug("browser sending start message");
frame.seleniumStart();
// 4. server requests identification, asks for "getTitle"
LOGGER.debug("browser expecting getTitle command, blocking..");
frame.expectCommand("getTitle", "", "");
// 5. browser replies "selenium remote runner" to getTitle
frame.sendResult("OK,selenium remote runner");
// 6. server requests setContext
frame.expectCommand("setContext", sessionId, "");
// 7. browser replies "OK" to setContext
frame.sendResult("OK");
// 8. server replies "OK,123" to driver
driverRequest.expectResult("OK," + sessionId);
return frame;
}
/**
* create a session and issue a valid "open" command
*/
@Test
public void testRegularOpen() {
openUrl();
}
private MockPIFrame openUrl() {
MockPIFrame frame1 = startSession();
// 1. driver issues an "open" command
DriverRequest driverRequest = sendCommand("open", "blah.html", "");
// 2. original frame receives open request; replies "OK" and then closes
frame1.expectCommand("open", "blah.html", "");
frame1.sendResult("OK");
// 3. old frame unloads
frame1.sendClose();
// 4. new frame with same frame address loads and replies "START"
MockPIFrame frame2 = new MockPIFrame(DRIVER_URL, sessionId, "frame2");
frame2.seleniumStart();
// 5. server automatically begins waiting for load; requests frame2 for "getTitle"
frame2.expectCommand("getTitle", "", "");
// 6. browser replies "blah.html"
frame2.sendResult("OK,blah.html");
// 7. server replies "OK" to driver's original "open" command
driverRequest.expectResult("OK");
return frame2;
}
/**
* create a session and issue a valid open command, simulating an out-of-order response from the
* browser, as the new page load request comes in before the "OK" from the original page
*/
@Test
public void testEvilOpen() {
MockPIFrame frame1 = startSession();
// 1. driver issues an "open" command
DriverRequest driverRequest = sendCommand("open", "blah.html", "");
// 2. original frame receives open request
// ... but doesn't reply "OK" yet (this is the evil part!)
frame1.expectCommand("open", "blah.html", "");
// 3. old frame unloads; new frame with same frame address loads and replies "START"
MockPIFrame frame2 = new MockPIFrame(DRIVER_URL, sessionId, "frame2");
frame2.seleniumStart();
// X. original frame finally manages to reply "OK" to original "open" command
sleepForAtLeast(100);
frame1.sendResult("OK");
// 4. server automatically begins waiting for load; asks frame2 for "getTitle"
frame2.expectCommand("getTitle", "", "");
// 5. browser replies "blah.html"
frame2.sendResult("OK,blah.html");
// 6. server replies "OK" to driver's original "open" command
driverRequest.expectResult("OK");
}
/**
* Click, then waitForPageToLoad
*/
@Test
public void testClickThenWait() {
MockPIFrame frame1 = startSession();
DriverRequest driverRequest = sendCommand("click", "foo", "");
frame1.expectCommand("click", "foo", "");
frame1.sendResult("OK");
driverRequest.expectResult("OK");
driverRequest = sendCommand("waitForPageToLoad", "5000", "");
frame1.sendClose().expectCommand("testComplete", "", "");
MockPIFrame frame2 = new MockPIFrame(DRIVER_URL, sessionId, "frame2");
frame2.seleniumStart();
frame2.expectCommand("getTitle", "", "");
frame2.sendResult("OK,newpage.html");
driverRequest.expectResult("OK");
driverRequest = sendCommand("click", "bar", "");
frame2.expectCommand("click", "bar", "");
frame2.sendResult("OK");
driverRequest.expectResult("OK");
}
/**
* Click, then wait for page to load; but this time, frame2 starts before frame1 declares close
*/
@Test
public void testEvilClickThenWait() {
MockPIFrame frame1 = startSession();
BrowserRequest browserRequest = frame1.getMostRecentRequest();
DriverRequest driverRequest = sendCommand("click", "foo", "");
browserRequest.expectCommand("click", "foo", "");
frame1.sendResult("OK");
driverRequest.expectResult("OK");
driverRequest = sendCommand("waitForPageToLoad", "5000", "");
// this is the evil part: frame2 starts before frame1 declares close
MockPIFrame frame2 = new MockPIFrame(DRIVER_URL, sessionId, "frame2");
browserRequest = frame2.seleniumStart();
sleepForAtLeast(100);
frame1.sendClose().expectCommand("testComplete", "", "");
browserRequest.expectCommand("getTitle", "", "");
browserRequest = frame2.sendResult("OK,newpage.html");
driverRequest.expectResult("OK");
driverRequest = sendCommand("click", "bar", "");
browserRequest.expectCommand("click", "bar", "");
frame2.sendResult("OK");
driverRequest.expectResult("OK");
}
/**
* click, then wait for page to load, but frame1 may send close before sending OK result
*/
@Test
public void testEvilClickThenWaitRaceCondition() {
MockPIFrame frame1 = startSession();
BrowserRequest browserRequest = frame1.getMostRecentRequest();
DriverRequest driverRequest = sendCommand("click", "foo", "");
browserRequest.expectCommand("click", "foo", "");
// ideally, "OK" arrives first; in practice, server may handle these requests in any order
int sequenceNumber = frame1.getSequenceNumber();
frame1.setSequenceNumber(sequenceNumber + 1);
frame1.sendClose();
sleepForAtLeast(100);
frame1.setSequenceNumber(sequenceNumber);
frame1.sendResult("OK");
driverRequest.expectResult("OK");
driverRequest = sendCommand("waitForPageToLoad", "5000", "");
MockPIFrame frame2 = new MockPIFrame(DRIVER_URL, sessionId, "frame2");
browserRequest = frame2.seleniumStart();
browserRequest.expectCommand("getTitle", "", "");
browserRequest = frame2.sendResult("OK,newpage.html");
driverRequest.expectResult("OK");
driverRequest = sendCommand("click", "bar", "");
browserRequest.expectCommand("click", "bar", "");
frame2.sendResult("OK");
driverRequest.expectResult("OK");
}
/**
* Click, then sleep for a while, then send commands. We expect this to work; waitForPageToLoad
* should not be mandatory
*/
@Test
public void testClickAndPause() {
MockPIFrame frame1 = startSession();
BrowserRequest browserRequest = frame1.getMostRecentRequest();
DriverRequest driverRequest = sendCommand("click", "foo", "");
browserRequest.expectCommand("click", "foo", "");
frame1.sendResult("OK");
driverRequest.expectResult("OK");
frame1.sendClose();
MockPIFrame frame2 = new MockPIFrame(DRIVER_URL, sessionId, "frame2");
browserRequest = frame2.seleniumStart();
sleepForAtLeast(100);
driverRequest = sendCommand("click", "bar", "");
browserRequest.expectCommand("getTitle", "", "");
browserRequest = frame2.sendResult("OK,blah");
browserRequest.expectCommand("click", "bar", "");
frame2.sendResult("OK");
driverRequest.expectResult("OK");
}
/**
* Click, then sleep for a while, then start waiting for page to load. WaitForPageToLoad should
* work regardles of whether it runs before or after the page loads.
*/
@Test
public void testClickAndPauseThenWait() {
MockPIFrame frame1 = startSession();
BrowserRequest browserRequest = frame1.getMostRecentRequest();
DriverRequest driverRequest = sendCommand("click", "foo", "");
browserRequest.expectCommand("click", "foo", "");
frame1.sendResult("OK");
driverRequest.expectResult("OK");
frame1.sendClose();
MockPIFrame frame2 = new MockPIFrame(DRIVER_URL, sessionId, "frame2");
browserRequest = frame2.seleniumStart();
sleepForAtLeast(100);
driverRequest = sendCommand("waitForPageToLoad", "5000", "");
browserRequest.expectCommand("getTitle", "", "");
browserRequest = frame2.sendResult("OK,newpage.html");
driverRequest.expectResult("OK");
driverRequest = sendCommand("click", "bar", "");
browserRequest.expectCommand("click", "bar", "");
frame2.sendResult("OK");
driverRequest.expectResult("OK");
}
/**
* Click, causing a page load (i.e. close and open). Try clicking again too early; you'll get a
* WindowClosedException, even if you click more than once. Eventually the page will load and then
* clicking will work again.
*/
@Test
public void testClickForgetToWait() {
MockPIFrame frame1 = startSession();
BrowserRequest browserRequest = frame1.getMostRecentRequest();
DriverRequest driverRequest = sendCommand("click", "foo", "");
browserRequest.expectCommand("click", "foo", "");
frame1.sendResult("OK");
driverRequest.expectResult("OK");
driverRequest = sendCommand("click", "bar", "");
frame1.sendClose();
driverRequest.expectResult(WindowClosedException.WINDOW_CLOSED_ERROR);
sendCommand("click", "bar", "").expectResult(WindowClosedException.WINDOW_CLOSED_ERROR);
sendCommand("click", "bar", "").expectResult(WindowClosedException.WINDOW_CLOSED_ERROR);
MockPIFrame frame2 = new MockPIFrame(DRIVER_URL, sessionId, "frame2");
browserRequest = frame2.seleniumStart();
sleepForAtLeast(100);
driverRequest = sendCommand("click", "bar", "");
browserRequest.expectCommand("getTitle", "", "");
browserRequest = frame2.sendResult("OK,blah");
browserRequest.expectCommand("click", "bar", "");
frame2.sendResult("OK");
driverRequest.expectResult("OK");
}
/**
* Test out the retryLast logic.
*/
@Test
public void testRetryLast() throws Exception {
MockPIFrame frame = startSession();
// 1. driver requests getTitle
DriverRequest getTitle = sendCommand("getTitle", "", "");
// 2. browser receives getTitle; replies "OK,foo"
frame.expectCommand("getTitle", "", "");
frame.sendResult("OK,foo");
// 3. driver receives "OK,foo"
getTitle.expectResult("OK,foo");
// 4. browser waits around for another command that never arrives. In 10 seconds, server replies
// "retryLast"
frame.expectCommand("retryLast", "", "");
// 5. browser retries
frame.sendRetry();
// 6. driver requests click
DriverRequest click = sendCommand("click", "foo", "");
// 7. browser receives click; replies "OK"
frame.expectCommand("click", "foo", "");
frame.sendResult("OK");
// 8. server receives "OK"
click.expectResult("OK");
}
/**
* This test is fragile with respect to the length of the timeout. The FrameGroupCommandQueue,
* which provides the expected string in the last assert, does not receive the same timeout as a
* parameter as is set here. This test may need to be more explicit about which timeout is truly
* being set and testing the timeout values along the way.
*
* @throws Exception
*/
@Test
public void testSetTimeout() throws Exception {
MockPIFrame frame = startSession();
int timeout = 4000;
// 1. driver requests setTimeout, server replies "OK" without contacting the browser
sendCommand("setTimeout", "100", "").expectResult("OK");
// 2. driver requests open
DriverRequest open = sendCommand("open", "blah.html", "", timeout);
// 3. original frame receives open request; replies "OK"
frame.expectCommand("open", "blah.html", "");
frame.sendResult("OK");
// 4. normally, a new frame instance would come into existence, and
// send back a "START". But instead, too much time passes.
sleepForAtLeast(timeout);
// 5. server replies to driver with an error message
String result = open.getResult();
boolean hasTimeoutMessage = result.contains("timed out waiting for window");
assertTrue("wrong error message on timeout", hasTimeoutMessage);
}
/**
* Open a subWindow, close the subWindow, select the mainWindow, and send it a command.
*/
@Test
public void testMultiWindow() throws Exception {
MockPIFrame frame = openUrl();
MockPIFrame subWindow = openSubWindow(frame);
// Send subWindow a "close" command
DriverRequest driverRequest1 = sendCommand("close", "", "");
subWindow.expectCommand("close", "", "");
subWindow.sendResult("OK");
subWindow.sendClose();
driverRequest1.expectResult("OK");
sendCommand("selectWindow", "null", "").expectResult("OK");
DriverRequest driverRequest = sendCommand("doubleClick", "", "");
frame.expectCommand("doubleClick", "", "");
frame.sendResult("OK");
driverRequest.expectResult("OK");
}
private void sleepForAtLeast(long ms) {
if (ms > 0) {
long now = System.currentTimeMillis();
long deadline = now + ms;
while (now < deadline) {
try {
Thread.sleep(deadline - now);
now = deadline; // terminates loop
} catch (InterruptedException ie) {
now = System.currentTimeMillis();
}
}
}
}
/**
* Open a subWindow, close the subWindow, and send a command to the closed subWindow. This will
* fail; then we select the main window and send commands to it.
* <p/>
* This test passes when run singly or as part of the MockPIFrameUnitTest, but does not pass when
* run in Eclipse as part of the UnitTestSuite. Raising the timeout does not necessarily help.
* test.
*/
@Test
public void testEvilClosingWindow() throws Exception {
MockPIFrame frame = startSession();
MockPIFrame subWindow = openSubWindow(frame);
BrowserRequest mainBrowserRequest = frame.getMostRecentRequest();
// Send subWindow a "close" command
DriverRequest driverRequest = sendCommand("close", "", "");
subWindow.expectCommand("close", "", "");
subWindow.sendResult("OK");
subWindow.sendClose();
driverRequest.expectResult("OK");
// The user is SUPPOSED to selectWindow(null) here, but in this test, he forgot
// sendCommand("selectWindow", "null", "").expectResult("OK");
sendCommand("doubleClick", "", "").expectResult(WindowClosedException.WINDOW_CLOSED_ERROR);
sendCommand("doubleClick", "", "").expectResult(WindowClosedException.WINDOW_CLOSED_ERROR);
sendCommand("selectWindow", "null", "").expectResult("OK");
// sleep for a while. for evilness.
Thread.sleep(RemoteControlConfiguration.DEFAULT_RETRY_TIMEOUT_IN_SECONDS / 2);
mainBrowserRequest.expectCommand("retryLast", "", "");
mainBrowserRequest = frame.sendRetry();
// send a new command
driverRequest = sendCommand("submit", "", "");
mainBrowserRequest.expectCommand("submit", "", "");
// sleep less than the command timeout
Thread.sleep(timeoutInSeconds / 2);
mainBrowserRequest = frame.sendResult("OK");
driverRequest.expectResult("OK");
}
private MockPIFrame openSubWindow(MockPIFrame frame1) {
// Let's say this page has an "openWindow" button
// OK, let's click on it
DriverRequest driverRequest = sendCommand("click", "openWindow", "");
frame1.expectCommand("click", "openWindow", "");
frame1.sendResult("OK");
driverRequest.expectResult("OK");
// wait for subWindow to popup
driverRequest = sendCommand("waitForPopUp", "subWindow", "2000");
MockPIFrame subWindow =
new MockPIFrame(DRIVER_URL, sessionId, "subWindowId", "top", "subWindow");
subWindow.seleniumStart();
subWindow.expectCommand("getTitle", "", "");
subWindow.sendResult("OK,Sub Window");
driverRequest.expectResult("OK");
// select the subWindow
sendCommand("selectWindow", "subWindow", "").expectResult("OK");
// send the subWindow a type command
driverRequest = sendCommand("type", "subWindowLink", "foo");
subWindow.expectCommand("type", "subWindowLink", "foo");
subWindow.sendResult("OK");
driverRequest.expectResult("OK");
return subWindow;
}
/**
* Open "frames.html", which we'll imagine has two subFrames: subFrame0 and subFrame1
*
* @return a set containing a top frame and two subframes
*/
public SmallFrameSet openSubFrames() {
MockPIFrame oldFrame = startSession();
DriverRequest driverRequest = sendCommand("open", "frames.html", "");
oldFrame.expectCommand("open", "frames.html", "");
oldFrame.sendResult("OK");
oldFrame.sendClose();
MockPIFrame subFrame0 =
new MockPIFrame(DRIVER_URL, sessionId, "subFrame0Id", "top.frames[0]", "");
MockPIFrame subFrame1 =
new MockPIFrame(DRIVER_URL, sessionId, "subFrame1Id", "top.frames[1]", "");
subFrame0.seleniumStart();
subFrame1.seleniumStart();
// topFrame opens last, after his subFrames have finished loading
MockPIFrame topFrame = new MockPIFrame(DRIVER_URL, sessionId, "frameId");
topFrame.seleniumStart();
topFrame.expectCommand("getTitle", "", "");
topFrame.sendResult("OK,frames.html");
driverRequest.expectResult("OK");
SmallFrameSet set = new SmallFrameSet(topFrame, subFrame0, subFrame1);
return set;
}
/**
* Open a page that has subframes
*/
@Test
public void testSubFrames() {
openSubFrames();
}
/**
* Select a subFrame, then send an "open" command to that subFrame
*/
@Test
public void testFramesOpen() {
SmallFrameSet set = openSubFrames();
DriverRequest driverRequest = sendCommand("selectFrame", "subFrame1", "");
set.topFrame.expectCommand("getWhetherThisFrameMatchFrameExpression", "top", "subFrame1");
set.topFrame.sendResult("OK,false");
set.subFrame0.expectCommand("getWhetherThisFrameMatchFrameExpression", "top", "subFrame1");
set.subFrame0.sendResult("OK,false");
set.subFrame1.expectCommand("getWhetherThisFrameMatchFrameExpression", "top", "subFrame1");
set.subFrame1.sendResult("OK,true");
driverRequest.expectResult("OK");
driverRequest = sendCommand("open", "blah.html", "");
set.subFrame1.expectCommand("open", "blah.html", "");
set.subFrame1.sendResult("OK");
set.subFrame1.sendClose();
MockPIFrame newSubFrame1 =
new MockPIFrame(DRIVER_URL, sessionId, "newSubFrame1", "top.frames[1]", "");
newSubFrame1.seleniumStart();
newSubFrame1.expectCommand("getTitle", "", "");
newSubFrame1.sendResult("OK,blah.html");
driverRequest.expectResult("OK");
}
private class SmallFrameSet {
MockPIFrame topFrame;
MockPIFrame subFrame0;
MockPIFrame subFrame1;
public SmallFrameSet(MockPIFrame topFrame, MockPIFrame subFrame0,
MockPIFrame subFrame1) {
super();
this.topFrame = topFrame;
this.subFrame0 = subFrame0;
this.subFrame1 = subFrame1;
}
}
/**
* Try sending two commands at once
*/
@Test
@Ignore
public void testDoubleCommand() throws Exception {
MockPIFrame frame = startSession();
BrowserRequest browserRequest = frame.getMostRecentRequest();
// 1. driver requests click "foo"
DriverRequest clickFoo = sendCommand("click", "foo", "");
sleepForAtLeast(100);
// 2. before the browser can respond, driver requests click "bar"
DriverRequest clickBar = sendCommand("click", "bar", "");
browserRequest.expectCommand("click", "foo", "");
browserRequest = frame.sendResult("OK");
browserRequest.expectCommand("click", "bar", "");
frame.sendResult("OK");
assertEquals("click foo result got mangled", "OK", clickFoo.getResult());
assertEquals("click bar result got mangled", "OK", clickBar.getResult());
}
/**
* Extracts a sessionId from the DummyBrowserLauncher, so we can use it in our tests. Note that
* the original driver request won't be resolved until some MockPIFrame is launched with the new
* sessionId, so we need to extract it prior to calling getNewBrowserSession.getResult().
*
* @param getNewBrowserSession a not-yet-resolved request to get a new browser session; used to
* get an error message if we're forced to give up
* @return the sessionId of the requested session
*/
private String waitForSessionId(DriverRequest getNewBrowserSession) {
// wait until timeout
long now = System.currentTimeMillis();
long timeout = AsyncHttpRequest.DEFAULT_TIMEOUT;
long finish = now + timeout;
if (timeout == 0) {
finish = Long.MAX_VALUE;
}
sleepForAtLeast(10);
String sessionId1;
String result = null;
while (System.currentTimeMillis() < finish) {
// DummyBrowserLauncher records its sessionId in a static variable; extract it here
sessionId1 = DummyBrowserLauncher.getSessionId();
if (sessionId1 != null) {
return sessionId1;
}
if (!getNewBrowserSession.isAlive()) {
// something must have gone wrong
try {
result = getNewBrowserSession.getResult();
} catch (Exception e) {
throw new RuntimeException("sessionId never appeared", e);
}
throw new RuntimeException("sessionId never appeared, getNewBrowserSession said: " + result);
}
// The DBL must not have been launched yet; keep waiting
sleepForAtLeast(10);
}
sessionId1 = DummyBrowserLauncher.getSessionId();
if (sessionId1 != null) {
return sessionId1;
}
// sessionId never appeared; something must have gone wrong
try {
result = getNewBrowserSession.getResult();
} catch (Exception e) {
throw new RuntimeException("sessionId never appeared", e);
}
throw new RuntimeException("sessionId never appeared, getNewBrowserSession said: " + result);
}
private DriverRequest sendCommand(String cmd, String arg1, String arg2, int timeoutInMillis) {
return sendCommand(new DefaultRemoteCommand(cmd, arg1, arg2), timeoutInMillis);
}
private DriverRequest sendCommand(String cmd, String arg1, String arg2) {
return sendCommand(new DefaultRemoteCommand(cmd, arg1, arg2), AsyncHttpRequest.DEFAULT_TIMEOUT);
}
private DriverRequest sendCommand(RemoteCommand cmd, int timeoutInMillis) {
LOGGER.info("Driver sends " + cmd + " on session " + sessionId);
return DriverRequest.request(DRIVER_URL, cmd, sessionId, timeoutInMillis);
}
}
|
|
package org.opentosca.planbuilder.model.plan;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import org.apache.commons.io.FileUtils;
/*
* Taken from OpenTOSCA PlanBuilder
*/
/**
* <p>
* This class represents a WSDL v1.1. This class is mainly used for the
* BuildPlan. It uses a internal fragmented WSDL File and allows to add
* declarations at defined points. The WSDL declares a single PortType for
* invoking the BuildPlan and second for callback. Both have a single one-way
* operation defined. With the given operations of this class, the messages can
* have additional elements defined, which can be used by the plugins to fetch
* data outside of the TopoloyTemplate scope.
* </p>
* Copyright 2013 IAAS University of Stuttgart <br>
* <br>
*
* @author Kalman Kepes - [email protected]
*
*/
public class GenericWsdlWrapper {
// corresponds the processname and namespace
private final static String WSDL_NAME_TAG = "{wsdlname}";
private final static String WSDL_TARGETNAMESPACE_TAG = "{wsdltargetnamespace}";
// used for adding namespace declarations
private final static String WSDL_NAMESPACEPREFIX_TAG = "{wsdlnamespaceprefix}";
// used as tag to add partnerlinks at the right place
private final static String WSDL_PARTNERLINKS_TAG = "{wsdlpartnerlinks}";
// used as tag to add imports at the right place
private final static String WSDL_IMPORTS_TAG = "{wsdlimports}";
// used as tag to add elements to the requestmessage
private final static String WSDL_REQUESTTYPEELEMENTS_TAG = "{wsdlrequesttypeelements}";
// use as tag to add elements to the response message
private final static String WSDL_RESPONETYPEELEMENTS_TAG = "{wsdlresponsetypeelements}";
// use as tag to add propertys
private final static String WSDL_PROPERTYS_TAG = "{vprops}";
// use as tag to add propertyaliases
private final static String WSDL_PROPERTYALIAS_TAG = "{vpropaliases}";
// this holds the complete wsdl
private String genericWsdlFileAsString;
// the namespace and name of the process this wsdl belongs to
private String processName = null;
private String namespace = null;
// the names of the partnerLinkTypes this wsdl holds
private List<String> partnerLinkTypeNames;
// the localNames inside the input and output message
private List<String> inputMessageLocalNames;
private List<String> outputMessageLocalNames;
// a list of absolute locations of imported wsdl/xsd's
private List<String> absoluteLocations;
// a list of names of delcared properties
private List<String> properties;
// a map to store partnerLinks
private PltMap pltMap = new PltMap();
// counts namespaces
private int namespaceCounter = 0;
// a set of namespaces used in the wsdl
private Set<String> namespaces = new HashSet<String>();
/**
* <p>
* This class is used to map and store partnerLinks inside the
* GenericWsdlWrapper calss
* </p>
* Copyright 2013 IAAS University of Stuttgart <br>
* <br>
*
* @author nyu
*
*/
private class PltMap {
private List<String> partnerLinkTypeNames = new ArrayList<String>();
private List<String> roleNames1 = new ArrayList<String>();
private List<QName> portTypes1 = new ArrayList<QName>();
private List<String> roleNames2 = new ArrayList<String>();
private List<QName> portTypes2 = new ArrayList<QName>();
/**
* Adds a partnerLinkType to this PltMap
*
* @param partnerLinkTypeName the name of the partnerLinkType to use
* @param role1 the name of the 1st role
* @param portType1 a QName of the 1st portType
* @param role2 the name of the 2nd role
* @param portType2 a QName of the 2nd portType
* @return true iff adding was successful
*/
public boolean addPLT(String partnerLinkTypeName, String role1, QName portType1, String role2, QName portType2) {
boolean check = true;
check &= this.partnerLinkTypeNames.add(partnerLinkTypeName);
check &= this.roleNames1.add(role1);
check &= this.portTypes1.add(portType1);
check &= this.roleNames2.add(role2);
check &= this.portTypes2.add(portType2);
return check;
}
/**
* Returns the names of the partnerLinkTypes
*
* @return a List of Strings
*/
public List<String> getPartnerLinkTypeNames() {
return this.partnerLinkTypeNames;
}
/**
* Returns the 1st portType of the given partnerLinkType
*
* @param partnerLinkTypeName the name of the partnerLinkType
* @return a QName if the partnerLinkType is found, else null
*/
public QName getPortType1OfPLT(String partnerLinkTypeName) {
int pos = this.partnerLinkTypeNames.indexOf(partnerLinkTypeName);
return this.portTypes1.get(pos);
}
/**
* Returns the 2nd portType of the given partnerLinkType
*
* @param partnerLinkTypeName the name of the partnerLinkType
* @return a QName of the 2nd PortType, else null
*/
public QName getPortType2OfPLT(String partnerLinkTypeName) {
int pos = this.partnerLinkTypeNames.indexOf(partnerLinkTypeName);
QName portType = this.portTypes2.get(pos);
// check if this is a portType dummy
if (portType.getLocalPart().equals("")) {
return null;
} else {
return portType;
}
}
}
/**
* Constructor
*
* @throws IOException is thrown when reading the internal file fails
*/
public GenericWsdlWrapper() throws IOException {
URL url = getClass().getResource("genericProcessWsdl.wsdl");
File genericWsdlFile = new File(url.toString());
this.genericWsdlFileAsString = FileUtils.readFileToString(genericWsdlFile);
this.partnerLinkTypeNames = new ArrayList<String>();
this.absoluteLocations = new ArrayList<String>();
this.inputMessageLocalNames = new ArrayList<String>();
this.outputMessageLocalNames = new ArrayList<String>();
this.properties = new ArrayList<String>();
}
/**
* Returns the file name of this wsdl
*
* @return a WSDL file name as String
*/
public String getFileName() {
return this.processName + ".wsdl";
}
/**
* Returns the localNames of the Elements inside the output message of this
* wsdl
*
* @return a List of Strings
*/
public List<String> getOuputMessageLocalNames() {
return this.outputMessageLocalNames;
}
/**
* Returns the localNames of the Elements inside the input message of this
* wsdl
*
* @return a List of Strings
*/
public List<String> getInputMessageLocalNames() {
return this.inputMessageLocalNames;
}
/**
* Adds a element declaration to the input message of this wsdl
*
* @param elementName the localName of the element
* @param type the XSD type of the element
* @return true iff adding was successful
*/
public boolean addElementToRequestMessage(String elementName, QName type) {
if (!this.inputMessageLocalNames.contains(elementName)) {
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_REQUESTTYPEELEMENTS_TAG, this.generateElementString(elementName, type.getLocalPart()) + GenericWsdlWrapper.WSDL_REQUESTTYPEELEMENTS_TAG);
this.inputMessageLocalNames.add(elementName);
return true;
} else {
return false;
}
}
/**
* Adds a element declaration to the output message of this wsdl
*
* @param elementName the localName of the element
* @param type the XSD type of the element
* @return true iff adding was successful
*/
public boolean addElementToResponseMessage(String elementName, QName type) {
if (!this.outputMessageLocalNames.contains(elementName)) {
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_RESPONETYPEELEMENTS_TAG, this.generateElementString(elementName, type.getLocalPart()) + GenericWsdlWrapper.WSDL_RESPONETYPEELEMENTS_TAG);
this.outputMessageLocalNames.add(elementName);
return true;
} else {
return false;
}
}
/**
* Adds a namespace with fiven prefix to this wsdl
*
* @param namespace the namespace to add
* @param prefix the prefix for the given namespace
* @return true iff adding was successful
*/
private boolean addNamespace(String namespace, String prefix) {
if (!this.namespaces.contains(namespace)) {
this.namespaces.add(namespace);
if ((prefix == null) | prefix.equals("")) {
String nsDecl1 = "xmlns:ns" + this.namespaceCounter + "=\"" + namespace + "\" ";
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_NAMESPACEPREFIX_TAG, nsDecl1 + GenericWsdlWrapper.WSDL_NAMESPACEPREFIX_TAG);
this.namespaceCounter++;
} else {
String nsDecl2 = "xmlns:" + prefix + "=\"" + namespace + "\" ";
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_NAMESPACEPREFIX_TAG, nsDecl2 + GenericWsdlWrapper.WSDL_NAMESPACEPREFIX_TAG);
}
return true;
} else {
return false;
}
}
/**
* Adds an import element to his wsdl
*
* @param importType the type of the import (wsdl, xsd)
* @param namespace the namespace of the import
* @param prefix the prefix of namespace
* @param location the location of the import
* @return true iff adding was successful
*/
public boolean addImportElement(String importType, String namespace, String prefix, String location) {
// TODO we assume the location is absolute for packaging later this has
// to be fixed
if (this.absoluteLocations.contains(location)) {
return false;
}
String importString = this.generateImportString(importType, namespace, location);
this.absoluteLocations.add(location);
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_IMPORTS_TAG, importString + GenericWsdlWrapper.WSDL_IMPORTS_TAG);
this.addNamespace(namespace, prefix);
return true;
}
/**
* Generates a string which contains a wsdl import string
*
* @param importType the importType of the import as String
* @param namespace the namespace of the import as String
* @param location the location of the import as String
* @return a String containing an WSDL import declaration
*/
private String generateImportString(String importType, String namespace, String location) {
// FIXME ? killed importType here importType=\"" + importType + "\"
return "<import namespace=\"" + namespace + "\" location=\"" + location + "\"/>";
}
/**
* Generates a XSD element declaration as string
*
* @param name the name of the element as String
* @param type the type of the element as String
* @return a String containing a XSD declaration
*/
private String generateElementString(String name, String type) {
return "<element name=\"" + name + "\" " + "type=\"" + type + "\"/>";
}
/**
* Sets the id of this WSDL
*
* @param namespace the namespace of the WSDL to set
* @param name the name of the WSDL to set
*/
public void setId(String namespace, String name) {
if (this.processName == null) {
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_NAME_TAG, name);
} else {
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(this.processName, name);
}
this.processName = name;
if (this.namespace == null) {
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_TARGETNAMESPACE_TAG, namespace);
} else {
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(this.namespace, namespace);
}
this.namespace = namespace;
}
/**
* Returns the targetNamespace of this WSDL
*
* @return a String containing the targetNamespace of this WSDL
*/
public String getTargetNamespace() {
return this.namespace;
}
/**
* Returns the localName of the Response message this WSDL
*
* @return a String containing the localName of the Response message
*/
public String getResponseMessageLocalName() {
return this.processName + "Response";
}
/**
* Returns the localName of the Request message this WSDL
*
* @return a String containing the localName of the Request message
*/
public String getRequestMessageLocalName() {
return this.processName + "Request";
}
/**
* Adds a partnerLinkType to this WSDL
*
* @param partnerLinkTypeName the name of partnerLinkType
* @param roleName the name of the 1st role
* @param portType the portType of the partner
* @return true iff adding the partnerLinkType was successful
*/
public boolean addPartnerLinkType(String partnerLinkTypeName, String roleName, QName portType) {
if (this.isPartnerLinkTypeNameAlreadyUsed(partnerLinkTypeName)) {
return false;
} else {
// replace the tag with new partnerlinktype+tag, for adding other
// partnerlinks later
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_PARTNERLINKS_TAG, this.generatePartnerLinkTypeString(partnerLinkTypeName, roleName, portType) + GenericWsdlWrapper.WSDL_PARTNERLINKS_TAG);
}
this.partnerLinkTypeNames.add(partnerLinkTypeName);
this.pltMap.addPLT(partnerLinkTypeName, roleName, portType, "", new QName(""));
this.addNamespace(portType.getNamespaceURI(), portType.getPrefix());
return true;
}
/**
* Adds a partnerLinkType to this WSDL
*
* @param partnerLinkTypeName the name of the partnerLinkType
* @param roleName1 the name of the 1st role
* @param portType1 the portType of the 1st role
* @param roleName2 the name of the 2nd role
* @param portType2 the portType of the 2nd role
* @return true iff adding was successful
*/
public boolean addPartnerLinkType(String partnerLinkTypeName, String roleName1, QName portType1, String roleName2, QName portType2) {
if (this.isPartnerLinkTypeNameAlreadyUsed(partnerLinkTypeName)) {
return false;
} else {
// replace the tag with new partnerlinktype+tag, for adding other
// partnerlinks later
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_PARTNERLINKS_TAG, this.generatePartnerLinkTypeString(partnerLinkTypeName, roleName1, portType1, roleName2, portType2) + GenericWsdlWrapper.WSDL_PARTNERLINKS_TAG);
}
this.partnerLinkTypeNames.add(partnerLinkTypeName);
this.pltMap.addPLT(partnerLinkTypeName, roleName1, portType1, roleName2, portType2);
this.addNamespace(portType1.getNamespaceURI(), portType1.getPrefix());
this.addNamespace(portType2.getNamespaceURI(), portType2.getPrefix());
return true;
}
/**
* Returns the names of all registered partnerLinkTypes in this WSDL
*
* @return a List of Strings containing the names of the partnerLinkTypes
*/
public List<String> getPartnerlinkTypeNames() {
return this.pltMap.getPartnerLinkTypeNames();
}
/**
* Returns the QName of the 1st portType for the given partnerLinkType name
*
* @param partnerLinkTypeName the name of the partnerLinkType
* @return a QName representing the 1st portType of the partnerLinkType,
* else null
*/
public QName getPortType1FromPartnerLinkType(String partnerLinkTypeName) {
return this.pltMap.getPortType1OfPLT(partnerLinkTypeName);
}
/**
* Adds a property declaration to this WSDL
*
* @param propertyName the name of the property
* @param type the type of the property
* @return true iff adding was succesful
*/
public boolean addProperty(String propertyName, QName type) {
if (this.properties.contains(propertyName)) {
return false;
}
this.addNamespace(type.getNamespaceURI(), type.getPrefix());
String property = this.generatePropertyString(propertyName, type);
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_PROPERTYS_TAG, property + GenericWsdlWrapper.WSDL_PROPERTYS_TAG);
return true;
}
/**
* Adds a propertyAlias to this WSDL for the given property
*
* @param propertyName the name of the property the propertyAlias should
* belong to
* @param partName the name of the message part
* @param messageType the type of the message
* @param query a XPath Query
* @return true iff adding was successful
*/
public boolean addPropertyAlias(String propertyName, String partName, QName messageType, String query) {
this.addNamespace(messageType.getNamespaceURI(), messageType.getPrefix());
String propertyAlias = this.generatePropertyAliasString(propertyName, partName, messageType, query);
this.genericWsdlFileAsString = this.genericWsdlFileAsString.replace(GenericWsdlWrapper.WSDL_PROPERTYALIAS_TAG, propertyAlias + GenericWsdlWrapper.WSDL_PROPERTYALIAS_TAG);
return true;
}
/**
* Returns the 2nd portType of referenced partnerLinkType
*
* @param partnerLinkTypeName the name of a partnerLinkType
* @return a QName representing the 2nd portType, else null
*/
public QName getPortType2FromPartnerLinkType(String partnerLinkTypeName) {
return this.pltMap.getPortType2OfPLT(partnerLinkTypeName);
}
/**
* Generates a String which contains a property declaration
*
* @param propertyName the name of the property
* @param type the type of the property
* @return a String containing a property declaration
*/
private String generatePropertyString(String propertyName, QName type) {
// <vprop:property name="createEC2InstanceCorrelationID"
// type="xsd:string"/>
return "<vprop:property name=\"" + propertyName + "\" type=\"" + type.getPrefix() + ":" + type.getLocalPart() + "\"/>";
}
/**
* Generates a String which contains a propertyAlias declaration
*
* @param propertyName the name of the property the propertyAlias should
* belong to
* @param partName the part name of the message the propertyAlias should
* reference
* @param messageType the type of the message the propertyAlias should
* reference
* @param query a XPath query which the propertyAlias should use
* @return a String containing a propertyAlias declaration
*/
private String generatePropertyAliasString(String propertyName, String partName, QName messageType, String query) {
// <vprop:propertyAlias messageType="wsdl:createEC2InstanceResponse"
// part="parameters" propertyName="tns:createEC2InstanceCorrelationID">
// <vprop:query><![CDATA[/wsdl:CorrelationId]]></vprop:query>
// </vprop:propertyAlias>
return "<vprop:propertyAlias messageType=\"" + messageType.getPrefix() + ":" + messageType.getLocalPart() + "\" part=\"" + partName + "\" propertyName=\"tns:" + propertyName + "\"><vprop:query><![CDATA[" + query + "]]></vprop:query></vprop:propertyAlias>";
}
/**
* Generates a String containing a partnerLinkType declaration with one
* portType
*
* @param partnerLinkTypeName the name for the partnerLinkType
* @param roleName the name for the role
* @param portType a QName for the portType
* @return a String containing a partnerLinkType declaration
*/
private String generatePartnerLinkTypeString(String partnerLinkTypeName, String roleName, QName portType) {
return "<plnk:partnerLinkType name=\"" + partnerLinkTypeName + "\"><plnk:role name=\"" + roleName + "\" portType=\"" + portType.getPrefix() + ":" + portType.getLocalPart() + "\"/></plnk:partnerLinkType>";
}
/**
* Generates a String containing a partnerLinkType declaration with two
* roles
*
* @param partnerLinkTypeName the name of the partnerLinkType
* @param roleName1 the name of the 1st role
* @param portType1 a QName of a portType for the 1st role
* @param roleName2 the name of the 2nd role
* @param portType2 a QName of a portType for the 2nd role
* @return a String containing a partnerLinkType declaration with 2 roles
*/
private String generatePartnerLinkTypeString(String partnerLinkTypeName, String roleName1, QName portType1, String roleName2, QName portType2) {
return "<plnk:partnerLinkType name=\"" + partnerLinkTypeName + "\"><plnk:role name=\"" + roleName1 + "\" portType=\"" + portType1.getPrefix() + ":" + portType1.getLocalPart() + "\"/><plnk:role name=\"" + roleName2 + "\" portType=\"" + portType2.getPrefix() + ":" + portType2.getLocalPart() + "\"/></plnk:partnerLinkType>";
}
/**
* Checks whether the given partnerLinkType name is already in use
*
* @param partnerLinkTypeName a String
* @return true if the given String is already used as partnerLinkType name,
* else false
*/
private boolean isPartnerLinkTypeNameAlreadyUsed(String partnerLinkTypeName) {
return this.partnerLinkTypeNames.contains(partnerLinkTypeName);
}
/**
* Returns a representation of this WSDL as String.
*
* @return a String containing a complete WSDL definition document
*/
public String getFinalizedWsdlAsString() {
String wsdlString = this.genericWsdlFileAsString;
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_IMPORTS_TAG, "");
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_NAMESPACEPREFIX_TAG, "");
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_NAME_TAG, "");
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_PARTNERLINKS_TAG, "");
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_REQUESTTYPEELEMENTS_TAG, "");
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_PROPERTYS_TAG, "");
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_PROPERTYALIAS_TAG, "");
if (this.outputMessageLocalNames.size() == 0) {
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_RESPONETYPEELEMENTS_TAG, "<any minOccurs=\"0\"/>");
} else {
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_RESPONETYPEELEMENTS_TAG, "");
}
wsdlString = wsdlString.replace(GenericWsdlWrapper.WSDL_TARGETNAMESPACE_TAG, "");
// change absolute locations to relative
for (String absolutePath : this.absoluteLocations) {
wsdlString = wsdlString.replace(absolutePath, new File(absolutePath).getName());
}
return wsdlString;
}
/**
* Checks whether the QName with the given location is already imported
* inside this wsdl
*
* @param qName a QName
* @param absolutePath a location where the QName is defined
* @return true iff the given QName is already imported inside this WSDL
*/
public boolean isImported(QName qName, String absolutePath) {
boolean check = true;
check &= this.absoluteLocations.contains(absolutePath);
check &= this.namespaces.contains(qName.getNamespaceURI());
return check;
}
}
|
|
/*
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.ocs.dynamo.ui.component;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.ArrayUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.ocs.dynamo.dao.FetchJoinInformation;
import com.ocs.dynamo.domain.AbstractEntity;
import com.ocs.dynamo.domain.model.AttributeModel;
import com.ocs.dynamo.domain.model.EntityModel;
import com.ocs.dynamo.service.BaseService;
import com.ocs.dynamo.ui.composite.dialog.ModelBasedSearchDialog;
import com.ocs.dynamo.ui.utils.VaadinUtils;
import com.ocs.dynamo.util.SystemPropertyUtils;
import com.ocs.dynamo.utils.EntityModelUtils;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.data.provider.SortOrder;
import com.vaadin.flow.function.SerializablePredicate;
/**
* A composite component that displays a selected entity and offers a search
* dialog to search for another one
*
* @author bas.rutten
* @param <ID> the type of the primary key
* @param <T> the type of the entity
*/
public class EntityLookupField<ID extends Serializable, T extends AbstractEntity<ID>> extends QuickAddEntityField<ID, T, Object> {
private static final long serialVersionUID = 5377765863515463622L;
/**
* Whether the component is inside a grid
*/
private boolean grid;
/**
* Whether direct navigation via internal link is allowed
*/
private boolean directNavigationAllowed;
/**
* Indicates whether it is allowed to clear the selection
*/
private boolean clearAllowed;
/**
* Indicates whether it is allowed to add items
*/
private boolean addAllowed;
/**
* The button used to clear the current selection
*/
private Button clearButton;
/**
* The joins to apply to the search in the search dialog
*/
private FetchJoinInformation[] joins;
/**
* The label that displays the currently selected item
*/
private Span label;
/**
* Whether the component allows multiple select
*/
private boolean multiSelect;
/**
* The button that brings up the search dialog
*/
private Button selectButton;
/**
* The sort order to apply to the search dialog
*/
private List<SortOrder<?>> sortOrders = new ArrayList<>();
/**
* The current value of the component. This can either be a single item or a set
*/
private Object value;
/**
* Constructor
*
* @param service the service used to query the database
* @param entityModel the entity model
* @param attributeModel the attribute mode
* @param filter the filter to apply when searching
* @param search whether the component is used in a search screen
* @param sortOrders the sort order
* @param joins the joins to use when fetching data when filling the
* pop-up dialog
*/
public EntityLookupField(BaseService<ID, T> service, EntityModel<T> entityModel, AttributeModel attributeModel,
SerializablePredicate<T> filter, boolean search, boolean multiSelect, boolean grid, List<SortOrder<?>> sortOrders,
FetchJoinInformation... joins) {
super(service, entityModel, attributeModel, filter);
this.sortOrders = sortOrders != null ? sortOrders : new ArrayList<>();
this.joins = joins;
this.multiSelect = multiSelect;
this.clearAllowed = true;
this.addAllowed = !search && (attributeModel != null && attributeModel.isQuickAddAllowed());
this.directNavigationAllowed = !search && (attributeModel != null && attributeModel.isNavigable());
this.grid = grid;
initContent();
}
/**
* Adds additional fetch joins
*
* @param fetchJoinInformation the joins to add
*/
public void addFetchJoinInformation(FetchJoinInformation... fetchJoinInformation) {
joins = ArrayUtils.addAll(joins, fetchJoinInformation);
}
/**
* Adds a sort order
*
* @param sortOrder the sort order to add
*/
public void addSortOrder(SortOrder<T> sortOrder) {
this.sortOrders.add(sortOrder);
}
@Override
@SuppressWarnings("unchecked")
protected void afterNewEntityAdded(T entity) {
if (multiSelect) {
if (getValue() == null) {
// create new collection
setValue(Lists.newArrayList(entity));
} else {
// add new entity to existing collection
Collection<T> col = (Collection<T>) getValue();
col.add(entity);
setValue(col);
}
} else {
setValue(entity);
}
}
public Button getClearButton() {
return clearButton;
}
protected FetchJoinInformation[] getJoins() {
return joins;
}
/**
* Gets the value that must be displayed on the label that shows which items are
* currently selected
*
* @param newValue the new value
* @return
*/
@SuppressWarnings("unchecked")
protected String constructLabelValue(Object newValue) {
String caption = getMessageService().getMessage("ocs.no.item.selected", VaadinUtils.getLocale());
if (newValue instanceof Collection<?>) {
Collection<T> col = (Collection<T>) newValue;
if (!col.isEmpty()) {
caption = EntityModelUtils.getDisplayPropertyValue(col, getEntityModel(), SystemPropertyUtils.getLookupFieldMaxItems(),
getMessageService(), VaadinUtils.getLocale());
}
} else {
// just a single value
T t = (T) newValue;
if (newValue != null) {
caption = EntityModelUtils.getDisplayPropertyValue(t, getEntityModel());
}
}
return caption;
}
public Button getSelectButton() {
return selectButton;
}
public List<SortOrder<?>> getSortOrders() {
return Collections.unmodifiableList(sortOrders);
}
@Override
public Object getValue() {
return convertToCorrectCollection(value);
}
protected void initContent() {
HorizontalLayout bar = new HorizontalLayout();
if (this.getAttributeModel() != null) {
this.setLabel(getAttributeModel().getDisplayName(VaadinUtils.getLocale()));
}
// label for displaying selected values
label = new Span("");
updateLabel(getValue());
bar.add(label);
// button for selecting an entity - brings up the search dialog
selectButton = new Button(grid ? "" : getMessageService().getMessage("ocs.select", VaadinUtils.getLocale()));
selectButton.setIcon(VaadinIcon.SEARCH.create());
selectButton.addClickListener(event -> {
List<SerializablePredicate<T>> filterList = new ArrayList<>();
if (getFilter() != null) {
filterList.add(getFilter());
}
if (getAdditionalFilter() != null) {
filterList.add(getAdditionalFilter());
}
ModelBasedSearchDialog<ID, T> dialog = new ModelBasedSearchDialog<ID, T>(getService(), getEntityModel(), filterList, sortOrders,
multiSelect, true, getJoins()) {
private static final long serialVersionUID = -3432107069929941520L;
@Override
protected boolean doClose() {
if (multiSelect) {
if (EntityLookupField.this.getValue() == null) {
EntityLookupField.this.setValue(getSelectedItems());
} else {
// add selected items to already selected items
@SuppressWarnings("unchecked")
Collection<T> cumulative = (Collection<T>) EntityLookupField.this.getValue();
cumulative.addAll(getSelectedItems());
EntityLookupField.this.setValue(cumulative);
}
} else {
// single value select
EntityLookupField.this.setValue(getSelectedItem());
}
return true;
}
};
dialog.build();
selectValuesInDialog(dialog);
dialog.open();
});
bar.add(selectButton);
// button for clearing the current selection
if (clearAllowed) {
clearButton = new Button(grid ? "" : getMessageService().getMessage("ocs.clear", VaadinUtils.getLocale()));
clearButton.setIcon(VaadinIcon.ERASER.create());
clearButton.addClickListener(event -> clearValue());
bar.add(clearButton);
}
// quick add button
if (addAllowed) {
Button addButton = constructAddButton();
bar.add(addButton);
}
// direct navigation link
if (directNavigationAllowed) {
Button directNavigationButton = constructDirectNavigationButton();
bar.add(directNavigationButton);
}
bar.setSizeFull();
add(bar);
}
protected boolean isAddAllowed() {
return addAllowed;
}
protected boolean isClearAllowed() {
return clearAllowed;
}
protected boolean isDirectNavigationAllowed() {
return directNavigationAllowed;
}
@Override
public void refresh(SerializablePredicate<T> filter) {
setFilter(filter);
}
/**
* Makes sure any currently selected values are highlighted in the search dialog
*
* @param dialog the dialog
*/
@SuppressWarnings("unchecked")
public void selectValuesInDialog(ModelBasedSearchDialog<ID, T> dialog) {
// select any previously selected values in the dialog
if (multiSelect && getValue() != null && getValue() instanceof Collection) {
Collection<T> col = (Collection<T>) getValue();
dialog.select(col);
}
}
protected void setAddAllowed(boolean addAllowed) {
this.addAllowed = addAllowed;
}
@Override
public void setAdditionalFilter(SerializablePredicate<T> additionalFilter) {
setValue(null);
super.setAdditionalFilter(additionalFilter);
}
protected void setClearAllowed(boolean clearAllowed) {
this.clearAllowed = clearAllowed;
}
protected void setDirectNavigationAllowed(boolean directNavigationAllowed) {
this.directNavigationAllowed = directNavigationAllowed;
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (selectButton != null) {
selectButton.setEnabled(enabled);
if (getClearButton() != null) {
getClearButton().setEnabled(enabled);
}
if (getAddButton() != null) {
getAddButton().setEnabled(enabled);
}
}
}
public void clearValue() {
if (Set.class.isAssignableFrom(getAttributeModel().getType())) {
setValue(Sets.newHashSet());
} else if (List.class.isAssignableFrom(getAttributeModel().getType())) {
setValue(Lists.newArrayList());
} else {
setValue(null);
}
}
@Override
@SuppressWarnings("unchecked")
public void setValue(Object value) {
if (value == null) {
super.setValue(null);
} else if (Set.class.isAssignableFrom(getAttributeModel().getType())) {
Collection<T> col = (Collection<T>) value;
super.setValue(Sets.newHashSet(col));
} else if (List.class.isAssignableFrom(getAttributeModel().getType())) {
Collection<T> col = (Collection<T>) value;
super.setValue(Lists.newArrayList(col));
} else {
super.setValue(value);
}
updateLabel(value);
}
/**
* Updates the value that is displayed in the label
*
* @param newValue the new value
*/
private void updateLabel(Object newValue) {
if (label != null) {
String caption = constructLabelValue(newValue);
label.setText(caption);
}
}
@Override
public void setPlaceholder(String placeholder) {
// do nothing
}
@Override
protected Object generateModelValue() {
return convertToCorrectCollection(value);
}
@Override
protected void setPresentationValue(Object value) {
this.value = value;
updateLabel(value);
}
}
|
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.discovery;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.coordination.Coordinator;
import org.elasticsearch.cluster.coordination.FollowersChecker;
import org.elasticsearch.cluster.coordination.LeaderChecker;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.disruption.LongGCDisruption;
import org.elasticsearch.test.disruption.NetworkDisruption;
import org.elasticsearch.test.disruption.NetworkDisruption.NetworkLinkDisruptionType;
import org.elasticsearch.test.disruption.NetworkDisruption.TwoPartitions;
import org.elasticsearch.test.disruption.SingleNodeDisruption;
import org.elasticsearch.test.transport.MockTransportService;
import java.util.ArrayList;
import java.util.Arrays;
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.Objects;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static java.util.Collections.singleton;
import static org.hamcrest.Matchers.equalTo;
/**
* Tests relating to the loss of the master, but which work with the default fault detection settings which are rather lenient and will
* not detect a master failure too quickly.
*/
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0)
public class StableMasterDisruptionIT extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Collections.singletonList(MockTransportService.TestPlugin.class);
}
/**
* Test that no split brain occurs under partial network partition. See https://github.com/elastic/elasticsearch/issues/2488
*/
public void testFailWithMinimumMasterNodesConfigured() throws Exception {
List<String> nodes = internalCluster().startNodes(3);
ensureStableCluster(3);
// Figure out what is the elected master node
final String masterNode = internalCluster().getMasterName();
logger.info("---> legit elected master node={}", masterNode);
// Pick a node that isn't the elected master.
Set<String> nonMasters = new HashSet<>(nodes);
nonMasters.remove(masterNode);
final String unluckyNode = randomFrom(nonMasters.toArray(Strings.EMPTY_ARRAY));
// Simulate a network issue between the unlucky node and elected master node in both directions.
NetworkDisruption networkDisconnect =
new NetworkDisruption(new NetworkDisruption.TwoPartitions(masterNode, unluckyNode), NetworkDisruption.DISCONNECT);
setDisruptionScheme(networkDisconnect);
networkDisconnect.startDisrupting();
// Wait until elected master has removed that the unlucky node...
ensureStableCluster(2, masterNode);
// The unlucky node must report *no* master node, since it can't connect to master and in fact it should
// continuously ping until network failures have been resolved. However
// It may a take a bit before the node detects it has been cut off from the elected master
ensureNoMaster(unluckyNode);
networkDisconnect.stopDisrupting();
// Wait until the master node sees all 3 nodes again.
ensureStableCluster(3);
// The elected master shouldn't have changed, since the unlucky node never could have elected itself as master
assertThat(internalCluster().getMasterName(), equalTo(masterNode));
}
private void ensureNoMaster(String node) throws Exception {
assertBusy(() -> assertNull(client(node).admin().cluster().state(
new ClusterStateRequest().local(true)).get().getState().nodes().getMasterNode()));
}
/**
* Verify that nodes fault detection detects a disconnected node after master reelection
*/
public void testFollowerCheckerDetectsDisconnectedNodeAfterMasterReelection() throws Exception {
testFollowerCheckerAfterMasterReelection(NetworkDisruption.DISCONNECT, Settings.EMPTY);
}
/**
* Verify that nodes fault detection detects an unresponsive node after master reelection
*/
public void testFollowerCheckerDetectsUnresponsiveNodeAfterMasterReelection() throws Exception {
testFollowerCheckerAfterMasterReelection(NetworkDisruption.UNRESPONSIVE, Settings.builder()
.put(LeaderChecker.LEADER_CHECK_TIMEOUT_SETTING.getKey(), "1s")
.put(LeaderChecker.LEADER_CHECK_RETRY_COUNT_SETTING.getKey(), "4")
.put(FollowersChecker.FOLLOWER_CHECK_TIMEOUT_SETTING.getKey(), "1s")
.put(FollowersChecker.FOLLOWER_CHECK_RETRY_COUNT_SETTING.getKey(), 1).build());
}
private void testFollowerCheckerAfterMasterReelection(NetworkLinkDisruptionType networkLinkDisruptionType,
Settings settings) throws Exception {
internalCluster().startNodes(4, settings);
ensureStableCluster(4);
logger.info("--> stopping current master");
internalCluster().stopCurrentMasterNode();
ensureStableCluster(3);
final String master = internalCluster().getMasterName();
final List<String> nonMasters = Arrays.stream(internalCluster().getNodeNames()).filter(n -> master.equals(n) == false)
.collect(Collectors.toList());
final String isolatedNode = randomFrom(nonMasters);
final String otherNode = nonMasters.get(nonMasters.get(0).equals(isolatedNode) ? 1 : 0);
logger.info("--> isolating [{}]", isolatedNode);
final NetworkDisruption networkDisruption = new NetworkDisruption(new TwoPartitions(
singleton(isolatedNode), Sets.newHashSet(master, otherNode)), networkLinkDisruptionType);
setDisruptionScheme(networkDisruption);
networkDisruption.startDisrupting();
logger.info("--> waiting for master to remove it");
ensureStableCluster(2, master);
ensureNoMaster(isolatedNode);
networkDisruption.stopDisrupting();
ensureStableCluster(3);
}
/**
* Tests that emulates a frozen elected master node that unfreezes and pushes its cluster state to other nodes that already are
* following another elected master node. These nodes should reject this cluster state and prevent them from following the stale master.
*/
public void testStaleMasterNotHijackingMajority() throws Exception {
final List<String> nodes = internalCluster().startNodes(3, Settings.builder()
.put(LeaderChecker.LEADER_CHECK_TIMEOUT_SETTING.getKey(), "1s")
.put(Coordinator.PUBLISH_TIMEOUT_SETTING.getKey(), "1s")
.build());
ensureStableCluster(3);
// Save the current master node as old master node, because that node will get frozen
final String oldMasterNode = internalCluster().getMasterName();
// Simulating a painful gc by suspending all threads for a long time on the current elected master node.
SingleNodeDisruption masterNodeDisruption = new LongGCDisruption(random(), oldMasterNode);
// Save the majority side
final List<String> majoritySide = new ArrayList<>(nodes);
majoritySide.remove(oldMasterNode);
// Keeps track of the previous and current master when a master node transition took place on each node on the majority side:
final Map<String, List<Tuple<String, String>>> masters = Collections.synchronizedMap(new HashMap<>());
for (final String node : majoritySide) {
masters.put(node, new ArrayList<>());
internalCluster().getInstance(ClusterService.class, node).addListener(event -> {
DiscoveryNode previousMaster = event.previousState().nodes().getMasterNode();
DiscoveryNode currentMaster = event.state().nodes().getMasterNode();
if (!Objects.equals(previousMaster, currentMaster)) {
logger.info("--> node {} received new cluster state: {} \n and had previous cluster state: {}", node, event.state(),
event.previousState());
String previousMasterNodeName = previousMaster != null ? previousMaster.getName() : null;
String currentMasterNodeName = currentMaster != null ? currentMaster.getName() : null;
masters.get(node).add(new Tuple<>(previousMasterNodeName, currentMasterNodeName));
}
});
}
final CountDownLatch oldMasterNodeSteppedDown = new CountDownLatch(1);
internalCluster().getInstance(ClusterService.class, oldMasterNode).addListener(event -> {
if (event.state().nodes().getMasterNodeId() == null) {
oldMasterNodeSteppedDown.countDown();
}
});
internalCluster().setDisruptionScheme(masterNodeDisruption);
logger.info("--> freezing node [{}]", oldMasterNode);
masterNodeDisruption.startDisrupting();
// Wait for majority side to elect a new master
assertBusy(() -> {
for (final Map.Entry<String, List<Tuple<String, String>>> entry : masters.entrySet()) {
final List<Tuple<String, String>> transitions = entry.getValue();
assertTrue(entry.getKey() + ": " + transitions,
transitions.stream().anyMatch(transition -> transition.v2() != null));
}
});
// The old master node is frozen, but here we submit a cluster state update task that doesn't get executed, but will be queued and
// once the old master node un-freezes it gets executed. The old master node will send this update + the cluster state where it is
// flagged as master to the other nodes that follow the new master. These nodes should ignore this update.
internalCluster().getInstance(ClusterService.class, oldMasterNode).submitStateUpdateTask("sneaky-update", new
ClusterStateUpdateTask(Priority.IMMEDIATE) {
@Override
public ClusterState execute(ClusterState currentState) {
return ClusterState.builder(currentState).build();
}
@Override
public void onFailure(String source, Exception e) {
logger.warn(() -> new ParameterizedMessage("failure [{}]", source), e);
}
});
// Save the new elected master node
final String newMasterNode = internalCluster().getMasterName(majoritySide.get(0));
logger.info("--> new detected master node [{}]", newMasterNode);
// Stop disruption
logger.info("--> unfreezing node [{}]", oldMasterNode);
masterNodeDisruption.stopDisrupting();
oldMasterNodeSteppedDown.await(30, TimeUnit.SECONDS);
logger.info("--> [{}] stepped down as master", oldMasterNode);
ensureStableCluster(3);
assertThat(masters.size(), equalTo(2));
for (Map.Entry<String, List<Tuple<String, String>>> entry : masters.entrySet()) {
String nodeName = entry.getKey();
List<Tuple<String, String>> transitions = entry.getValue();
assertTrue("[" + nodeName + "] should not apply state from old master [" + oldMasterNode + "] but it did: " + transitions,
transitions.stream().noneMatch(t -> oldMasterNode.equals(t.v2())));
}
}
}
|
|
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved.
*
*/
package com.sleepycat.je.rep.impl.node;
import java.util.logging.Logger;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Durability.ReplicaAckPolicy;
import com.sleepycat.je.rep.InsufficientAcksException;
import com.sleepycat.je.rep.InsufficientReplicasException;
import com.sleepycat.je.rep.arbitration.Arbiter;
import com.sleepycat.je.rep.impl.RepImpl;
import com.sleepycat.je.rep.stream.FeederTxns;
import com.sleepycat.je.rep.txn.MasterTxn;
import com.sleepycat.je.utilint.LoggerUtils;
/**
*/
public class DurabilityQuorum {
private final RepImpl repImpl;
private final Logger logger;
public DurabilityQuorum(RepImpl repImpl) {
this.repImpl = repImpl;
logger = LoggerUtils.getLogger(getClass());
}
/**
* See if there are a sufficient number of replicas alive to support
* the commit for this transaction. Used as an optimizing step before any
* writes are executed, to reduce the number of outstanding writes that
* suffer from insufficient ack problems.
*
* If this node is not the master, just return. A different kind of check
* will catch the fact that this node cannot support writes.
*
* TODO: Read only transactions on the master should not have to wait.
* In the future, introduce either a read-only attribute as part of
* TransactionConfig or a read only transaction class to optimize this.
*
* @param insufficientReplicasTimeout timeout in ms
* @throws InsufficientReplicasException if there are not enough replicas
* connected to this feeder to be able to commit the transaction.
*/
public void ensureReplicasForCommit(MasterTxn txn,
int insufficientReplicasTimeout)
throws DatabaseException, InterruptedException,
InsufficientReplicasException {
RepNode repNode = repImpl.getRepNode();
if (!repNode.isMaster()) {
return;
}
ReplicaAckPolicy ackPolicy =
txn.getDefaultDurability().getReplicaAck();
int requiredReplicaAckCount = getCurrentRequiredAckCount(ackPolicy);
LoggerUtils.fine(logger, repImpl, "Txn " + txn + ": checking that " +
requiredReplicaAckCount +
" feeders exist before starting commit");
/* No need to wait for anyone else, only this node is needed. */
if (requiredReplicaAckCount == 0) {
return;
}
if (repNode.feederManager().awaitFeederReplicaConnections
(requiredReplicaAckCount, insufficientReplicasTimeout)) {
/* Wait was successful */
return;
}
/* Timed out, not enough replicas connected */
if (!repNode.isMaster()) {
/*
* Continue if we are no longer the master after the wait. The
* transaction will fail if it tries to acquire write locks, or
* at commit.
*/
return;
}
if (repNode.getArbiter().activateArbitration()) {
return;
}
throw new InsufficientReplicasException
(txn, ackPolicy, requiredReplicaAckCount + 1,
repNode.feederManager().activeReplicas());
}
/**
* Apply any situational requirements
* regarding replication group composition or arbitration state to
* determine whether the incoming ack should be counted against the
* durability requirements or not.
* TODO: add parameters to indicate the source of the ack.
* @param txnId currently unused, will be used when there is more specific
* filtering of incoming acknowledgments.
*/
public boolean ackQualifies(long txnId) {
return true;
}
/**
* Determine if this transaction has been adequately acknowledged.
*
* @throws InsufficientAcksException if the transaction's durability
* requirements have not been met.
*/
public void ensureSufficientAcks(FeederTxns.TxnInfo txnInfo,
int timeoutMs)
throws InsufficientAcksException {
int pendingAcks = txnInfo.getPendingAcks();
if (pendingAcks == 0) {
return;
}
MasterTxn txn = txnInfo.getTxn();
final int requiredAcks = getCurrentRequiredAckCount
(txn.getCommitDurability().getReplicaAck());
int requiredAckDelta = txn.getRequiredAckCount() - requiredAcks;
if (requiredAckDelta >= pendingAcks) {
/*
* The group size was reduced while waiting for acks and the
* acks received are sufficient given the new reduced group
* size.
*/
return;
}
/* Snapshot the state to be used in the error message */
final String dumpState = repImpl.dumpFeederState();
/*
* Repeat the check to ensure that acks have not been received in
* the time between the completion of the await() call above and
* the creation of the exception message. This tends to happen when
* there are lots of threads in the process thus potentially
* delaying the resumption of this thread following the timeout
* resulting from the await.
*/
final FeederManager feederManager =
repImpl.getRepNode().feederManager();
int currentFeederCount =
feederManager.getNumCurrentAckFeeders(txn.getCommitVLSN());
if (currentFeederCount >= requiredAcks) {
String msg = "txn " + txn.getId() +
" commit vlsn:" + txnInfo.getCommitVLSN() +
" acknowledged after explicit feeder check" +
" latch count:" + txnInfo.getPendingAcks() +
" state:" + dumpState +
" required acks:" + requiredAcks;
LoggerUtils.info(logger, repImpl, msg);
return;
}
/*
* We can avoid the exception if it's possible for this node to enter
* activate arbitration. It's useful to check for this again here in
* case we happen to lose connections to replicas in the (brief)
* period since the pre-log hook. Note that in this case we merely
* want to check; we don't want to switch into active arbitration
* unless/until we actually lose the connection to the replica at
* commit time. TODO: this doesn't seem right! Shouldn't we require
* activation at this point!!!
*/
if (repImpl.getRepNode().getArbiter().activationPossible()) {
return;
}
throw new InsufficientAcksException(txn, pendingAcks, timeoutMs,
dumpState);
}
/**
* Returns the minimum number of acknowledgments required to satisfy the
* ReplicaAckPolicy for a given group size. Does not include the master.
* The method factors in considerations like the current arbitration status
* of the environment and the composition of the replication group.
*
* TODO: it seems sufficient to return a number, as opposed to a set of
* qualified ack nodes, as long as {@link #ackQualifies} will only count
* qualified acks against the required count. That does mean that
* getCurrentRequiredAckCount and noteReplicaAcks for a transaction must be
* kept consistent.
*
* @return the number of nodes that are needed, not including the master.
*/
public int getCurrentRequiredAckCount(ReplicaAckPolicy ackPolicy) {
/*
* If the electableGroupSizeOverride is determining the size of the
* election quorum, let it also influence the durability quorum.
*/
RepNode repNode = repImpl.getRepNode();
int electableGroupSizeOverride =
repNode.getElectionQuorum().getElectableGroupSizeOverride();
if (electableGroupSizeOverride > 0) {
/*
* Use the override-defined group size to determine the
* number of acks.
*/
return ackPolicy.minAckNodes(electableGroupSizeOverride) - 1;
}
Arbiter arbiter = repNode.getArbiter();
if (arbiter.isApplicable(ackPolicy)) {
return arbiter.getAckCount(ackPolicy);
}
return ackPolicy.minAckNodes
(repNode.getGroup().getElectableGroupSize()) - 1;
}
}
|
|
/*
* Copyright 2016 Richard Cartwright
*
* 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.
*/
/*
* $Log: DeltaEntryImpl.java,v $
* Revision 1.4 2011/07/28 18:51:18 vizigoth
* Changes to better support creating index tables with delta entries.
*
* Revision 1.3 2011/01/04 10:40:23 vizigoth
* Refactor all package names to simpler forms more consistent with typical Java usage.
*
* Revision 1.2 2010/01/21 20:51:31 vizigoth
* Updates to index table support to the point where index table data can be read from MXF files and stream offsets can be calculated.
*
* Revision 1.1 2010/01/19 14:44:24 vizigoth
* Major refactor to create a cleaner OO class structure and separate interface from implementation. Interim check in - work in progress.
*
*
*/
package tv.amwa.maj.io.mxf.impl;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Node;
import java.text.ParseException;
import tv.amwa.maj.integer.Int8;
import tv.amwa.maj.integer.UInt32;
import tv.amwa.maj.integer.UInt32Array;
import tv.amwa.maj.integer.UInt8;
import tv.amwa.maj.io.mxf.DeltaEntry;
import tv.amwa.maj.io.mxf.MXFConstants;
import tv.amwa.maj.io.xml.XMLBuilder;
import tv.amwa.maj.io.xml.XMLSerializable;
import tv.amwa.maj.meta.impl.TypeDefinitionRecordImpl;
/**
* <p>Defines a byte offset value along an incrementing timeline as part of a delta entry
* array in an {@linkplain IndexTableSegmentImpl index table segment}.</p>
*
*
*
*/
public class DeltaEntryImpl
implements
DeltaEntry,
Cloneable,
Serializable,
XMLSerializable {
private static final long serialVersionUID = -1341008782583700631L;
private @Int8 byte posTableIndex = POSTABLEINDEX_DEFAULT;
private @UInt8 byte slice = SLICE_DEFAULT;
private @UInt32 int elementDelta;
static {
TypeDefinitionRecordImpl.registerInterfaceMapping(DeltaEntry.class, DeltaEntryImpl.class);
}
public DeltaEntryImpl() { }
public DeltaEntryImpl(
@UInt32 int elementDelta)
throws IllegalArgumentException {
setElementDelta(elementDelta);
}
public DeltaEntryImpl(
@Int8 byte posTableIndex,
@UInt8 byte slice,
@UInt32 int elementDelta)
throws IllegalArgumentException {
setPosTableIndex(posTableIndex);
setSlice(slice);
setElementDelta(elementDelta);
}
public final static DeltaEntry[] makeDeltaEntryArray(
@UInt32Array int[] elementDeltas)
throws NullPointerException,
IllegalArgumentException {
if (elementDeltas == null)
throw new NullPointerException("Cannot make an array of delta entries from a null value.");
for ( int elementDelta : elementDeltas )
if (elementDelta < 0) throw new IllegalArgumentException("Cannot set an element delta value to a negative value.");
DeltaEntry[] deltaEntries = new DeltaEntry[elementDeltas.length];
for ( int x = 0 ; x < elementDeltas.length ; x++ )
deltaEntries[x] = new DeltaEntryImpl(elementDeltas[x]);
return deltaEntries;
}
/**
* <p>Create a cloned copy of this DeltaEntryImpl.</p>
*
* @return Cloned copy of this DeltaEntryImpl.
*/
public @Int8 byte getPosTableIndex() {
return posTableIndex;
}
/**
* <p>Create a cloned copy of this DeltaEntryImpl.</p>
*
* @return Cloned copy of this DeltaEntryImpl.
*/
public @UInt8 void setPosTableIndex(
@UInt8 byte posTableIndex)
throws IllegalArgumentException {
if (posTableIndex < -1)
throw new IllegalArgumentException("A position table index cannot be less than -1.");
this.posTableIndex = posTableIndex;
}
/**
* <p>Create a cloned copy of this DeltaEntryImpl.</p>
*
* @return Cloned copy of this DeltaEntryImpl.
*/
public @UInt8 byte getSlice() {
return slice;
}
/**
* <p>Create a cloned copy of this DeltaEntryImpl.</p>
*
* @return Cloned copy of this DeltaEntryImpl.
*/
public void setSlice(
@UInt8 byte slice)
throws IllegalArgumentException {
if (slice < 0)
throw new IllegalArgumentException("Cannot set the value of the slice number to a negative value.");
this.slice = slice;
}
/**
* <p>Create a cloned copy of this DeltaEntryImpl.</p>
*
* @return Cloned copy of this DeltaEntryImpl.
*/
public @UInt32 int getElementDelta() {
return elementDelta;
}
/**
* <p>Create a cloned copy of this DeltaEntryImpl.</p>
*
* @return Cloned copy of this DeltaEntryImpl.
*/
public void setElementDelta(
@UInt32 int elementDelta)
throws IllegalArgumentException {
if (elementDelta < 0)
throw new IllegalArgumentException("Cannot set the delta from the element delta offset to a negative value.");
this.elementDelta = elementDelta;
}
public boolean equals(
Object o) {
if (o == null) return false;
if (this == o) return true;
if (!(o instanceof DeltaEntry)) return false;
DeltaEntry testEntry = (DeltaEntry) o;
if (testEntry.getElementDelta() != elementDelta) return false;
if (testEntry.getPosTableIndex() != posTableIndex) return false;
if (testEntry.getSlice() != slice) return false;
return true;
}
/**
* <p>Create a cloned copy of this DeltaEntryImpl.</p>
*
* @return Cloned copy of this DeltaEntryImpl.
*/
public DeltaEntry clone() {
try {
return (DeltaEntry) super.clone();
}
catch (CloneNotSupportedException cnse) {
// Implements cloneable, so lot likely
throw new InternalError(cnse.getMessage());
}
}
public String toString() {
return XMLBuilder.toXMLNonMetadata(this);
}
public int hashCode() {
return (posTableIndex << 24) ^ (slice << 16) ^ elementDelta;
}
public final static String DELTAENTRY_TAG = "DeltaEntry";
final static String POSTABLEINDEX_TAG = "PosTableIndex";
final static String SLICE_TAG = "Slice";
final static String ELEMENTDELTA_TAG = "ElementDelta";
public void appendXMLChildren(
Node parent) {
Node deltaEntryElement;
if (parent instanceof DocumentFragment)
deltaEntryElement =
XMLBuilder.createChild(parent, MXFConstants.RP210_NAMESPACE,
MXFConstants.RP210_PREFIX, DELTAENTRY_TAG);
else
deltaEntryElement = parent;
XMLBuilder.appendElement(deltaEntryElement, MXFConstants.RP210_NAMESPACE,
MXFConstants.RP210_PREFIX, POSTABLEINDEX_TAG, posTableIndex);
XMLBuilder.appendElement(deltaEntryElement, MXFConstants.RP210_NAMESPACE,
MXFConstants.RP210_PREFIX, SLICE_TAG, slice);
XMLBuilder.appendElement(deltaEntryElement, MXFConstants.RP210_NAMESPACE,
MXFConstants.RP210_PREFIX, ELEMENTDELTA_TAG, elementDelta);
}
private final static Pattern posTableIndexPattern =
Pattern.compile("<\\w*\\:?" + POSTABLEINDEX_TAG + "\\>(-?\\d+|(-?0x[0-9a-fA-F]+))\\<\\/\\w*\\:?" + POSTABLEINDEX_TAG + "\\>");
private final static Pattern slicePattern =
Pattern.compile("<\\w*\\:?" + SLICE_TAG + "\\>(\\d+|(0x[0-9a-fA-F]+))\\<\\/\\w*\\:?" + SLICE_TAG + "\\>");
private final static Pattern elementDeltaPattern =
Pattern.compile("<\\w*\\:?" + ELEMENTDELTA_TAG + "\\>(\\d+|(0x[0-9a-fA-F]+))\\<\\/\\w*\\:?" + ELEMENTDELTA_TAG + "\\>");
public final static DeltaEntry parseFactory(
String deltaEntryString)
throws NullPointerException,
ParseException {
if (deltaEntryString == null)
throw new NullPointerException("Cannot create a delta entry from a null value.");
Matcher matcher = null;
byte posTableIndex = POSTABLEINDEX_DEFAULT;
byte slice = SLICE_DEFAULT;
int elementDelta = 0;
try {
matcher = posTableIndexPattern.matcher(deltaEntryString);
if (matcher.find()) {
String posTableIndexString = matcher.group(1);
boolean posTableNegative = (posTableIndexString.startsWith("-")) ? true : false;
if (posTableNegative) posTableIndexString = posTableIndexString.substring(1);
if (posTableIndexString.startsWith("0x"))
posTableIndex = Byte.parseByte(posTableIndexString.substring(2), 16);
else
posTableIndex = Byte.parseByte(posTableIndexString);
if (posTableNegative) posTableIndex = (byte) -posTableIndex;
}
matcher = slicePattern.matcher(deltaEntryString);
if (matcher.find()) {
String sliceString = matcher.group(1);
if (sliceString.startsWith("0x"))
slice = Byte.parseByte(sliceString.substring(2), 16);
else
slice = Byte.parseByte(sliceString);
}
matcher = elementDeltaPattern.matcher(deltaEntryString);
if (!matcher.find())
throw new ParseException("A delta entry must have an element delta value specified.", 0);
String elementDeltaString = matcher.group(1);
if (elementDeltaString.startsWith("0x"))
elementDelta = Integer.parseInt(elementDeltaString, 16);
else
elementDelta = Integer.parseInt(elementDeltaString);
return new DeltaEntryImpl(posTableIndex, slice, elementDelta);
}
catch (Exception e) {
throw new ParseException(e.getClass().getName() + " thrown when parsing a delta entry: " + e.getMessage(), 0);
}
}
// TODO XMLHandler - is this needed in this case?
public String getComment() {
// TODO Auto-generated method stub
return null;
}
}
|
|
/*
* 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.ordering;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import io.druid.jackson.DefaultObjectMapper;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class StringComparatorsTest
{
private void commonTest(StringComparator comparator)
{
// equality test
Assert.assertTrue(comparator.compare(null, null) == 0);
Assert.assertTrue(comparator.compare("", "") == 0);
Assert.assertTrue(comparator.compare("123", "123") == 0);
Assert.assertTrue(comparator.compare("abc123", "abc123") == 0);
// empty strings < non-empty
Assert.assertTrue(comparator.compare("", "abc") < 0);
Assert.assertTrue(comparator.compare("abc", "") > 0);
// null first test
Assert.assertTrue(comparator.compare(null, "apple") < 0);
}
@Test
public void testLexicographicComparator()
{
commonTest(StringComparators.LEXICOGRAPHIC);
Assert.assertTrue(StringComparators.LEXICOGRAPHIC.compare("apple", "banana") < 0);
Assert.assertTrue(StringComparators.LEXICOGRAPHIC.compare("banana", "banana") == 0);
}
@Test
public void testAlphanumericComparator()
{
commonTest(StringComparators.ALPHANUMERIC);
// numbers < non numeric
Assert.assertTrue(StringComparators.ALPHANUMERIC.compare("123", "abc") < 0);
Assert.assertTrue(StringComparators.ALPHANUMERIC.compare("abc", "123") > 0);
// numbers ordered numerically
Assert.assertTrue(StringComparators.ALPHANUMERIC.compare("2", "11") < 0);
Assert.assertTrue(StringComparators.ALPHANUMERIC.compare("a2", "a11") < 0);
// leading zeros
Assert.assertTrue(StringComparators.ALPHANUMERIC.compare("02", "11") < 0);
Assert.assertTrue(StringComparators.ALPHANUMERIC.compare("02", "002") < 0);
// decimal points ...
Assert.assertTrue(StringComparators.ALPHANUMERIC.compare("1.3", "1.5") < 0);
// ... don't work too well
Assert.assertTrue(StringComparators.ALPHANUMERIC.compare("1.3", "1.15") < 0);
// but you can sort ranges
List<String> sorted = Lists.newArrayList("1-5", "11-15", "16-20", "21-25", "26-30", "6-10", "Other");
Collections.sort(sorted, StringComparators.ALPHANUMERIC);
Assert.assertEquals(
ImmutableList.of("1-5", "6-10", "11-15", "16-20", "21-25", "26-30", "Other"),
sorted
);
List<String> sortedFixedDecimal = Lists.newArrayList(
"Other", "[0.00-0.05)", "[0.05-0.10)", "[0.10-0.50)", "[0.50-1.00)",
"[1.00-5.00)", "[5.00-10.00)", "[10.00-20.00)"
);
Collections.sort(sortedFixedDecimal, StringComparators.ALPHANUMERIC);
Assert.assertEquals(
ImmutableList.of(
"[0.00-0.05)", "[0.05-0.10)", "[0.10-0.50)", "[0.50-1.00)",
"[1.00-5.00)", "[5.00-10.00)", "[10.00-20.00)", "Other"
),
sortedFixedDecimal
);
}
@Test
public void testStrlenComparator()
{
commonTest(StringComparators.STRLEN);
Assert.assertTrue(StringComparators.STRLEN.compare("a", "apple") < 0);
Assert.assertTrue(StringComparators.STRLEN.compare("a", "elppa") < 0);
Assert.assertTrue(StringComparators.STRLEN.compare("apple", "elppa") < 0);
}
@Test
public void testNumericComparator()
{
commonTest(StringComparators.NUMERIC);
Assert.assertTrue(StringComparators.NUMERIC.compare("-1230.452487532", "6893") < 0);
List<String> values = Arrays.asList("-1", "-1.10", "-1.2", "-100", "-2", "0", "1", "1.10", "1.2", "2", "100");
Collections.sort(values, StringComparators.NUMERIC);
Assert.assertEquals(
Arrays.asList("-100", "-2", "-1.2", "-1.10", "-1", "0", "1", "1.10", "1.2", "2", "100"),
values
);
Assert.assertTrue(StringComparators.NUMERIC.compare(null, null) == 0);
Assert.assertTrue(StringComparators.NUMERIC.compare(null, "1001") < 0);
Assert.assertTrue(StringComparators.NUMERIC.compare("1001", null) > 0);
Assert.assertTrue(StringComparators.NUMERIC.compare("-500000000.14124", "CAN'T TOUCH THIS") > 0);
Assert.assertTrue(StringComparators.NUMERIC.compare("CAN'T PARSE THIS", "-500000000.14124") < 0);
Assert.assertTrue(StringComparators.NUMERIC.compare("CAN'T PARSE THIS", "CAN'T TOUCH THIS") < 0);
}
@Test
public void testLexicographicComparatorSerdeTest() throws IOException
{
ObjectMapper jsonMapper = new DefaultObjectMapper();
String expectJsonSpec = "{\"type\":\"lexicographic\"}";
String jsonSpec = jsonMapper.writeValueAsString(StringComparators.LEXICOGRAPHIC);
Assert.assertEquals(expectJsonSpec, jsonSpec);
Assert.assertEquals(StringComparators.LEXICOGRAPHIC
, jsonMapper.readValue(expectJsonSpec, StringComparator.class));
String makeFromJsonSpec = "\"lexicographic\"";
Assert.assertEquals(StringComparators.LEXICOGRAPHIC
, jsonMapper.readValue(makeFromJsonSpec, StringComparator.class));
}
@Test
public void testAlphanumericComparatorSerdeTest() throws IOException
{
ObjectMapper jsonMapper = new DefaultObjectMapper();
String expectJsonSpec = "{\"type\":\"alphanumeric\"}";
String jsonSpec = jsonMapper.writeValueAsString(StringComparators.ALPHANUMERIC);
Assert.assertEquals(expectJsonSpec, jsonSpec);
Assert.assertEquals(StringComparators.ALPHANUMERIC
, jsonMapper.readValue(expectJsonSpec, StringComparator.class));
String makeFromJsonSpec = "\"alphanumeric\"";
Assert.assertEquals(StringComparators.ALPHANUMERIC
, jsonMapper.readValue(makeFromJsonSpec, StringComparator.class));
}
@Test
public void testStrlenComparatorSerdeTest() throws IOException
{
ObjectMapper jsonMapper = new DefaultObjectMapper();
String expectJsonSpec = "{\"type\":\"strlen\"}";
String jsonSpec = jsonMapper.writeValueAsString(StringComparators.STRLEN);
Assert.assertEquals(expectJsonSpec, jsonSpec);
Assert.assertEquals(StringComparators.STRLEN
, jsonMapper.readValue(expectJsonSpec, StringComparator.class));
String makeFromJsonSpec = "\"strlen\"";
Assert.assertEquals(StringComparators.STRLEN
, jsonMapper.readValue(makeFromJsonSpec, StringComparator.class));
}
@Test
public void testNumericComparatorSerdeTest() throws IOException
{
ObjectMapper jsonMapper = new DefaultObjectMapper();
String expectJsonSpec = "{\"type\":\"numeric\"}";
String jsonSpec = jsonMapper.writeValueAsString(StringComparators.NUMERIC);
Assert.assertEquals(expectJsonSpec, jsonSpec);
Assert.assertEquals(StringComparators.NUMERIC
, jsonMapper.readValue(expectJsonSpec, StringComparator.class));
String makeFromJsonSpec = "\"numeric\"";
Assert.assertEquals(StringComparators.NUMERIC
, jsonMapper.readValue(makeFromJsonSpec, StringComparator.class));
makeFromJsonSpec = "\"NuMeRiC\"";
Assert.assertEquals(StringComparators.NUMERIC
, jsonMapper.readValue(makeFromJsonSpec, StringComparator.class));
}
}
|
|
/*
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2011-2018, Sebastian Staudt
*/
package com.github.koraktor.steamcondenser.community;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.json.JSONException;
import org.json.JSONObject;
import com.github.koraktor.steamcondenser.exceptions.SteamCondenserException;
import com.github.koraktor.steamcondenser.exceptions.WebApiException;
/**
* This class represents a game available on Steam
*
* @author Sebastian Staudt
*/
public class SteamGame {
private static Map<Integer, SteamGame> games = new HashMap<>();
private int appId;
private String iconUrl;
private String logoHash;
private String name;
private String shortName;
/**
* Clears the game cache
*/
public static void clearCache() {
games.clear();
}
/**
* Checks if a game is up-to-date by reading information from a
* <code>steam.inf</code> file and comparing it using the Web API
*
* @param path The file system path of the `steam.inf` file
* @return <code>true</code> if the game is up-to-date
* @throws IOException if the steam.inf cannot be read
* @throws JSONException if the JSON data is malformed
* @throws SteamCondenserException if the given steam.inf is invalid or
* the Web API request fails
*/
public static boolean checkSteamInf(String path)
throws IOException, JSONException, SteamCondenserException {
BufferedReader steamInf = new BufferedReader(new FileReader(path));
String steamInfContents = "";
while(steamInf.ready()) {
steamInfContents += steamInf.readLine() + "\n";
}
steamInf.close();
Pattern appIdPattern = Pattern.compile("^\\s*appID=(\\d+)\\s*$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher appIdMatcher = appIdPattern.matcher(steamInfContents);
Pattern versionPattern = Pattern.compile("^\\s*PatchVersion=([\\d\\.]+)\\s*$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher versionMatcher = versionPattern.matcher(steamInfContents);
if(!(appIdMatcher.find() && versionMatcher.find())) {
throw new SteamCondenserException("The steam.inf file at \"" + path + "\" is invalid.");
}
int appId = Integer.parseInt(appIdMatcher.group(1));
int version = Integer.parseInt(versionMatcher.group(1).replace(".", ""));
return isUpToDate(appId, version);
}
/**
* Creates a new or cached instance of the game specified by the given XML
* data
*
* @param appId The application ID of the game
* @param gameData The XML data of the game
* @return The game instance for the given data
* @see SteamGame#SteamGame
*/
public static SteamGame create(int appId, XMLData gameData) {
if(games.containsKey(appId)) {
return games.get(appId);
} else {
return new SteamGame(appId, gameData);
}
}
/**
* Returns whether the given version of the game with the given application
* ID is up-to-date
*
* @param appId The application ID of the game to check
* @param version The version to check against the Web API
* @return <code>true</code> if the given version is up-to-date
* @throws JSONException if the JSON data is malformed
* @throws SteamCondenserException if the Web API request fails
*/
public static boolean isUpToDate(int appId, int version)
throws JSONException, SteamCondenserException {
Map<String, Object> params = new HashMap<>();
params.put("appid", appId);
params.put("version", version);
String json = WebApi.getJSON("ISteamApps", "UpToDateCheck", 1, params);
JSONObject result = new JSONObject(json).getJSONObject("response");
if(!result.getBoolean("success")) {
throw new SteamCondenserException(result.getString("error"));
}
return result.getBoolean("up_to_date");
}
/**
* Creates a new instance of a game with the given data and caches it
*
* @param appId The application ID of the game
* @param gameData The XML data of the game
*/
private SteamGame(int appId, XMLData gameData) {
this.appId = appId;
String logoUrl;
if(gameData.hasElement("name")) {
logoUrl = gameData.getString("logo");
this.name = gameData.getString("name");
if(gameData.hasElement("globalStatsLink")) {
Pattern regex = Pattern.compile("http://steamcommunity.com/stats/([^?/]+)/achievements/");
Matcher matcher = regex.matcher(gameData.getString("globalStatsLink"));
matcher.find();
shortName = matcher.group(1).toLowerCase();
this.shortName = matcher.group(1).toLowerCase();
} else {
this.shortName = null;
}
} else {
this.iconUrl = gameData.getString("gameIcon");
logoUrl = gameData.getString("gameLogo");
this.name = gameData.getString("gameName");
this.shortName = gameData.getString("gameFriendlyName").toLowerCase();
}
Pattern regex = Pattern.compile("/" + appId + "/([0-9a-f]+).jpg");
Matcher matcher = regex.matcher(logoUrl);
if (matcher.find()) {
this.logoHash = matcher.group(1).toLowerCase();
}
games.put(appId, this);
}
/**
* Returns the Steam application ID of this game
*
* @return The Steam application ID of this game
*/
public int getAppId() {
return this.appId;
}
/**
* Returns the URL for the icon image of this game
*
* @return The URL for the game icon
*/
public String getIconUrl() {
return this.iconUrl;
}
/**
* Returns a unique identifier for this game
*
* This is either the numeric application ID or the unique short name
*
* @return The application ID or short name of the game
*/
public Object getId() {
if(String.valueOf(this.appId).equals(this.shortName)) {
return this.appId;
} else {
return this.shortName;
}
}
/**
* Returns the full name of this game
*
* @return The full name of this game
*/
public String getName() {
return this.name;
}
/**
* Returns the leaderboard for this game and the given leaderboard ID
*
* @param id The ID of the leaderboard to return
* @return The matching leaderboard if available
*/
public GameLeaderboard getLeaderboard(int id)
throws SteamCondenserException {
return GameLeaderboard.getLeaderboard(this.shortName, id);
}
/**
* Returns the leaderboard for this game and the given leaderboard name
*
* @param name The name of the leaderboard to return
* @return The matching leaderboard if available
*/
public GameLeaderboard getLeaderboard(String name)
throws SteamCondenserException {
return GameLeaderboard.getLeaderboard(this.shortName, name);
}
/**
* Returns an array containing all of this game's leaderboards
*
* @return The leaderboards for this game
*/
public Map<Integer, GameLeaderboard> getLeaderboards()
throws SteamCondenserException {
return GameLeaderboard.getLeaderboards(this.shortName);
}
/**
* Returns the URL for the logo image of this game
*
* @return The URL for the game logo
*/
public String getLogoUrl() {
if (this.logoHash == null) {
return null;
} else {
return "http://media.steampowered.com/steamcommunity/public/images/apps/" + this.appId + "/" + this.logoHash + ".jpg";
}
}
/**
* Returns the URL for the logo thumbnail image of this game
*
* @return The URL for the game logo thumbnail
*/
public String getLogoThumbnailUrl() {
if (this.logoHash == null) {
return null;
} else {
return "http://media.steampowered.com/steamcommunity/public/images/apps/" + this.appId + "/" + this.logoHash + "_thumb.jpg";
}
}
/**
* Returns the overall number of players currently playing this game
*
* @return The number of players playing this game
* @throws JSONException In case of misformatted JSON data
* @throws WebApiException on Web API errors
*/
public int getPlayerCount() throws JSONException, WebApiException {
Map<String, Object> params = new HashMap<>();
params.put("appid", this.appId);
String jsonString = WebApi.getJSON("ISteamUserStats", "GetNumberOfCurrentPlayers", 1, params);
JSONObject result = new JSONObject(jsonString).getJSONObject("response");
return result.getInt("player_count");
}
/**
* Returns the short name of this game (also known as "friendly name")
*
* @return The short name of this game
*/
public String getShortName() {
return this.shortName;
}
/**
* Returns the URL of this game's page in the Steam Store
*
* @return This game's store page
*/
public String getStoreUrl() {
return "http://store.steampowered.com/app/" + this.appId;
}
/**
* Creates a stats object for the given user and this game
*
* @param steamId The custom URL or the 64bit Steam ID of the user
* @return The stats of this game for the given user
*/
public GameStats getUserStats(Object steamId)
throws SteamCondenserException {
if(!this.hasStats()) {
return null;
}
return GameStats.createGameStats(steamId, this.shortName);
}
/**
* Returns whether this game has statistics available
*
* @return <code>true</code> if this game has stats
*/
public boolean hasStats() {
return this.shortName != null;
}
/**
* Returns whether the given version of this game is up-to-date
*
* @param version The version to check against the Web API
* @return <code>true</code> if the given version is up-to-date
* @throws JSONException if the JSON data is malformed
* @throws SteamCondenserException if the Web API request fails
*/
public boolean isUpToDate(int version)
throws JSONException, SteamCondenserException {
return SteamGame.isUpToDate(this.appId, version);
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("appId", this.appId)
.append("name", this.name)
.append("shortName", this.shortName)
.toString();
}
}
|
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* TargetingSettingDetail.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201809.cm;
/**
* Specifies if criteria of this type group should be used to restrict
* targeting, or if ads can serve anywhere and criteria are only used
* in
* determining the bid.
* <p>For more information, see
* <a href="https://support.google.com/adwords/answer/6056342">Targeting
* Settings</a>.</p>
*/
public class TargetingSettingDetail implements java.io.Serializable {
/* The criterion type group that these settings apply to.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span> */
private com.google.api.ads.adwords.axis.v201809.cm.CriterionTypeGroup criterionTypeGroup;
/* If true, criteria of this type can be used to modify bidding
* but will not restrict targeting
* of ads. This is equivalent to "Bid only" in the AdWords
* user interface.
* If false, restricts your ads to showing only for the
* criteria you have selected for this
* CriterionTypeGroup. This is equivalent to "Target
* and Bid" in the AdWords user interface.
* The default setting for a CriterionTypeGroup is false
* ("Target and Bid").
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span> */
private java.lang.Boolean targetAll;
public TargetingSettingDetail() {
}
public TargetingSettingDetail(
com.google.api.ads.adwords.axis.v201809.cm.CriterionTypeGroup criterionTypeGroup,
java.lang.Boolean targetAll) {
this.criterionTypeGroup = criterionTypeGroup;
this.targetAll = targetAll;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("criterionTypeGroup", getCriterionTypeGroup())
.add("targetAll", getTargetAll())
.toString();
}
/**
* Gets the criterionTypeGroup value for this TargetingSettingDetail.
*
* @return criterionTypeGroup * The criterion type group that these settings apply to.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public com.google.api.ads.adwords.axis.v201809.cm.CriterionTypeGroup getCriterionTypeGroup() {
return criterionTypeGroup;
}
/**
* Sets the criterionTypeGroup value for this TargetingSettingDetail.
*
* @param criterionTypeGroup * The criterion type group that these settings apply to.
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public void setCriterionTypeGroup(com.google.api.ads.adwords.axis.v201809.cm.CriterionTypeGroup criterionTypeGroup) {
this.criterionTypeGroup = criterionTypeGroup;
}
/**
* Gets the targetAll value for this TargetingSettingDetail.
*
* @return targetAll * If true, criteria of this type can be used to modify bidding
* but will not restrict targeting
* of ads. This is equivalent to "Bid only" in the AdWords
* user interface.
* If false, restricts your ads to showing only for the
* criteria you have selected for this
* CriterionTypeGroup. This is equivalent to "Target
* and Bid" in the AdWords user interface.
* The default setting for a CriterionTypeGroup is false
* ("Target and Bid").
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public java.lang.Boolean getTargetAll() {
return targetAll;
}
/**
* Sets the targetAll value for this TargetingSettingDetail.
*
* @param targetAll * If true, criteria of this type can be used to modify bidding
* but will not restrict targeting
* of ads. This is equivalent to "Bid only" in the AdWords
* user interface.
* If false, restricts your ads to showing only for the
* criteria you have selected for this
* CriterionTypeGroup. This is equivalent to "Target
* and Bid" in the AdWords user interface.
* The default setting for a CriterionTypeGroup is false
* ("Target and Bid").
* <span class="constraint Required">This field is required
* and should not be {@code null}.</span>
*/
public void setTargetAll(java.lang.Boolean targetAll) {
this.targetAll = targetAll;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof TargetingSettingDetail)) return false;
TargetingSettingDetail other = (TargetingSettingDetail) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.criterionTypeGroup==null && other.getCriterionTypeGroup()==null) ||
(this.criterionTypeGroup!=null &&
this.criterionTypeGroup.equals(other.getCriterionTypeGroup()))) &&
((this.targetAll==null && other.getTargetAll()==null) ||
(this.targetAll!=null &&
this.targetAll.equals(other.getTargetAll())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getCriterionTypeGroup() != null) {
_hashCode += getCriterionTypeGroup().hashCode();
}
if (getTargetAll() != null) {
_hashCode += getTargetAll().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(TargetingSettingDetail.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "TargetingSettingDetail"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("criterionTypeGroup");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "criterionTypeGroup"));
elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "CriterionTypeGroup"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("targetAll");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "targetAll"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
|
/*
* 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.cluster.metadata;
import com.carrotsearch.hppc.ObjectHashSet;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.cluster.Diff;
import org.elasticsearch.cluster.Diffable;
import org.elasticsearch.cluster.DiffableUtils;
import org.elasticsearch.cluster.DiffableUtils.KeyedReader;
import org.elasticsearch.cluster.InternalClusterInfoService;
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.routing.allocation.decider.DiskThresholdDecider;
import org.elasticsearch.cluster.service.InternalClusterService;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.HppcMaps;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.loader.SettingsLoader;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.discovery.DiscoverySettings;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.indices.recovery.RecoverySettings;
import org.elasticsearch.indices.store.IndicesStore;
import org.elasticsearch.indices.ttl.IndicesTTLService;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.warmer.IndexWarmersMetaData;
import java.io.IOException;
import java.util.*;
import static org.elasticsearch.common.settings.Settings.*;
public class MetaData implements Iterable<IndexMetaData>, Diffable<MetaData>, FromXContentBuilder<MetaData>, ToXContent {
public static final MetaData PROTO = builder().build();
public static final String ALL = "_all";
public enum XContentContext {
/* Custom metadata should be returns as part of API call */
API,
/* Custom metadata should be stored as part of the persistent cluster state */
GATEWAY,
/* Custom metadata should be stored as part of a snapshot */
SNAPSHOT
}
public static EnumSet<XContentContext> API_ONLY = EnumSet.of(XContentContext.API);
public static EnumSet<XContentContext> API_AND_GATEWAY = EnumSet.of(XContentContext.API, XContentContext.GATEWAY);
public static EnumSet<XContentContext> API_AND_SNAPSHOT = EnumSet.of(XContentContext.API, XContentContext.SNAPSHOT);
public interface Custom extends Diffable<Custom>, ToXContent {
String type();
Custom fromXContent(XContentParser parser) throws IOException;
EnumSet<XContentContext> context();
}
public static Map<String, Custom> customPrototypes = new HashMap<>();
static {
// register non plugin custom metadata
registerPrototype(RepositoriesMetaData.TYPE, RepositoriesMetaData.PROTO);
}
/**
* Register a custom index meta data factory. Make sure to call it from a static block.
*/
public static void registerPrototype(String type, Custom proto) {
customPrototypes.put(type, proto);
}
@Nullable
public static <T extends Custom> T lookupPrototype(String type) {
//noinspection unchecked
return (T) customPrototypes.get(type);
}
public static <T extends Custom> T lookupPrototypeSafe(String type) {
//noinspection unchecked
T proto = (T) customPrototypes.get(type);
if (proto == null) {
throw new IllegalArgumentException("No custom metadata prototype registered for type [" + type + "]");
}
return proto;
}
public static final String SETTING_READ_ONLY = "cluster.blocks.read_only";
public static final ClusterBlock CLUSTER_READ_ONLY_BLOCK = new ClusterBlock(6, "cluster read-only (api)", false, false, RestStatus.FORBIDDEN, EnumSet.of(ClusterBlockLevel.WRITE, ClusterBlockLevel.METADATA_WRITE));
public static final MetaData EMPTY_META_DATA = builder().build();
public static final String CONTEXT_MODE_PARAM = "context_mode";
public static final String CONTEXT_MODE_SNAPSHOT = XContentContext.SNAPSHOT.toString();
public static final String CONTEXT_MODE_GATEWAY = XContentContext.GATEWAY.toString();
private final String clusterUUID;
private final long version;
private final Settings transientSettings;
private final Settings persistentSettings;
private final Settings settings;
private final ImmutableOpenMap<String, IndexMetaData> indices;
private final ImmutableOpenMap<String, IndexTemplateMetaData> templates;
private final ImmutableOpenMap<String, Custom> customs;
private final transient int totalNumberOfShards; // Transient ? not serializable anyway?
private final int numberOfShards;
private final String[] allIndices;
private final String[] allOpenIndices;
private final String[] allClosedIndices;
private final SortedMap<String, AliasOrIndex> aliasAndIndexLookup;
@SuppressWarnings("unchecked")
MetaData(String clusterUUID, long version, Settings transientSettings, Settings persistentSettings, ImmutableOpenMap<String, IndexMetaData> indices, ImmutableOpenMap<String, IndexTemplateMetaData> templates, ImmutableOpenMap<String, Custom> customs, String[] allIndices, String[] allOpenIndices, String[] allClosedIndices, SortedMap<String, AliasOrIndex> aliasAndIndexLookup) {
this.clusterUUID = clusterUUID;
this.version = version;
this.transientSettings = transientSettings;
this.persistentSettings = persistentSettings;
this.settings = Settings.settingsBuilder().put(persistentSettings).put(transientSettings).build();
this.indices = indices;
this.customs = customs;
this.templates = templates;
int totalNumberOfShards = 0;
int numberOfShards = 0;
for (ObjectCursor<IndexMetaData> cursor : indices.values()) {
totalNumberOfShards += cursor.value.totalNumberOfShards();
numberOfShards += cursor.value.numberOfShards();
}
this.totalNumberOfShards = totalNumberOfShards;
this.numberOfShards = numberOfShards;
this.allIndices = allIndices;
this.allOpenIndices = allOpenIndices;
this.allClosedIndices = allClosedIndices;
this.aliasAndIndexLookup = aliasAndIndexLookup;
}
public long version() {
return this.version;
}
public String clusterUUID() {
return this.clusterUUID;
}
/**
* Returns the merged transient and persistent settings.
*/
public Settings settings() {
return this.settings;
}
public Settings transientSettings() {
return this.transientSettings;
}
public Settings persistentSettings() {
return this.persistentSettings;
}
public boolean hasAlias(String alias) {
AliasOrIndex aliasOrIndex = getAliasAndIndexLookup().get(alias);
if (aliasOrIndex != null) {
return aliasOrIndex.isAlias();
} else {
return false;
}
}
public boolean equalsAliases(MetaData other) {
for (ObjectCursor<IndexMetaData> cursor : other.indices().values()) {
IndexMetaData otherIndex = cursor.value;
IndexMetaData thisIndex= indices().get(otherIndex.getIndex());
if (thisIndex == null) {
return false;
}
if (otherIndex.getAliases().equals(thisIndex.getAliases()) == false) {
return false;
}
}
return true;
}
public SortedMap<String, AliasOrIndex> getAliasAndIndexLookup() {
return aliasAndIndexLookup;
}
/**
* Finds the specific index aliases that match with the specified aliases directly or partially via wildcards and
* that point to the specified concrete indices or match partially with the indices via wildcards.
*
* @param aliases The names of the index aliases to find
* @param concreteIndices The concrete indexes the index aliases must point to order to be returned.
* @return the found index aliases grouped by index
*/
public ImmutableOpenMap<String, ImmutableList<AliasMetaData>> findAliases(final String[] aliases, String[] concreteIndices) {
assert aliases != null;
assert concreteIndices != null;
if (concreteIndices.length == 0) {
return ImmutableOpenMap.of();
}
boolean matchAllAliases = matchAllAliases(aliases);
ImmutableOpenMap.Builder<String, ImmutableList<AliasMetaData>> mapBuilder = ImmutableOpenMap.builder();
Iterable<String> intersection = HppcMaps.intersection(ObjectHashSet.from(concreteIndices), indices.keys());
for (String index : intersection) {
IndexMetaData indexMetaData = indices.get(index);
List<AliasMetaData> filteredValues = Lists.newArrayList();
for (ObjectCursor<AliasMetaData> cursor : indexMetaData.getAliases().values()) {
AliasMetaData value = cursor.value;
if (matchAllAliases || Regex.simpleMatch(aliases, value.alias())) {
filteredValues.add(value);
}
}
if (!filteredValues.isEmpty()) {
// Make the list order deterministic
CollectionUtil.timSort(filteredValues, new Comparator<AliasMetaData>() {
@Override
public int compare(AliasMetaData o1, AliasMetaData o2) {
return o1.alias().compareTo(o2.alias());
}
});
mapBuilder.put(index, ImmutableList.copyOf(filteredValues));
}
}
return mapBuilder.build();
}
private static boolean matchAllAliases(final String[] aliases) {
for (String alias : aliases) {
if (alias.equals(ALL)) {
return true;
}
}
return aliases.length == 0;
}
/**
* Checks if at least one of the specified aliases exists in the specified concrete indices. Wildcards are supported in the
* alias names for partial matches.
*
* @param aliases The names of the index aliases to find
* @param concreteIndices The concrete indexes the index aliases must point to order to be returned.
* @return whether at least one of the specified aliases exists in one of the specified concrete indices.
*/
public boolean hasAliases(final String[] aliases, String[] concreteIndices) {
assert aliases != null;
assert concreteIndices != null;
if (concreteIndices.length == 0) {
return false;
}
Iterable<String> intersection = HppcMaps.intersection(ObjectHashSet.from(concreteIndices), indices.keys());
for (String index : intersection) {
IndexMetaData indexMetaData = indices.get(index);
List<AliasMetaData> filteredValues = Lists.newArrayList();
for (ObjectCursor<AliasMetaData> cursor : indexMetaData.getAliases().values()) {
AliasMetaData value = cursor.value;
if (Regex.simpleMatch(aliases, value.alias())) {
filteredValues.add(value);
}
}
if (!filteredValues.isEmpty()) {
return true;
}
}
return false;
}
/*
* Finds all mappings for types and concrete indices. Types are expanded to
* include all types that match the glob patterns in the types array. Empty
* types array, null or {"_all"} will be expanded to all types available for
* the given indices.
*/
public ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> findMappings(String[] concreteIndices, final String[] types) {
assert types != null;
assert concreteIndices != null;
if (concreteIndices.length == 0) {
return ImmutableOpenMap.of();
}
ImmutableOpenMap.Builder<String, ImmutableOpenMap<String, MappingMetaData>> indexMapBuilder = ImmutableOpenMap.builder();
Iterable<String> intersection = HppcMaps.intersection(ObjectHashSet.from(concreteIndices), indices.keys());
for (String index : intersection) {
IndexMetaData indexMetaData = indices.get(index);
ImmutableOpenMap.Builder<String, MappingMetaData> filteredMappings;
if (isAllTypes(types)) {
indexMapBuilder.put(index, indexMetaData.getMappings()); // No types specified means get it all
} else {
filteredMappings = ImmutableOpenMap.builder();
for (ObjectObjectCursor<String, MappingMetaData> cursor : indexMetaData.mappings()) {
if (Regex.simpleMatch(types, cursor.key)) {
filteredMappings.put(cursor.key, cursor.value);
}
}
if (!filteredMappings.isEmpty()) {
indexMapBuilder.put(index, filteredMappings.build());
}
}
}
return indexMapBuilder.build();
}
public ImmutableOpenMap<String, ImmutableList<IndexWarmersMetaData.Entry>> findWarmers(String[] concreteIndices, final String[] types, final String[] uncheckedWarmers) {
assert uncheckedWarmers != null;
assert concreteIndices != null;
if (concreteIndices.length == 0) {
return ImmutableOpenMap.of();
}
// special _all check to behave the same like not specifying anything for the warmers (not for the indices)
final String[] warmers = Strings.isAllOrWildcard(uncheckedWarmers) ? Strings.EMPTY_ARRAY : uncheckedWarmers;
ImmutableOpenMap.Builder<String, ImmutableList<IndexWarmersMetaData.Entry>> mapBuilder = ImmutableOpenMap.builder();
Iterable<String> intersection = HppcMaps.intersection(ObjectHashSet.from(concreteIndices), indices.keys());
for (String index : intersection) {
IndexMetaData indexMetaData = indices.get(index);
IndexWarmersMetaData indexWarmersMetaData = indexMetaData.custom(IndexWarmersMetaData.TYPE);
if (indexWarmersMetaData == null || indexWarmersMetaData.entries().isEmpty()) {
continue;
}
Collection<IndexWarmersMetaData.Entry> filteredWarmers = Collections2.filter(indexWarmersMetaData.entries(), new Predicate<IndexWarmersMetaData.Entry>() {
@Override
public boolean apply(IndexWarmersMetaData.Entry warmer) {
if (warmers.length != 0 && types.length != 0) {
return Regex.simpleMatch(warmers, warmer.name()) && Regex.simpleMatch(types, warmer.types());
} else if (warmers.length != 0) {
return Regex.simpleMatch(warmers, warmer.name());
} else if (types.length != 0) {
return Regex.simpleMatch(types, warmer.types());
} else {
return true;
}
}
});
if (!filteredWarmers.isEmpty()) {
mapBuilder.put(index, ImmutableList.copyOf(filteredWarmers));
}
}
return mapBuilder.build();
}
/**
* Returns all the concrete indices.
*/
public String[] concreteAllIndices() {
return allIndices;
}
public String[] getConcreteAllIndices() {
return concreteAllIndices();
}
public String[] concreteAllOpenIndices() {
return allOpenIndices;
}
public String[] getConcreteAllOpenIndices() {
return allOpenIndices;
}
public String[] concreteAllClosedIndices() {
return allClosedIndices;
}
public String[] getConcreteAllClosedIndices() {
return allClosedIndices;
}
/**
* Returns indexing routing for the given index.
*/
// TODO: This can be moved to IndexNameExpressionResolver too, but this means that we will support wildcards and other expressions
// in the index,bulk,update and delete apis.
public String resolveIndexRouting(@Nullable String routing, String aliasOrIndex) {
if (aliasOrIndex == null) {
return routing;
}
AliasOrIndex result = getAliasAndIndexLookup().get(aliasOrIndex);
if (result == null || result.isAlias() == false) {
return routing;
}
AliasOrIndex.Alias alias = (AliasOrIndex.Alias) result;
if (result.getIndices().size() > 1) {
String[] indexNames = new String[result.getIndices().size()];
int i = 0;
for (IndexMetaData indexMetaData : result.getIndices()) {
indexNames[i++] = indexMetaData.getIndex();
}
throw new IllegalArgumentException("Alias [" + aliasOrIndex + "] has more than one index associated with it [" + Arrays.toString(indexNames) + "], can't execute a single index op");
}
AliasMetaData aliasMd = alias.getFirstAliasMetaData();
if (aliasMd.indexRouting() != null) {
if (routing != null) {
if (!routing.equals(aliasMd.indexRouting())) {
throw new IllegalArgumentException("Alias [" + aliasOrIndex + "] has index routing associated with it [" + aliasMd.indexRouting() + "], and was provided with routing value [" + routing + "], rejecting operation");
}
}
routing = aliasMd.indexRouting();
}
if (routing != null) {
if (routing.indexOf(',') != -1) {
throw new IllegalArgumentException("index/alias [" + aliasOrIndex + "] provided with routing value [" + routing + "] that resolved to several routing values, rejecting operation");
}
}
return routing;
}
public boolean hasIndex(String index) {
return indices.containsKey(index);
}
public boolean hasConcreteIndex(String index) {
return getAliasAndIndexLookup().containsKey(index);
}
public IndexMetaData index(String index) {
return indices.get(index);
}
public ImmutableOpenMap<String, IndexMetaData> indices() {
return this.indices;
}
public ImmutableOpenMap<String, IndexMetaData> getIndices() {
return indices();
}
public ImmutableOpenMap<String, IndexTemplateMetaData> templates() {
return this.templates;
}
public ImmutableOpenMap<String, IndexTemplateMetaData> getTemplates() {
return this.templates;
}
public ImmutableOpenMap<String, Custom> customs() {
return this.customs;
}
public ImmutableOpenMap<String, Custom> getCustoms() {
return this.customs;
}
public <T extends Custom> T custom(String type) {
return (T) customs.get(type);
}
public int totalNumberOfShards() {
return this.totalNumberOfShards;
}
public int getTotalNumberOfShards() {
return totalNumberOfShards();
}
public int numberOfShards() {
return this.numberOfShards;
}
public int getNumberOfShards() {
return numberOfShards();
}
/**
* Identifies whether the array containing type names given as argument refers to all types
* The empty or null array identifies all types
*
* @param types the array containing types
* @return true if the provided array maps to all types, false otherwise
*/
public static boolean isAllTypes(String[] types) {
return types == null || types.length == 0 || isExplicitAllType(types);
}
/**
* Identifies whether the array containing type names given as argument explicitly refers to all types
* The empty or null array doesn't explicitly map to all types
*
* @param types the array containing index names
* @return true if the provided array explicitly maps to all types, false otherwise
*/
public static boolean isExplicitAllType(String[] types) {
return types != null && types.length == 1 && ALL.equals(types[0]);
}
/**
* @param concreteIndex The concrete index to check if routing is required
* @param type The type to check if routing is required
* @return Whether routing is required according to the mapping for the specified index and type
*/
public boolean routingRequired(String concreteIndex, String type) {
IndexMetaData indexMetaData = indices.get(concreteIndex);
if (indexMetaData != null) {
MappingMetaData mappingMetaData = indexMetaData.getMappings().get(type);
if (mappingMetaData != null) {
return mappingMetaData.routing().required();
}
}
return false;
}
@Override
public UnmodifiableIterator<IndexMetaData> iterator() {
return indices.valuesIt();
}
public static boolean isGlobalStateEquals(MetaData metaData1, MetaData metaData2) {
if (!metaData1.persistentSettings.equals(metaData2.persistentSettings)) {
return false;
}
if (!metaData1.templates.equals(metaData2.templates())) {
return false;
}
// Check if any persistent metadata needs to be saved
int customCount1 = 0;
for (ObjectObjectCursor<String, Custom> cursor : metaData1.customs) {
if (customPrototypes.get(cursor.key).context().contains(XContentContext.GATEWAY)) {
if (!cursor.value.equals(metaData2.custom(cursor.key))) return false;
customCount1++;
}
}
int customCount2 = 0;
for (ObjectObjectCursor<String, Custom> cursor : metaData2.customs) {
if (customPrototypes.get(cursor.key).context().contains(XContentContext.GATEWAY)) {
customCount2++;
}
}
if (customCount1 != customCount2) return false;
return true;
}
@Override
public Diff<MetaData> diff(MetaData previousState) {
return new MetaDataDiff(previousState, this);
}
@Override
public Diff<MetaData> readDiffFrom(StreamInput in) throws IOException {
return new MetaDataDiff(in);
}
@Override
public MetaData fromXContent(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException {
return Builder.fromXContent(parser);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
Builder.toXContent(this, builder, params);
return builder;
}
private static class MetaDataDiff implements Diff<MetaData> {
private long version;
private String clusterUUID;
private Settings transientSettings;
private Settings persistentSettings;
private Diff<ImmutableOpenMap<String, IndexMetaData>> indices;
private Diff<ImmutableOpenMap<String, IndexTemplateMetaData>> templates;
private Diff<ImmutableOpenMap<String, Custom>> customs;
public MetaDataDiff(MetaData before, MetaData after) {
clusterUUID = after.clusterUUID;
version = after.version;
transientSettings = after.transientSettings;
persistentSettings = after.persistentSettings;
indices = DiffableUtils.diff(before.indices, after.indices);
templates = DiffableUtils.diff(before.templates, after.templates);
customs = DiffableUtils.diff(before.customs, after.customs);
}
public MetaDataDiff(StreamInput in) throws IOException {
clusterUUID = in.readString();
version = in.readLong();
transientSettings = Settings.readSettingsFromStream(in);
persistentSettings = Settings.readSettingsFromStream(in);
indices = DiffableUtils.readImmutableOpenMapDiff(in, IndexMetaData.PROTO);
templates = DiffableUtils.readImmutableOpenMapDiff(in, IndexTemplateMetaData.PROTO);
customs = DiffableUtils.readImmutableOpenMapDiff(in, new KeyedReader<Custom>() {
@Override
public Custom readFrom(StreamInput in, String key) throws IOException {
return lookupPrototypeSafe(key).readFrom(in);
}
@Override
public Diff<Custom> readDiffFrom(StreamInput in, String key) throws IOException {
return lookupPrototypeSafe(key).readDiffFrom(in);
}
});
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(clusterUUID);
out.writeLong(version);
Settings.writeSettingsToStream(transientSettings, out);
Settings.writeSettingsToStream(persistentSettings, out);
indices.writeTo(out);
templates.writeTo(out);
customs.writeTo(out);
}
@Override
public MetaData apply(MetaData part) {
Builder builder = builder();
builder.clusterUUID(clusterUUID);
builder.version(version);
builder.transientSettings(transientSettings);
builder.persistentSettings(persistentSettings);
builder.indices(indices.apply(part.indices));
builder.templates(templates.apply(part.templates));
builder.customs(customs.apply(part.customs));
return builder.build();
}
}
@Override
public MetaData readFrom(StreamInput in) throws IOException {
Builder builder = new Builder();
builder.version = in.readLong();
builder.clusterUUID = in.readString();
builder.transientSettings(readSettingsFromStream(in));
builder.persistentSettings(readSettingsFromStream(in));
int size = in.readVInt();
for (int i = 0; i < size; i++) {
builder.put(IndexMetaData.Builder.readFrom(in), false);
}
size = in.readVInt();
for (int i = 0; i < size; i++) {
builder.put(IndexTemplateMetaData.Builder.readFrom(in));
}
int customSize = in.readVInt();
for (int i = 0; i < customSize; i++) {
String type = in.readString();
Custom customIndexMetaData = lookupPrototypeSafe(type).readFrom(in);
builder.putCustom(type, customIndexMetaData);
}
return builder.build();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeLong(version);
out.writeString(clusterUUID);
writeSettingsToStream(transientSettings, out);
writeSettingsToStream(persistentSettings, out);
out.writeVInt(indices.size());
for (IndexMetaData indexMetaData : this) {
indexMetaData.writeTo(out);
}
out.writeVInt(templates.size());
for (ObjectCursor<IndexTemplateMetaData> cursor : templates.values()) {
cursor.value.writeTo(out);
}
out.writeVInt(customs.size());
for (ObjectObjectCursor<String, Custom> cursor : customs) {
out.writeString(cursor.key);
cursor.value.writeTo(out);
}
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(MetaData metaData) {
return new Builder(metaData);
}
/** All known byte-sized cluster settings. */
public static final Set<String> CLUSTER_BYTES_SIZE_SETTINGS = ImmutableSet.of(
IndicesStore.INDICES_STORE_THROTTLE_MAX_BYTES_PER_SEC,
RecoverySettings.INDICES_RECOVERY_FILE_CHUNK_SIZE,
RecoverySettings.INDICES_RECOVERY_TRANSLOG_SIZE,
RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC,
RecoverySettings.INDICES_RECOVERY_MAX_SIZE_PER_SEC);
/** All known time cluster settings. */
public static final Set<String> CLUSTER_TIME_SETTINGS = ImmutableSet.of(
IndicesTTLService.INDICES_TTL_INTERVAL,
RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC,
RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_NETWORK,
RecoverySettings.INDICES_RECOVERY_ACTIVITY_TIMEOUT,
RecoverySettings.INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT,
RecoverySettings.INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT,
DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_REROUTE_INTERVAL,
InternalClusterInfoService.INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL,
InternalClusterInfoService.INTERNAL_CLUSTER_INFO_TIMEOUT,
DiscoverySettings.PUBLISH_TIMEOUT,
InternalClusterService.SETTING_CLUSTER_SERVICE_SLOW_TASK_LOGGING_THRESHOLD);
/** As of 2.0 we require units for time and byte-sized settings. This methods adds default units to any cluster settings that don't
* specify a unit. */
public static MetaData addDefaultUnitsIfNeeded(ESLogger logger, MetaData metaData) {
Settings.Builder newPersistentSettings = null;
for(Map.Entry<String,String> ent : metaData.persistentSettings().getAsMap().entrySet()) {
String settingName = ent.getKey();
String settingValue = ent.getValue();
if (CLUSTER_BYTES_SIZE_SETTINGS.contains(settingName)) {
try {
Long.parseLong(settingValue);
} catch (NumberFormatException nfe) {
continue;
}
// It's a naked number that previously would be interpreted as default unit (bytes); now we add it:
logger.warn("byte-sized cluster setting [{}] with value [{}] is missing units; assuming default units (b) but in future versions this will be a hard error", settingName, settingValue);
if (newPersistentSettings == null) {
newPersistentSettings = Settings.builder();
newPersistentSettings.put(metaData.persistentSettings());
}
newPersistentSettings.put(settingName, settingValue + "b");
}
if (CLUSTER_TIME_SETTINGS.contains(settingName)) {
try {
Long.parseLong(settingValue);
} catch (NumberFormatException nfe) {
continue;
}
// It's a naked number that previously would be interpreted as default unit (ms); now we add it:
logger.warn("time cluster setting [{}] with value [{}] is missing units; assuming default units (ms) but in future versions this will be a hard error", settingName, settingValue);
if (newPersistentSettings == null) {
newPersistentSettings = Settings.builder();
newPersistentSettings.put(metaData.persistentSettings());
}
newPersistentSettings.put(settingName, settingValue + "ms");
}
}
if (newPersistentSettings != null) {
return new MetaData(
metaData.clusterUUID(),
metaData.version(),
metaData.transientSettings(),
newPersistentSettings.build(),
metaData.getIndices(),
metaData.getTemplates(),
metaData.getCustoms(),
metaData.concreteAllIndices(),
metaData.concreteAllOpenIndices(),
metaData.concreteAllClosedIndices(),
metaData.getAliasAndIndexLookup());
} else {
// No changes:
return metaData;
}
}
public static class Builder {
private String clusterUUID;
private long version;
private Settings transientSettings = Settings.Builder.EMPTY_SETTINGS;
private Settings persistentSettings = Settings.Builder.EMPTY_SETTINGS;
private final ImmutableOpenMap.Builder<String, IndexMetaData> indices;
private final ImmutableOpenMap.Builder<String, IndexTemplateMetaData> templates;
private final ImmutableOpenMap.Builder<String, Custom> customs;
public Builder() {
clusterUUID = "_na_";
indices = ImmutableOpenMap.builder();
templates = ImmutableOpenMap.builder();
customs = ImmutableOpenMap.builder();
}
public Builder(MetaData metaData) {
this.clusterUUID = metaData.clusterUUID;
this.transientSettings = metaData.transientSettings;
this.persistentSettings = metaData.persistentSettings;
this.version = metaData.version;
this.indices = ImmutableOpenMap.builder(metaData.indices);
this.templates = ImmutableOpenMap.builder(metaData.templates);
this.customs = ImmutableOpenMap.builder(metaData.customs);
}
public Builder put(IndexMetaData.Builder indexMetaDataBuilder) {
// we know its a new one, increment the version and store
indexMetaDataBuilder.version(indexMetaDataBuilder.version() + 1);
IndexMetaData indexMetaData = indexMetaDataBuilder.build();
indices.put(indexMetaData.index(), indexMetaData);
return this;
}
public Builder put(IndexMetaData indexMetaData, boolean incrementVersion) {
if (indices.get(indexMetaData.index()) == indexMetaData) {
return this;
}
// if we put a new index metadata, increment its version
if (incrementVersion) {
indexMetaData = IndexMetaData.builder(indexMetaData).version(indexMetaData.version() + 1).build();
}
indices.put(indexMetaData.index(), indexMetaData);
return this;
}
public IndexMetaData get(String index) {
return indices.get(index);
}
public Builder remove(String index) {
indices.remove(index);
return this;
}
public Builder removeAllIndices() {
indices.clear();
return this;
}
public Builder indices(ImmutableOpenMap<String, IndexMetaData> indices) {
this.indices.putAll(indices);
return this;
}
public Builder put(IndexTemplateMetaData.Builder template) {
return put(template.build());
}
public Builder put(IndexTemplateMetaData template) {
templates.put(template.name(), template);
return this;
}
public Builder removeTemplate(String templateName) {
templates.remove(templateName);
return this;
}
public Builder templates(ImmutableOpenMap<String, IndexTemplateMetaData> templates) {
this.templates.putAll(templates);
return this;
}
public Custom getCustom(String type) {
return customs.get(type);
}
public Builder putCustom(String type, Custom custom) {
customs.put(type, custom);
return this;
}
public Builder removeCustom(String type) {
customs.remove(type);
return this;
}
public Builder customs(ImmutableOpenMap<String, Custom> customs) {
this.customs.putAll(customs);
return this;
}
public Builder updateSettings(Settings settings, String... indices) {
if (indices == null || indices.length == 0) {
indices = this.indices.keys().toArray(String.class);
}
for (String index : indices) {
IndexMetaData indexMetaData = this.indices.get(index);
if (indexMetaData == null) {
throw new IndexNotFoundException(index);
}
put(IndexMetaData.builder(indexMetaData)
.settings(settingsBuilder().put(indexMetaData.settings()).put(settings)));
}
return this;
}
public Builder updateNumberOfReplicas(int numberOfReplicas, String... indices) {
if (indices == null || indices.length == 0) {
indices = this.indices.keys().toArray(String.class);
}
for (String index : indices) {
IndexMetaData indexMetaData = this.indices.get(index);
if (indexMetaData == null) {
throw new IndexNotFoundException(index);
}
put(IndexMetaData.builder(indexMetaData).numberOfReplicas(numberOfReplicas));
}
return this;
}
public Settings transientSettings() {
return this.transientSettings;
}
public Builder transientSettings(Settings settings) {
this.transientSettings = settings;
return this;
}
public Settings persistentSettings() {
return this.persistentSettings;
}
public Builder persistentSettings(Settings settings) {
this.persistentSettings = settings;
return this;
}
public Builder version(long version) {
this.version = version;
return this;
}
public Builder clusterUUID(String clusterUUID) {
this.clusterUUID = clusterUUID;
return this;
}
public Builder generateClusterUuidIfNeeded() {
if (clusterUUID.equals("_na_")) {
clusterUUID = Strings.randomBase64UUID();
}
return this;
}
public MetaData build() {
// TODO: We should move these datastructures to IndexNameExpressionResolver, this will give the following benefits:
// 1) The datastructures will only be rebuilded when needed. Now during serailizing we rebuild these datastructures
// while these datastructures aren't even used.
// 2) The aliasAndIndexLookup can be updated instead of rebuilding it all the time.
// build all concrete indices arrays:
// TODO: I think we can remove these arrays. it isn't worth the effort, for operations on all indices.
// When doing an operation across all indices, most of the time is spent on actually going to all shards and
// do the required operations, the bottleneck isn't resolving expressions into concrete indices.
List<String> allIndicesLst = Lists.newArrayList();
for (ObjectCursor<IndexMetaData> cursor : indices.values()) {
allIndicesLst.add(cursor.value.index());
}
String[] allIndices = allIndicesLst.toArray(new String[allIndicesLst.size()]);
List<String> allOpenIndicesLst = Lists.newArrayList();
List<String> allClosedIndicesLst = Lists.newArrayList();
for (ObjectCursor<IndexMetaData> cursor : indices.values()) {
IndexMetaData indexMetaData = cursor.value;
if (indexMetaData.state() == IndexMetaData.State.OPEN) {
allOpenIndicesLst.add(indexMetaData.index());
} else if (indexMetaData.state() == IndexMetaData.State.CLOSE) {
allClosedIndicesLst.add(indexMetaData.index());
}
}
String[] allOpenIndices = allOpenIndicesLst.toArray(new String[allOpenIndicesLst.size()]);
String[] allClosedIndices = allClosedIndicesLst.toArray(new String[allClosedIndicesLst.size()]);
// build all indices map
SortedMap<String, AliasOrIndex> aliasAndIndexLookup = new TreeMap<>();
for (ObjectCursor<IndexMetaData> cursor : indices.values()) {
IndexMetaData indexMetaData = cursor.value;
aliasAndIndexLookup.put(indexMetaData.getIndex(), new AliasOrIndex.Index(indexMetaData));
for (ObjectObjectCursor<String, AliasMetaData> aliasCursor : indexMetaData.getAliases()) {
AliasMetaData aliasMetaData = aliasCursor.value;
AliasOrIndex.Alias aliasOrIndex = (AliasOrIndex.Alias) aliasAndIndexLookup.get(aliasMetaData.getAlias());
if (aliasOrIndex == null) {
aliasOrIndex = new AliasOrIndex.Alias(aliasMetaData, indexMetaData);
aliasAndIndexLookup.put(aliasMetaData.getAlias(), aliasOrIndex);
} else {
aliasOrIndex.addIndex(indexMetaData);
}
}
}
aliasAndIndexLookup = Collections.unmodifiableSortedMap(aliasAndIndexLookup);
return new MetaData(clusterUUID, version, transientSettings, persistentSettings, indices.build(), templates.build(), customs.build(), allIndices, allOpenIndices, allClosedIndices, aliasAndIndexLookup);
}
public static String toXContent(MetaData metaData) throws IOException {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.startObject();
toXContent(metaData, builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
return builder.string();
}
public static void toXContent(MetaData metaData, XContentBuilder builder, ToXContent.Params params) throws IOException {
XContentContext context = XContentContext.valueOf(params.param(CONTEXT_MODE_PARAM, "API"));
builder.startObject("meta-data");
builder.field("version", metaData.version());
builder.field("cluster_uuid", metaData.clusterUUID);
if (!metaData.persistentSettings().getAsMap().isEmpty()) {
builder.startObject("settings");
for (Map.Entry<String, String> entry : metaData.persistentSettings().getAsMap().entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
}
if (context == XContentContext.API && !metaData.transientSettings().getAsMap().isEmpty()) {
builder.startObject("transient_settings");
for (Map.Entry<String, String> entry : metaData.transientSettings().getAsMap().entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
}
builder.startObject("templates");
for (ObjectCursor<IndexTemplateMetaData> cursor : metaData.templates().values()) {
IndexTemplateMetaData.Builder.toXContent(cursor.value, builder, params);
}
builder.endObject();
if (context == XContentContext.API && !metaData.indices().isEmpty()) {
builder.startObject("indices");
for (IndexMetaData indexMetaData : metaData) {
IndexMetaData.Builder.toXContent(indexMetaData, builder, params);
}
builder.endObject();
}
for (ObjectObjectCursor<String, Custom> cursor : metaData.customs()) {
Custom proto = lookupPrototypeSafe(cursor.key);
if (proto.context().contains(context)) {
builder.startObject(cursor.key);
cursor.value.toXContent(builder, params);
builder.endObject();
}
}
builder.endObject();
}
public static MetaData fromXContent(XContentParser parser) throws IOException {
Builder builder = new Builder();
// we might get here after the meta-data element, or on a fresh parser
XContentParser.Token token = parser.currentToken();
String currentFieldName = parser.currentName();
if (!"meta-data".equals(currentFieldName)) {
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
// move to the field name (meta-data)
token = parser.nextToken();
// move to the next object
token = parser.nextToken();
}
currentFieldName = parser.currentName();
if (token == null) {
// no data...
return builder.build();
}
}
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("settings".equals(currentFieldName)) {
builder.persistentSettings(Settings.settingsBuilder().put(SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered())).build());
} else if ("indices".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
builder.put(IndexMetaData.Builder.fromXContent(parser), false);
}
} else if ("templates".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
builder.put(IndexTemplateMetaData.Builder.fromXContent(parser, parser.currentName()));
}
} else {
// check if its a custom index metadata
Custom proto = lookupPrototype(currentFieldName);
if (proto == null) {
//TODO warn
parser.skipChildren();
} else {
Custom custom = proto.fromXContent(parser);
builder.putCustom(custom.type(), custom);
}
}
} else if (token.isValue()) {
if ("version".equals(currentFieldName)) {
builder.version = parser.longValue();
} else if ("cluster_uuid".equals(currentFieldName) || "uuid".equals(currentFieldName)) {
builder.clusterUUID = parser.text();
}
}
}
return builder.build();
}
public static MetaData readFrom(StreamInput in) throws IOException {
return PROTO.readFrom(in);
}
}
}
|
|
/*
* 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.atlas.data;
import java.io.*;
import java.util.*;
import org.apache.jena.atlas.AtlasException;
import org.apache.jena.atlas.data.AbortableComparator.Finish;
import org.apache.jena.atlas.iterator.Iter;
import org.apache.jena.atlas.iterator.IteratorCloseable;
import org.apache.jena.atlas.lib.Sink;
/**
* <p>
* This data bag will gather items in memory until a size threshold is passed,
* at which point it will write out all of the items to disk using the supplied
* serializer.
* </p>
* <p>
* After adding is finished, call {@link #iterator()} to set up the data bag for
* reading back items and iterating over them. The iterator will retrieve the
* items in sorted order using the supplied comparator.
* </p>
* <p>
* IMPORTANT: You may not add any more items after this call. You may
* subsequently call {@link #iterator()} multiple times which will give you a
* new iterator for each invocation. If you do not consume the entire iterator,
* you should call {@link Iter#close(Iterator)} to close any FileInputStreams
* associated with the iterator.
* </p>
* <p>
* Additionally, make sure to call {@link #close()} when you are finished to
* free any system resources (preferably in a finally block).
* </p>
* <p>
* Implementation Notes: Data is stored in an ArrayList as it comes in. When it
* is time to spill, that data is sorted and written to disk. An iterator will
* read in each file and perform a merge-sort as the results are returned.
* </p>
*/
public class SortedDataBag<E> extends AbstractDataBag<E> {
/**
* The the maximum number of files to merge at the same time. Without this, you
* can run out of file handles and other bad things.
*/
protected static int MAX_SPILL_FILES = 100;
protected final ThresholdPolicy<E> policy;
protected final SerializationFactory<E> serializationFactory;
protected final AbortableComparator<E> comparator;
protected boolean finishedAdding = false;
protected boolean spilled = false;
protected boolean closed = false;
public SortedDataBag(ThresholdPolicy<E> policy, SerializationFactory<E> serializerFactory, Comparator<? super E> comparator) {
this.policy = policy;
this.serializationFactory = serializerFactory;
this.comparator = new AbortableComparator<>(comparator);
}
/**
* cancel arranges that further comparisons using the supplied comparator will
* abandon the sort in progress.
*/
public void cancel() {
comparator.cancel();
close();
}
/**
* isCancelled is true iff cancel has been called on this bags comparator. (Used
* in testing.)
*/
public boolean isCancelled() {
return comparator.cancelled;
}
/**
* isClosed returns true iff this bag has been closed. (Used in testing.)
*/
public boolean isClosed() {
return closed;
}
protected void checkClosed() {
if ( closed )
throw new AtlasException("SortedDataBag is closed, no operations can be performed on it.");
}
@Override
public boolean isSorted() {
return true;
}
@Override
public boolean isDistinct() {
return false;
}
@Override
public void add(E item) {
checkClosed();
if ( finishedAdding )
throw new AtlasException("SortedDataBag: Cannot add any more items after the writing phase is complete.");
if ( policy.isThresholdExceeded() ) {
spill();
}
if ( memory.add(item) ) {
policy.increment(item);
size++;
}
}
@SuppressWarnings({"unchecked"})
protected void spill() {
// Make sure we have something to spill.
if ( memory.size() > 0 ) {
OutputStream out;
try {
out = getSpillStream();
} catch (IOException e) {
throw new AtlasException(e);
}
// Sort the tuples as an array. The CanAbortComparator will sort
// the array using Arrays.sort. The cast to E[] is safe. If the sort is
// aborted, don't bother messing around with the serialisation.
// We'll never get around to using it anyway.
E[] array = (E[])memory.toArray();
if ( comparator.abortableSort(array) == Finish.COMPLETED ) {
Sink<E> serializer = serializationFactory.createSerializer(out);
try {
for ( Object tuple : array ) {
serializer.send((E)tuple);
}
}
finally {
serializer.close();
}
}
spilled = true;
policy.reset();
memory.clear();
}
}
@Override
public void flush() {
spill();
}
protected Iterator<E> getInputIterator(File spillFile) throws FileNotFoundException {
InputStream in = getInputStream(spillFile);
Iterator<E> deserializer = serializationFactory.createDeserializer(in);
return Iter.onCloseIO(deserializer, in);
}
/**
* Returns an iterator over a set of elements of type E. If you do not exhaust
* the iterator, you should call
* {@link org.apache.jena.atlas.iterator.Iter#close(Iterator)} to be sure any
* open file handles are closed.
*
* @return an Iterator
*/
@Override
public Iterator<E> iterator() {
preMerge();
return iterator(getSpillFiles().size());
}
@SuppressWarnings({"unchecked"})
private Iterator<E> iterator(int size) {
checkClosed();
int memSize = memory.size();
// Constructing an iterator from this class is not thread-safe (just
// like all the the other methods)
if ( !finishedAdding && memSize > 1 ) {
E[] array = (E[])memory.toArray();
comparator.abortableSort(array); // don't care if we aborted or not
memory = Arrays.asList(array);
}
finishedAdding = true;
if ( spilled ) {
List<Iterator<E>> inputs = new ArrayList<>(size + (memSize > 0 ? 1 : 0));
if ( memSize > 0 ) {
inputs.add(memory.iterator());
}
for ( int i = 0 ; i < size ; i++ ) {
File spillFile = getSpillFiles().get(i);
try {
Iterator<E> irc = getInputIterator(spillFile);
inputs.add(irc);
} catch (FileNotFoundException e) {
// Close any open streams before we throw an exception
for ( Iterator<E> it : inputs ) {
Iter.close(it);
}
throw new AtlasException("Cannot find one of the spill files", e);
}
}
SpillSortIterator<E> ssi = new SpillSortIterator<>(inputs, comparator);
registerCloseableIterator(ssi);
return ssi;
} else {
if ( memSize > 0 ) {
return memory.iterator();
} else {
return Iter.nullIterator();
}
}
}
private void preMerge() {
if ( getSpillFiles() == null || getSpillFiles().size() <= MAX_SPILL_FILES ) {
return;
}
try {
while (getSpillFiles().size() > MAX_SPILL_FILES) {
Sink<E> sink = serializationFactory.createSerializer(getSpillStream());
Iterator<E> ssi = iterator(MAX_SPILL_FILES);
try {
while (ssi.hasNext()) {
sink.send(ssi.next());
}
}
finally {
Iter.close(ssi);
sink.close();
}
List<File> toRemove = new ArrayList<>(MAX_SPILL_FILES);
for ( int i = 0 ; i < MAX_SPILL_FILES ; i++ ) {
File file = getSpillFiles().get(i);
file.delete();
toRemove.add(file);
}
getSpillFiles().removeAll(toRemove);
memory = new ArrayList<>();
}
} catch (IOException e) {
throw new AtlasException(e);
}
}
@Override
public void close() {
if ( !closed ) {
closeIterators();
deleteSpillFiles();
memory = null;
closed = true;
}
}
/**
* An iterator that handles getting the next tuple from the bag.
*/
protected static class SpillSortIterator<T> implements IteratorCloseable<T> {
private final List<Iterator<T>> inputs;
private final Comparator<? super T> comp;
private final PriorityQueue<Item<T>> minHeap;
public SpillSortIterator(List<Iterator<T>> inputs, Comparator<? super T> comp) {
this.inputs = inputs;
this.comp = comp;
this.minHeap = new PriorityQueue<>(inputs.size());
// Prime the heap
for ( int i = 0 ; i < inputs.size() ; i++ ) {
replaceItem(i);
}
}
private void replaceItem(int index) {
Iterator<T> it = inputs.get(index);
if ( it.hasNext() ) {
T tuple = it.next();
minHeap.add(new Item<>(index, tuple, comp));
}
}
@Override
public boolean hasNext() {
return (minHeap.peek() != null);
}
@Override
public T next() {
if ( !hasNext() ) {
throw new NoSuchElementException();
}
Item<T> curr = minHeap.poll();
// Read replacement item
replaceItem(curr.getIndex());
return curr.getTuple();
}
@Override
public void remove() {
throw new UnsupportedOperationException("SpillSortIterator.remove");
}
@Override
public void close() {
for ( Iterator<T> it : inputs ) {
Iter.close(it);
}
}
private final class Item<U> implements Comparable<Item<U>> {
private final int index;
private final U tuple;
private final Comparator<? super U> c;
public Item(int index, U tuple, Comparator<? super U> c) {
this.index = index;
this.tuple = tuple;
this.c = c;
}
public int getIndex() {
return index;
}
public U getTuple() {
return tuple;
}
@Override
@SuppressWarnings("unchecked")
public int compareTo(Item<U> o) {
return (null != c) ? c.compare(tuple, o.getTuple()) : ((Comparable<U>)tuple).compareTo(o.getTuple());
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
if ( obj instanceof Item ) {
return compareTo((Item<U>)obj) == 0;
}
return false;
}
@Override
public int hashCode() {
return tuple.hashCode();
}
}
}
}
|
|
// This file was generated by Mendix Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package imdbtests.proxies;
public class Principals
{
private final com.mendix.systemwideinterfaces.core.IMendixObject principalsMendixObject;
private final com.mendix.systemwideinterfaces.core.IContext context;
/**
* Internal name of this entity
*/
public static final java.lang.String entityName = "ImdbTests.Principals";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
TitleId("TitleId"),
Ordering("Ordering"),
PersonId("PersonId"),
Category("Category"),
Job("Job"),
Characters("Characters"),
Principals_Title("ImdbTests.Principals_Title"),
Principals_Name("ImdbTests.Principals_Name");
private java.lang.String metaName;
MemberNames(java.lang.String s)
{
metaName = s;
}
@java.lang.Override
public java.lang.String toString()
{
return metaName;
}
}
public Principals(com.mendix.systemwideinterfaces.core.IContext context)
{
this(context, com.mendix.core.Core.instantiate(context, "ImdbTests.Principals"));
}
protected Principals(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject principalsMendixObject)
{
if (principalsMendixObject == null)
throw new java.lang.IllegalArgumentException("The given object cannot be null.");
if (!com.mendix.core.Core.isSubClassOf("ImdbTests.Principals", principalsMendixObject.getType()))
throw new java.lang.IllegalArgumentException("The given object is not a ImdbTests.Principals");
this.principalsMendixObject = principalsMendixObject;
this.context = context;
}
/**
* @deprecated Use 'Principals.load(IContext, IMendixIdentifier)' instead.
*/
@java.lang.Deprecated
public static imdbtests.proxies.Principals initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
return imdbtests.proxies.Principals.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access).
*/
public static imdbtests.proxies.Principals initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject)
{
return new imdbtests.proxies.Principals(context, mendixObject);
}
public static imdbtests.proxies.Principals load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException
{
com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier);
return imdbtests.proxies.Principals.initialize(context, mendixObject);
}
public static java.util.List<imdbtests.proxies.Principals> load(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String xpathConstraint) throws com.mendix.core.CoreException
{
java.util.List<imdbtests.proxies.Principals> result = new java.util.ArrayList<imdbtests.proxies.Principals>();
for (com.mendix.systemwideinterfaces.core.IMendixObject obj : com.mendix.core.Core.retrieveXPathQuery(context, "//ImdbTests.Principals" + xpathConstraint))
result.add(imdbtests.proxies.Principals.initialize(context, obj));
return result;
}
/**
* Commit the changes made on this proxy object.
*/
public final void commit() throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Commit the changes made on this proxy object using the specified context.
*/
public final void commit(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
com.mendix.core.Core.commit(context, getMendixObject());
}
/**
* Delete the object.
*/
public final void delete()
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* Delete the object using the specified context.
*/
public final void delete(com.mendix.systemwideinterfaces.core.IContext context)
{
com.mendix.core.Core.delete(context, getMendixObject());
}
/**
* @return value of TitleId
*/
public final java.lang.String getTitleId()
{
return getTitleId(getContext());
}
/**
* @param context
* @return value of TitleId
*/
public final java.lang.String getTitleId(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.TitleId.toString());
}
/**
* Set value of TitleId
* @param titleid
*/
public final void setTitleId(java.lang.String titleid)
{
setTitleId(getContext(), titleid);
}
/**
* Set value of TitleId
* @param context
* @param titleid
*/
public final void setTitleId(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String titleid)
{
getMendixObject().setValue(context, MemberNames.TitleId.toString(), titleid);
}
/**
* @return value of Ordering
*/
public final java.lang.Long getOrdering()
{
return getOrdering(getContext());
}
/**
* @param context
* @return value of Ordering
*/
public final java.lang.Long getOrdering(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.Long) getMendixObject().getValue(context, MemberNames.Ordering.toString());
}
/**
* Set value of Ordering
* @param ordering
*/
public final void setOrdering(java.lang.Long ordering)
{
setOrdering(getContext(), ordering);
}
/**
* Set value of Ordering
* @param context
* @param ordering
*/
public final void setOrdering(com.mendix.systemwideinterfaces.core.IContext context, java.lang.Long ordering)
{
getMendixObject().setValue(context, MemberNames.Ordering.toString(), ordering);
}
/**
* @return value of PersonId
*/
public final java.lang.String getPersonId()
{
return getPersonId(getContext());
}
/**
* @param context
* @return value of PersonId
*/
public final java.lang.String getPersonId(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.PersonId.toString());
}
/**
* Set value of PersonId
* @param personid
*/
public final void setPersonId(java.lang.String personid)
{
setPersonId(getContext(), personid);
}
/**
* Set value of PersonId
* @param context
* @param personid
*/
public final void setPersonId(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String personid)
{
getMendixObject().setValue(context, MemberNames.PersonId.toString(), personid);
}
/**
* @return value of Category
*/
public final java.lang.String getCategory()
{
return getCategory(getContext());
}
/**
* @param context
* @return value of Category
*/
public final java.lang.String getCategory(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.Category.toString());
}
/**
* Set value of Category
* @param category
*/
public final void setCategory(java.lang.String category)
{
setCategory(getContext(), category);
}
/**
* Set value of Category
* @param context
* @param category
*/
public final void setCategory(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String category)
{
getMendixObject().setValue(context, MemberNames.Category.toString(), category);
}
/**
* @return value of Job
*/
public final java.lang.String getJob()
{
return getJob(getContext());
}
/**
* @param context
* @return value of Job
*/
public final java.lang.String getJob(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.Job.toString());
}
/**
* Set value of Job
* @param job
*/
public final void setJob(java.lang.String job)
{
setJob(getContext(), job);
}
/**
* Set value of Job
* @param context
* @param job
*/
public final void setJob(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String job)
{
getMendixObject().setValue(context, MemberNames.Job.toString(), job);
}
/**
* @return value of Characters
*/
public final java.lang.String getCharacters()
{
return getCharacters(getContext());
}
/**
* @param context
* @return value of Characters
*/
public final java.lang.String getCharacters(com.mendix.systemwideinterfaces.core.IContext context)
{
return (java.lang.String) getMendixObject().getValue(context, MemberNames.Characters.toString());
}
/**
* Set value of Characters
* @param characters
*/
public final void setCharacters(java.lang.String characters)
{
setCharacters(getContext(), characters);
}
/**
* Set value of Characters
* @param context
* @param characters
*/
public final void setCharacters(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String characters)
{
getMendixObject().setValue(context, MemberNames.Characters.toString(), characters);
}
/**
* @return value of Principals_Title
*/
public final imdbtests.proxies.Title getPrincipals_Title() throws com.mendix.core.CoreException
{
return getPrincipals_Title(getContext());
}
/**
* @param context
* @return value of Principals_Title
*/
public final imdbtests.proxies.Title getPrincipals_Title(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
imdbtests.proxies.Title result = null;
com.mendix.systemwideinterfaces.core.IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.Principals_Title.toString());
if (identifier != null)
result = imdbtests.proxies.Title.load(context, identifier);
return result;
}
/**
* Set value of Principals_Title
* @param principals_title
*/
public final void setPrincipals_Title(imdbtests.proxies.Title principals_title)
{
setPrincipals_Title(getContext(), principals_title);
}
/**
* Set value of Principals_Title
* @param context
* @param principals_title
*/
public final void setPrincipals_Title(com.mendix.systemwideinterfaces.core.IContext context, imdbtests.proxies.Title principals_title)
{
if (principals_title == null)
getMendixObject().setValue(context, MemberNames.Principals_Title.toString(), null);
else
getMendixObject().setValue(context, MemberNames.Principals_Title.toString(), principals_title.getMendixObject().getId());
}
/**
* @return value of Principals_Name
*/
public final imdbtests.proxies.NameBasics getPrincipals_Name() throws com.mendix.core.CoreException
{
return getPrincipals_Name(getContext());
}
/**
* @param context
* @return value of Principals_Name
*/
public final imdbtests.proxies.NameBasics getPrincipals_Name(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException
{
imdbtests.proxies.NameBasics result = null;
com.mendix.systemwideinterfaces.core.IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.Principals_Name.toString());
if (identifier != null)
result = imdbtests.proxies.NameBasics.load(context, identifier);
return result;
}
/**
* Set value of Principals_Name
* @param principals_name
*/
public final void setPrincipals_Name(imdbtests.proxies.NameBasics principals_name)
{
setPrincipals_Name(getContext(), principals_name);
}
/**
* Set value of Principals_Name
* @param context
* @param principals_name
*/
public final void setPrincipals_Name(com.mendix.systemwideinterfaces.core.IContext context, imdbtests.proxies.NameBasics principals_name)
{
if (principals_name == null)
getMendixObject().setValue(context, MemberNames.Principals_Name.toString(), null);
else
getMendixObject().setValue(context, MemberNames.Principals_Name.toString(), principals_name.getMendixObject().getId());
}
/**
* @return the IMendixObject instance of this proxy for use in the Core interface.
*/
public final com.mendix.systemwideinterfaces.core.IMendixObject getMendixObject()
{
return principalsMendixObject;
}
/**
* @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
*/
public final com.mendix.systemwideinterfaces.core.IContext getContext()
{
return context;
}
@java.lang.Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final imdbtests.proxies.Principals that = (imdbtests.proxies.Principals) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@java.lang.Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static java.lang.String getType()
{
return "ImdbTests.Principals";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@java.lang.Deprecated
public java.lang.String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
|
|
/*
*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.core.api;
import org.wso2.carbon.apimgt.core.dao.ApiType;
import org.wso2.carbon.apimgt.core.exception.APICommentException;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.APIMgtDAOException;
import org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException;
import org.wso2.carbon.apimgt.core.exception.APIMgtWSDLException;
import org.wso2.carbon.apimgt.core.exception.APINotFoundException;
import org.wso2.carbon.apimgt.core.exception.APIRatingException;
import org.wso2.carbon.apimgt.core.exception.LabelException;
import org.wso2.carbon.apimgt.core.models.API;
import org.wso2.carbon.apimgt.core.models.Application;
import org.wso2.carbon.apimgt.core.models.ApplicationToken;
import org.wso2.carbon.apimgt.core.models.Comment;
import org.wso2.carbon.apimgt.core.models.CompositeAPI;
import org.wso2.carbon.apimgt.core.models.Label;
import org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo;
import org.wso2.carbon.apimgt.core.models.Rating;
import org.wso2.carbon.apimgt.core.models.Subscription;
import org.wso2.carbon.apimgt.core.models.SubscriptionResponse;
import org.wso2.carbon.apimgt.core.models.Tag;
import org.wso2.carbon.apimgt.core.models.User;
import org.wso2.carbon.apimgt.core.models.WSDLArchiveInfo;
import org.wso2.carbon.apimgt.core.models.policy.Policy;
import org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse;
import java.io.InputStream;
import java.util.List;
/**
* This interface used to write Store specific methods.
*
*/
public interface APIStore extends APIManager {
/**
* Returns details of an API
*
* @param id ID of the API
* @return An CompositeAPI object for the given id or null
* @throws APIManagementException if failed get CompositeAPI for given id
*/
CompositeAPI getCompositeAPIbyId(String id) throws APIManagementException;
/**
* Returns a paginated list of all APIs in given Status list. If a given API has multiple APIs,
* only the latest version will be included in this list.
*
* @param offset offset
* @param limit limit
* @param status One or more Statuses
* @return {@code List<API>}
* @throws APIManagementException if failed to API set
*/
List<API> getAllAPIsByStatus(int offset, int limit, String[] status) throws APIManagementException;
/**
* Returns a paginated list of all APIs which match the given search criteria.
*
* @param query searchType
* @param limit limit
* @param offset offset
* @return {@code List<API>}
* @throws APIManagementException If failed to search apis.
*/
List<API> searchAPIs(String query, int offset, int limit) throws APIManagementException;
/**
* Returns a paginated list of all Composite APIs which match the given search criteria.
*
* @param query searchType
* @param limit limit
* @param offset offset
* @return {@code List<CompositeAPI>}
* @throws APIManagementException If failed to search apis.
*/
List<CompositeAPI> searchCompositeAPIs(String query, int offset, int limit) throws APIManagementException;
/**
* Returns Swagger definition of a Composite API
*
* @param id ID of the API
* @return The CompositeAPI Swagger definition
* @throws APIManagementException if failed get CompositeAPI implementation for given id
*/
String getCompositeApiDefinition(String id) throws APIManagementException;
/**
* Checks the existence of a Composite API with {@code apiId}.
*
* @param apiId API id of the Composite API
* @return {@code true} if Composite API with {@code apiId} exists
* {@code false} otherwise.
* @throws APIManagementException if failed to retrieve summary of Composite API with {@code apiId}
*/
boolean isCompositeAPIExist(String apiId) throws APIManagementException;
/**
* Update Swagger definition of a Composite API
*
* @param id ID of the API
* @param apiDefinition CompositeAPI Swagger definition
* @throws APIManagementException if failed get CompositeAPI implementation for given id
*/
void updateCompositeApiDefinition(String id, String apiDefinition) throws APIManagementException;
/**
* Returns Ballerina implementation of a Composite API
*
* @param id ID of the API
* @return File of the CompositeAPI implementation
* @throws APIManagementException if failed get CompositeAPI implementation for given id
*/
InputStream getCompositeApiImplementation(String id) throws APIManagementException;
/**
* Update Ballerina implementation of a Composite API
*
* @param id ID of the API
* @param implementation CompositeAPI Ballerina implementation file
* @throws APIManagementException if failed get CompositeAPI implementation for given id
*/
void updateCompositeApiImplementation(String id, InputStream implementation) throws APIManagementException;
/**
* Function to remove an Application from the API Store
*
* @param appId - The Application id of the Application
* @return WorkflowResponse workflow response
* @throws APIManagementException If failed to delete application.
*/
WorkflowResponse deleteApplication(String appId) throws APIManagementException;
/**
* Adds an application
*
* @param application Application
* @return ApplicationCreationResponse
* @throws APIManagementException if failed to add Application
*/
ApplicationCreationResponse addApplication(Application application) throws APIManagementException;
/**
* This will return APIM application by giving name and subscriber
*
* @param applicationName APIM application name
* @param ownerId Application owner ID.
* @return it will return Application.
* @throws APIManagementException Failed to get application by name.
*/
Application getApplicationByName(String applicationName, String ownerId) throws APIManagementException;
/**
* Returns a list of applications for a given subscriber
*
* @param subscriber Subscriber
* @return Applications
* @throws APIManagementException if failed to applications for given subscriber
*/
List<Application> getApplications(String subscriber) throws APIManagementException;
/**
* Updates the details of the specified user application.
* @param uuid Uuid of the existing application
* @param application Application object containing updated data
* @return WorkflowResponse workflow status
* @throws APIManagementException If an error occurs while updating the application
*/
WorkflowResponse updateApplication(String uuid, Application application) throws APIManagementException;
/**
* Generates oAuth keys for an application.
*
* @param applicationId Id of the Application.
* @param keyType Key type (PRODUCTION | SANDBOX)
* @param callbackUrl Callback URL
* @param grantTypes List of grant types to be supported by the application
* @return {@link OAuthApplicationInfo} Generated OAuth client information
* @throws APIManagementException If oauth application creation was failed
*/
OAuthApplicationInfo generateApplicationKeys(String applicationId, String keyType,
String callbackUrl, List<String> grantTypes)
throws APIManagementException;
/**
* Provision out-of-band OAuth clients (Semi-manual client registration)
*
* @param applicationId Application ID
* @param keyType Key type (PRODUCTION | SANDBOX)
* @param clientId Client ID of the OAuth application
* @param clientSecret Client secret of the OAuth application
* @return {@link OAuthApplicationInfo} Existing OAuth client information
* @throws APIManagementException If oauth application mapping was failed
*/
OAuthApplicationInfo mapApplicationKeys(String applicationId, String keyType, String clientId,
String clientSecret) throws APIManagementException;
/**
* Get application key information
*
* @param applicationId Application Id
* @return {@link OAuthApplicationInfo} Application key information list
* @throws APIManagementException if error occurred while retrieving application keys
*/
List<OAuthApplicationInfo> getApplicationKeys(String applicationId) throws APIManagementException;
/**
* Get application key information of a given key type
*
* @param applicationId Application Id
* @param keyType Key Type (Production | Sandbox)
* @return {@link OAuthApplicationInfo} Application key information
* @throws APIManagementException if error occurred while retrieving application keys
*/
OAuthApplicationInfo getApplicationKeys(String applicationId, String keyType) throws APIManagementException;
/**
* Update grantTypes and callback URL of an application
*
* @param applicationId Application Id
* @param keyType Key Type (Production | Sandbox)
* @param grantTypes New Grant Type list
* @param callbackURL New callback URL
* @return {@link OAuthApplicationInfo} Application key information list
* @throws APIManagementException if error occurred while retrieving application keys
*/
OAuthApplicationInfo updateGrantTypesAndCallbackURL(String applicationId, String keyType, List<String> grantTypes,
String callbackURL) throws APIManagementException;
/**
* Generate an application access token (and revoke current token, if any)
*
* @param clientId Consumer Key
* @param clientSecret Consumer Secret
* @param scopes Scope of the token
* @param validityPeriod Token validity period
* @param tokenToBeRevoked Current access token which needs to be revoked
* @return {@link ApplicationToken} object which contains access token, scopes and validity period
* @throws APIManagementException if error occurred while generating access token
*/
ApplicationToken generateApplicationToken(String clientId, String clientSecret, String scopes, long validityPeriod,
String tokenToBeRevoked) throws APIManagementException;
/**
* Retrieve an application given the uuid.
*
* @param uuid UUID of the application.
* @return Application object of the given uuid
* @throws APIManagementException If failed to get the application.
*/
Application getApplicationByUuid(String uuid) throws APIManagementException;
/**
* Retrieve list of subscriptions given the application.
*
* @param application Application Object.
* @return List of subscriptions objects of the given application.
* @throws APIManagementException If failed to get the subscriptions for the application.
*/
List<Subscription> getAPISubscriptionsByApplication(Application application) throws APIManagementException;
/**
* Retrieve list of subscriptions given the application and the API Type.
*
* @param application Application Object.
* @param apiType API Type to filter subscriptions
* @return List of subscriptions objects of the given application made for the specified API Type.
* @throws APIManagementException If failed to get the subscriptions for the application.
*/
List<Subscription> getAPISubscriptionsByApplication(Application application, ApiType apiType)
throws APIManagementException;
/**
* Add an api subscription.
*
* @param apiId UUID of the API.
* @param applicationId UUID of the Application
* @param tier Tier level.
* @return SubscriptionResponse Id and the workflow response
* @throws APIManagementException If failed to add the subscription
*/
SubscriptionResponse addApiSubscription(String apiId, String applicationId, String tier)
throws APIManagementException;
/**
* Delete an API subscription.
*
* @param subscriptionId Id of the subscription to be deleted.
* @return WorkflowResponse workflow response
* @throws APIManagementException If failed to delete the subscription.
*/
WorkflowResponse deleteAPISubscription(String subscriptionId) throws APIManagementException;
/**
* Retrieve all tags
*
* @return List of Tag objects
* @throws APIManagementException If failed to retrieve tags
*/
List<Tag> getAllTags() throws APIManagementException;
/**
* Retrieve all policies of given tier level.
* @param tierLevel Tier level.
* @return List of policies for the given tier level.
* @throws APIManagementException If failed to get policies.
*/
List<Policy> getPolicies(APIMgtAdminService.PolicyLevel tierLevel) throws APIManagementException;
/**
* Retrieve all policies of given tier level.
* @param tierLevel Level of the tier.
* @param tierName Name of the tier.
* @return Policy object.
* @throws APIManagementException If failed to get the policy.
*/
Policy getPolicy(APIMgtAdminService.PolicyLevel tierLevel, String tierName) throws APIManagementException;
/**
* Retrieve Label information based on the label name
*
* @param labels List of label names
* @param username Username of the user
* @return {@code List<Label>} List of Labels
* @throws LabelException if failed to get labels
*/
List<Label> getLabelInfo(List<String> labels, String username) throws LabelException;
/**
* Retrieve List of all user Ratings based on API ID
*
* @param apiId UUID of the API
* @return List of Rating Objects
* @throws APIManagementException if failed to get labels
*/
List<Rating> getRatingsListForApi(String apiId) throws APIManagementException;
/**
* Add comment for an API
*
* @param comment the comment text
* @param apiId UUID of the API
* @return String UUID of the created comment
* @throws APICommentException if failed to add a comment
* @throws APIMgtResourceNotFoundException if api not found
*/
String addComment(Comment comment, String apiId) throws APICommentException, APIMgtResourceNotFoundException;
/**
* Delete a comment from an API given the commentId and apiId
*
* @param commentId UUID of the comment to be deleted
* @param apiId UUID of the api
* @param username username of the consumer
* @throws APICommentException if failed to delete a comment
* @throws APIMgtResourceNotFoundException if api or comment not found
*/
void deleteComment(String commentId, String apiId, String username) throws APICommentException,
APIMgtResourceNotFoundException;
/**
* Update a comment
*
* @param comment new Comment object
* @param commentId the id of the comment which needs to be updated
* @param apiId UUID of the api the comment belongs to
* @param username username of the consumer
* @throws APICommentException if failed to update a comment
* @throws APIMgtResourceNotFoundException if api or comment not found
*/
void updateComment(Comment comment, String commentId, String apiId, String username) throws APICommentException,
APIMgtResourceNotFoundException;
/**
* Retrieve list of comments for a given apiId
*
* @param apiId UUID of the api
* @return a list of comments for the api
* @throws APICommentException if failed to retrieve all comments for an api
* @throws APIMgtResourceNotFoundException if api not found
*/
List<Comment> getCommentsForApi(String apiId) throws APICommentException, APIMgtResourceNotFoundException;
/**
* Retrieve Individual Comment based on Comment ID
*
* @param commentId UUID od the comment
* @param apiId UUID of the API
* @return Comment Object.
* @throws APICommentException if failed to retrieve comment from data layer
* @throws APIMgtResourceNotFoundException if api or comment was not found
*/
Comment getCommentByUUID(String commentId, String apiId) throws APICommentException,
APIMgtResourceNotFoundException;
/**
* Creates a new rating
*
* @param apiId UUID of the api
* @param rating the rating object
* @return UUID of the newly created or updated rating
* @throws APIRatingException if failed to add rating
* @throws APIMgtResourceNotFoundException if api not found
*/
String addRating(String apiId, Rating rating) throws APIRatingException, APIMgtResourceNotFoundException;
/**
* Retrieves a rating given its UUID
*
* @param apiId UUID of the api
* @param ratingId UUID of the rating
* @return rating object
* @throws APIRatingException if failed to get rating
* @throws APIMgtResourceNotFoundException if api or rating not found
*/
Rating getRatingByUUID(String apiId, String ratingId) throws APIRatingException, APIMgtResourceNotFoundException;
/**
* Retrieve Average Rating based of an api, up to one decimal point.
*
* @param apiId UUID of the API
* @return Average Rating value
* @throws APIRatingException if failed to get average rating
* @throws APIMgtResourceNotFoundException if api not found
*/
double getAvgRating(String apiId) throws APIRatingException, APIMgtResourceNotFoundException;
/**
* Get user rating for an api
*
* @param apiId UUID of the api
* @param userId unique id of the user
* @return Rating of the user
* @throws APIRatingException if failed to retrieve user rating for the given api
* @throws APIMgtResourceNotFoundException if api or rating not found
*/
Rating getRatingForApiFromUser(String apiId, String userId) throws APIRatingException,
APIMgtResourceNotFoundException;
/**
* Updates an already existing api
*
* @param apiId UUID of the api
* @param ratingId UUID of the rating
* @param ratingFromPayload Rating object created from the request payload
* @throws APIRatingException if failed to update a rating
* @throws APIMgtResourceNotFoundException if api or rating not found
*/
void updateRating(String apiId, String ratingId, Rating ratingFromPayload) throws APIRatingException,
APIMgtResourceNotFoundException;
/**
* Adds a new Composite API
*
* @param apiBuilder API Builder object
* @return Details of the added Composite API.
* @throws APIManagementException if failed to add Composite API
*/
String addCompositeApi(CompositeAPI.Builder apiBuilder) throws APIManagementException;
/**
* Updates design and implementation of an existing Composite API.
*
* @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder}
* @throws APIManagementException if failed to update Composite API
*/
void updateCompositeApi(CompositeAPI.Builder apiBuilder) throws APIManagementException;
/**
* Delete an existing Composite API.
*
* @param apiId API Id
* @throws APIManagementException if failed to delete Composite API
*/
void deleteCompositeApi(String apiId) throws APIManagementException;
/**
* Create a new version of the <code>Composite API</code>, with version <code>newVersion</code>
*
* @param apiId The Composite API to be copied
* @param newVersion The version of the new Composite API
* @return Details of the newly created version of the Composite API.
* @throws APIManagementException If an error occurs while trying to create
* the new version of the Composite API
*/
String createNewCompositeApiVersion(String apiId, String newVersion) throws APIManagementException;
/**
* Create Composite API from Swagger Definition
*
* @param apiDefinition Swagger content of the Composite API.
* @return Details of the added Composite API.
* @throws APIManagementException If failed to add Composite API.
*/
String addCompositeApiFromDefinition(InputStream apiDefinition) throws APIManagementException;
/**
* Create Composite API from Swagger definition located by a given url
*
* @param swaggerResourceUrl url of the Swagger resource
* @return details of the added Composite API.
* @throws APIManagementException If failed to add the Composite API.
*/
String addCompositeApiFromDefinition(String swaggerResourceUrl) throws APIManagementException;
/**
* Returns the WSDL of a given API UUID and gateway label name
*
* @param apiId API Id
* @param labelName gateway label name
* @return WSDL of the API as {@link String}
* @throws APIMgtDAOException if error occurs while accessing the WSDL from the data layer
* @throws APIMgtWSDLException if error occurs while parsing/manipulating the WSDL
* @throws APINotFoundException If API cannot be found
* @throws LabelException If Label related error occurs
*/
String getAPIWSDL(String apiId, String labelName)
throws APIMgtDAOException, APIMgtWSDLException, APINotFoundException, LabelException;
/**
* Returns the WSDL archive info of a given API UUID and gateway label name
*
* @param apiId API Id
* @param labelName gateway label name
* @return WSDL archive information {@link WSDLArchiveInfo}
* @throws APIMgtDAOException if error occurs while accessing the WSDL from the data layer
* @throws APIMgtWSDLException if error occurs while parsing/manipulating the WSDL
* @throws APINotFoundException If API cannot be found
* @throws LabelException If Label related error occurs
*/
WSDLArchiveInfo getAPIWSDLArchive(String apiId, String labelName)
throws APIMgtDAOException, APIMgtWSDLException, APINotFoundException, LabelException;
/**
* Store user self signup
*
* @param user User information object
* @throws APIManagementException if error occurred while registering the new user
*/
void selfSignUp(User user) throws APIManagementException;
}
|
|
/*
* Copyright 2017 lizhaotailang
*
* 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.hut.zero.bean;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
/**
* Created by Lizhaotailang on 2016/9/17.
*/
public class DoubanMomentStory {
private int display_style;
private String short_url;
@SerializedName("abstract")
private String abs;
private int app_css;
private int like_count;
private ArrayList<DoubanMomentNews.Posts.thumbs> thumbs;
private String created_time;
private int id;
private boolean is_editor_choice;
private String original_url;
private String content;
private String share_pic_url;
private String type;
private boolean is_liked;
private ArrayList<DoubanMomentNews.Posts.thumbs> photos;
private String published_time;
private String url;
private String column;
private int comments_count;
private String title;
public int getDisplay_style() {
return display_style;
}
public void setDisplay_style(int display_style) {
this.display_style = display_style;
}
public String getShort_url() {
return short_url;
}
public void setShort_url(String short_url) {
this.short_url = short_url;
}
public String getAbs() {
return abs;
}
public void setAbs(String abs) {
this.abs = abs;
}
public int getApp_css() {
return app_css;
}
public void setApp_css(int app_css) {
this.app_css = app_css;
}
public int getLike_count() {
return like_count;
}
public void setLike_count(int like_count) {
this.like_count = like_count;
}
public ArrayList<DoubanMomentNews.Posts.thumbs> getThumbs() {
return thumbs;
}
public void setThumbs(ArrayList<DoubanMomentNews.Posts.thumbs> thumbs) {
this.thumbs = thumbs;
}
public String getCreated_time() {
return created_time;
}
public void setCreated_time(String created_time) {
this.created_time = created_time;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean is_editor_choice() {
return is_editor_choice;
}
public void setIs_editor_choice(boolean is_editor_choice) {
this.is_editor_choice = is_editor_choice;
}
public String getOriginal_url() {
return original_url;
}
public void setOriginal_url(String original_url) {
this.original_url = original_url;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getShare_pic_url() {
return share_pic_url;
}
public void setShare_pic_url(String share_pic_url) {
this.share_pic_url = share_pic_url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean is_liked() {
return is_liked;
}
public void setIs_liked(boolean is_liked) {
this.is_liked = is_liked;
}
public ArrayList<DoubanMomentNews.Posts.thumbs> getPhotos() {
return photos;
}
public void setPhotos(ArrayList<DoubanMomentNews.Posts.thumbs> photos) {
this.photos = photos;
}
public String getPublished_time() {
return published_time;
}
public void setPublished_time(String published_time) {
this.published_time = published_time;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
public int getComments_count() {
return comments_count;
}
public void setComments_count(int comments_count) {
this.comments_count = comments_count;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.sql.implementation;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.Resource;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.sql.fluent.JobVersionsClient;
import com.azure.resourcemanager.sql.models.JobVersionListResult;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in JobVersionsClient. */
public final class JobVersionsClientImpl implements JobVersionsClient {
private final ClientLogger logger = new ClientLogger(JobVersionsClientImpl.class);
/** The proxy service used to perform REST calls. */
private final JobVersionsService service;
/** The service client containing this operation class. */
private final SqlManagementClientImpl client;
/**
* Initializes an instance of JobVersionsClientImpl.
*
* @param client the instance of the service client containing this operation class.
*/
JobVersionsClientImpl(SqlManagementClientImpl client) {
this.service =
RestProxy.create(JobVersionsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for SqlManagementClientJobVersions to be used by the proxy service to
* perform REST calls.
*/
@Host("{$host}")
@ServiceInterface(name = "SqlManagementClientJ")
private interface JobVersionsService {
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers"
+ "/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/versions")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<JobVersionListResult>> listByJob(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("serverName") String serverName,
@PathParam("jobAgentName") String jobAgentName,
@PathParam("jobName") String jobName,
@PathParam("subscriptionId") String subscriptionId,
@QueryParam("api-version") String apiVersion,
Context context);
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Get(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers"
+ "/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/versions/{jobVersion}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<Resource>> get(
@HostParam("$host") String endpoint,
@PathParam("resourceGroupName") String resourceGroupName,
@PathParam("serverName") String serverName,
@PathParam("jobAgentName") String jobAgentName,
@PathParam("jobName") String jobName,
@PathParam("jobVersion") int jobVersion,
@PathParam("subscriptionId") String subscriptionId,
@QueryParam("api-version") String apiVersion,
Context context);
@Headers({"Accept: application/json", "Content-Type: application/json"})
@Get("{nextLink}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<JobVersionListResult>> listByJobNext(
@PathParam(value = "nextLink", encoded = true) String nextLink, Context context);
}
/**
* Gets all versions of a job.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all versions of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<Resource>> listByJobSinglePageAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (serverName == null) {
return Mono.error(new IllegalArgumentException("Parameter serverName is required and cannot be null."));
}
if (jobAgentName == null) {
return Mono.error(new IllegalArgumentException("Parameter jobAgentName is required and cannot be null."));
}
if (jobName == null) {
return Mono.error(new IllegalArgumentException("Parameter jobName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2017-03-01-preview";
return FluxUtil
.withContext(
context ->
service
.listByJob(
this.client.getEndpoint(),
resourceGroupName,
serverName,
jobAgentName,
jobName,
this.client.getSubscriptionId(),
apiVersion,
context))
.<PagedResponse<Resource>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Gets all versions of a job.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all versions of a job.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<Resource>> listByJobSinglePageAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (serverName == null) {
return Mono.error(new IllegalArgumentException("Parameter serverName is required and cannot be null."));
}
if (jobAgentName == null) {
return Mono.error(new IllegalArgumentException("Parameter jobAgentName is required and cannot be null."));
}
if (jobName == null) {
return Mono.error(new IllegalArgumentException("Parameter jobName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2017-03-01-preview";
context = this.client.mergeContext(context);
return service
.listByJob(
this.client.getEndpoint(),
resourceGroupName,
serverName,
jobAgentName,
jobName,
this.client.getSubscriptionId(),
apiVersion,
context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Gets all versions of a job.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all versions of a job.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<Resource> listByJobAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName) {
return new PagedFlux<>(
() -> listByJobSinglePageAsync(resourceGroupName, serverName, jobAgentName, jobName),
nextLink -> listByJobNextSinglePageAsync(nextLink));
}
/**
* Gets all versions of a job.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all versions of a job.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<Resource> listByJobAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, Context context) {
return new PagedFlux<>(
() -> listByJobSinglePageAsync(resourceGroupName, serverName, jobAgentName, jobName, context),
nextLink -> listByJobNextSinglePageAsync(nextLink, context));
}
/**
* Gets all versions of a job.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all versions of a job.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<Resource> listByJob(
String resourceGroupName, String serverName, String jobAgentName, String jobName) {
return new PagedIterable<>(listByJobAsync(resourceGroupName, serverName, jobAgentName, jobName));
}
/**
* Gets all versions of a job.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job to get.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all versions of a job.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<Resource> listByJob(
String resourceGroupName, String serverName, String jobAgentName, String jobName, Context context) {
return new PagedIterable<>(listByJobAsync(resourceGroupName, serverName, jobAgentName, jobName, context));
}
/**
* Gets a job version.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobVersion The version of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a job version.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Resource>> getWithResponseAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, int jobVersion) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (serverName == null) {
return Mono.error(new IllegalArgumentException("Parameter serverName is required and cannot be null."));
}
if (jobAgentName == null) {
return Mono.error(new IllegalArgumentException("Parameter jobAgentName is required and cannot be null."));
}
if (jobName == null) {
return Mono.error(new IllegalArgumentException("Parameter jobName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2017-03-01-preview";
return FluxUtil
.withContext(
context ->
service
.get(
this.client.getEndpoint(),
resourceGroupName,
serverName,
jobAgentName,
jobName,
jobVersion,
this.client.getSubscriptionId(),
apiVersion,
context))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Gets a job version.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobVersion The version of the job to get.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a job version.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<Response<Resource>> getWithResponseAsync(
String resourceGroupName,
String serverName,
String jobAgentName,
String jobName,
int jobVersion,
Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (resourceGroupName == null) {
return Mono
.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));
}
if (serverName == null) {
return Mono.error(new IllegalArgumentException("Parameter serverName is required and cannot be null."));
}
if (jobAgentName == null) {
return Mono.error(new IllegalArgumentException("Parameter jobAgentName is required and cannot be null."));
}
if (jobName == null) {
return Mono.error(new IllegalArgumentException("Parameter jobName is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2017-03-01-preview";
context = this.client.mergeContext(context);
return service
.get(
this.client.getEndpoint(),
resourceGroupName,
serverName,
jobAgentName,
jobName,
jobVersion,
this.client.getSubscriptionId(),
apiVersion,
context);
}
/**
* Gets a job version.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobVersion The version of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a job version.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Resource> getAsync(
String resourceGroupName, String serverName, String jobAgentName, String jobName, int jobVersion) {
return getWithResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, jobVersion)
.flatMap(
(Response<Resource> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
}
/**
* Gets a job version.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobVersion The version of the job to get.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a job version.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Resource get(
String resourceGroupName, String serverName, String jobAgentName, String jobName, int jobVersion) {
return getAsync(resourceGroupName, serverName, jobAgentName, jobName, jobVersion).block();
}
/**
* Gets a job version.
*
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value
* from the Azure Resource Manager API or the portal.
* @param serverName The name of the server.
* @param jobAgentName The name of the job agent.
* @param jobName The name of the job.
* @param jobVersion The version of the job to get.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a job version.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Resource> getWithResponse(
String resourceGroupName,
String serverName,
String jobAgentName,
String jobName,
int jobVersion,
Context context) {
return getWithResponseAsync(resourceGroupName, serverName, jobAgentName, jobName, jobVersion, context).block();
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job versions.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<Resource>> listByJobNextSinglePageAsync(String nextLink) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
return FluxUtil
.withContext(context -> service.listByJobNext(nextLink, context))
.<PagedResponse<Resource>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return a list of job versions.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<Resource>> listByJobNextSinglePageAsync(String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
context = this.client.mergeContext(context);
return service
.listByJobNext(nextLink, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
}
|
|
package mil.nga.geopackage.manager;
import java.io.File;
import java.sql.SQLException;
import java.util.List;
import mil.nga.geopackage.GeoPackage;
import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.core.contents.Contents;
import mil.nga.geopackage.db.GeoPackageConnection;
import mil.nga.geopackage.db.GeoPackageTableCreator;
import mil.nga.geopackage.factory.GeoPackageCoreImpl;
import mil.nga.geopackage.features.columns.GeometryColumns;
import mil.nga.geopackage.features.columns.GeometryColumnsDao;
import mil.nga.geopackage.features.user.FeatureConnection;
import mil.nga.geopackage.features.user.FeatureDao;
import mil.nga.geopackage.features.user.FeatureTable;
import mil.nga.geopackage.features.user.FeatureTableReader;
import mil.nga.geopackage.tiles.matrix.TileMatrix;
import mil.nga.geopackage.tiles.matrix.TileMatrixDao;
import mil.nga.geopackage.tiles.matrix.TileMatrixKey;
import mil.nga.geopackage.tiles.matrixset.TileMatrixSet;
import mil.nga.geopackage.tiles.matrixset.TileMatrixSetDao;
import mil.nga.geopackage.tiles.user.TileConnection;
import mil.nga.geopackage.tiles.user.TileDao;
import mil.nga.geopackage.tiles.user.TileTable;
import mil.nga.geopackage.tiles.user.TileTableReader;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
/**
* GeoPackage implementation
*
* @author osbornb
*/
class GeoPackageImpl extends GeoPackageCoreImpl implements GeoPackage {
/**
* Database connection
*/
private final GeoPackageConnection database;
/**
* Constructor
*
* @param file
* @param database
* @param tableCreator
*/
GeoPackageImpl(File file, GeoPackageConnection database,
GeoPackageTableCreator tableCreator) {
super(file.getName(), file.getAbsolutePath(), database, tableCreator,
true);
this.database = database;
}
/**
* {@inheritDoc}
*/
@Override
public FeatureDao getFeatureDao(GeometryColumns geometryColumns) {
if (geometryColumns == null) {
throw new GeoPackageException("Non null "
+ GeometryColumns.class.getSimpleName()
+ " is required to create "
+ FeatureDao.class.getSimpleName());
}
// Read the existing table and create the dao
FeatureTableReader tableReader = new FeatureTableReader(geometryColumns);
FeatureConnection userDb = new FeatureConnection(database);
final FeatureTable featureTable = tableReader.readTable(userDb);
userDb.setTable(featureTable);
FeatureDao dao = new FeatureDao(getName(), database, userDb,
geometryColumns, featureTable);
// TODO
// GeoPackages created with SQLite version 4.2.0+ with GeoPackage
// support are not supported in sqlite-jdbc (3.8.6 version from
// October8, 2014 uses SQLite version 3.8.6)
dropSQLiteTriggers(geometryColumns);
return dao;
}
/**
* {@inheritDoc}
*/
@Override
public FeatureDao getFeatureDao(Contents contents) {
if (contents == null) {
throw new GeoPackageException("Non null "
+ Contents.class.getSimpleName()
+ " is required to create "
+ FeatureDao.class.getSimpleName());
}
GeometryColumns geometryColumns = null;
try {
geometryColumns = getGeometryColumnsDao().queryForTableName(
contents.getTableName());
} catch (SQLException e) {
throw new GeoPackageException("No "
+ GeometryColumns.class.getSimpleName()
+ " could be retrieved for "
+ Contents.class.getSimpleName() + " " + contents.getId());
}
if (geometryColumns == null) {
throw new GeoPackageException("No "
+ GeometryColumns.class.getSimpleName() + " exists for "
+ Contents.class.getSimpleName() + " " + contents.getId());
}
return getFeatureDao(geometryColumns);
}
/**
* {@inheritDoc}
*/
@Override
public FeatureDao getFeatureDao(String tableName) {
GeometryColumnsDao dao = getGeometryColumnsDao();
List<GeometryColumns> geometryColumnsList;
try {
geometryColumnsList = dao.queryForEq(
GeometryColumns.COLUMN_TABLE_NAME, tableName);
} catch (SQLException e) {
throw new GeoPackageException("Failed to retrieve "
+ FeatureDao.class.getSimpleName() + " for table name: "
+ tableName + ". Exception retrieving "
+ GeometryColumns.class.getSimpleName() + ".", e);
}
if (geometryColumnsList.isEmpty()) {
throw new GeoPackageException(
"No Feature Table exists for table name: " + tableName);
} else if (geometryColumnsList.size() > 1) {
// This shouldn't happen with the table name unique constraint on
// geometry columns
throw new GeoPackageException("Unexpected state. More than one "
+ GeometryColumns.class.getSimpleName()
+ " matched for table name: " + tableName + ", count: "
+ geometryColumnsList.size());
}
return getFeatureDao(geometryColumnsList.get(0));
}
/**
* {@inheritDoc}
*/
@Override
public TileDao getTileDao(TileMatrixSet tileMatrixSet) {
if (tileMatrixSet == null) {
throw new GeoPackageException("Non null "
+ TileMatrixSet.class.getSimpleName()
+ " is required to create " + TileDao.class.getSimpleName());
}
// Get the Tile Matrix collection, order by zoom level ascending & pixel
// size descending per requirement 51
List<TileMatrix> tileMatrices;
try {
TileMatrixDao tileMatrixDao = getTileMatrixDao();
QueryBuilder<TileMatrix, TileMatrixKey> qb = tileMatrixDao
.queryBuilder();
qb.where().eq(TileMatrix.COLUMN_TABLE_NAME,
tileMatrixSet.getTableName());
qb.orderBy(TileMatrix.COLUMN_ZOOM_LEVEL, true);
qb.orderBy(TileMatrix.COLUMN_PIXEL_X_SIZE, false);
qb.orderBy(TileMatrix.COLUMN_PIXEL_Y_SIZE, false);
PreparedQuery<TileMatrix> query = qb.prepare();
tileMatrices = tileMatrixDao.query(query);
} catch (SQLException e) {
throw new GeoPackageException("Failed to retrieve "
+ TileDao.class.getSimpleName() + " for table name: "
+ tileMatrixSet.getTableName() + ". Exception retrieving "
+ TileMatrix.class.getSimpleName() + " collection.", e);
}
// Read the existing table and create the dao
TileTableReader tableReader = new TileTableReader(
tileMatrixSet.getTableName());
TileConnection userDb = new TileConnection(database);
final TileTable tileTable = tableReader.readTable(userDb);
userDb.setTable(tileTable);
TileDao dao = new TileDao(getName(), database, userDb, tileMatrixSet,
tileMatrices, tileTable);
return dao;
}
/**
* {@inheritDoc}
*/
@Override
public TileDao getTileDao(Contents contents) {
if (contents == null) {
throw new GeoPackageException("Non null "
+ Contents.class.getSimpleName()
+ " is required to create " + TileDao.class.getSimpleName());
}
TileMatrixSet tileMatrixSet = null;
try {
tileMatrixSet = getTileMatrixSetDao().queryForId(
contents.getTableName());
} catch (SQLException e) {
throw new GeoPackageException("No "
+ TileMatrixSet.class.getSimpleName()
+ " could be retrieved for "
+ Contents.class.getSimpleName() + " " + contents.getId());
}
if (tileMatrixSet == null) {
throw new GeoPackageException("No "
+ TileMatrixSet.class.getSimpleName() + " exists for "
+ Contents.class.getSimpleName() + " " + contents.getId());
}
return getTileDao(tileMatrixSet);
}
/**
* {@inheritDoc}
*/
@Override
public TileDao getTileDao(String tableName) {
TileMatrixSetDao dao = getTileMatrixSetDao();
List<TileMatrixSet> tileMatrixSetList;
try {
tileMatrixSetList = dao.queryForEq(TileMatrixSet.COLUMN_TABLE_NAME,
tableName);
} catch (SQLException e) {
throw new GeoPackageException("Failed to retrieve "
+ TileDao.class.getSimpleName() + " for table name: "
+ tableName + ". Exception retrieving "
+ TileMatrixSet.class.getSimpleName() + ".", e);
}
if (tileMatrixSetList.isEmpty()) {
throw new GeoPackageException(
"No Tile Table exists for table name: " + tableName + ", Tile Tables: " + getTileTables());
} else if (tileMatrixSetList.size() > 1) {
// This shouldn't happen with the table name primary key on tile
// matrix set table
throw new GeoPackageException("Unexpected state. More than one "
+ TileMatrixSet.class.getSimpleName()
+ " matched for table name: " + tableName + ", count: "
+ tileMatrixSetList.size());
}
return getTileDao(tileMatrixSetList.get(0));
}
}
|
|
/*
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.swing;
import java.io.File;
import java.net.MalformedURLException;
import java.lang.ref.WeakReference;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.w3c.dom.Element;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.UpdateManager;
import org.apache.batik.dom.svg.SVGContext;
import org.apache.batik.dom.svg.SVGOMDocument;
import org.apache.batik.dom.svg.SVGOMElement;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.test.DefaultTestReport;
import org.apache.batik.test.MemoryLeakTest;
import org.apache.batik.test.TestReport;
/**
* One line Class Desc
*
* Complete Class Desc
*
* @author <a href="mailto:[email protected]">l449433</a>
* @version $Id$
*/
public class JSVGMemoryLeakTest extends MemoryLeakTest
implements JSVGCanvasHandler.Delegate {
public JSVGMemoryLeakTest() {
}
public String getName() { return "JSVGMemoryLeakTest."+getId(); }
TestReport failReport = null;
boolean done;
JSVGCanvasHandler handler;
JFrame theFrame;
/**
* A WeakReference to the JSVGCanvas.
*/
WeakReference theCanvas;
protected void setTheCanvas(JSVGCanvas c) {
theCanvas = new WeakReference(c);
}
protected JSVGCanvas getTheCanvas() {
return (JSVGCanvas) theCanvas.get();
}
public static String fmt(String key, Object []args) {
return TestMessages.formatMessage(key, args);
}
public JSVGCanvasHandler createHandler() {
return new JSVGCanvasHandler(this, this);
}
public TestReport doSomething() throws Exception {
handler = createHandler();
registerObjectDesc(handler, "Handler");
done = false;
handler.runCanvas(getId());
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
// System.out.println("In Invoke");
theFrame.remove(getTheCanvas());
getTheCanvas().dispose();
theFrame.dispose();
theFrame=null;
theCanvas=null;
}
});
try { Thread.sleep(100); } catch (InterruptedException ie) { }
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
// Create a new Frame to take focus for Swing so old one
// can be GC'd.
theFrame = new JFrame("FocusFrame");
// registerObjectDesc(jframe, "FocusFrame");
theFrame.setSize(new java.awt.Dimension(40, 50));
theFrame.setVisible(true);
}});
try { Thread.sleep(100); } catch (InterruptedException ie) { }
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
theFrame.setVisible(false);
theFrame.dispose();
}});
handler = null;
if (failReport != null) return failReport;
DefaultTestReport report = new DefaultTestReport(this);
report.setPassed(true);
return report;
}
public void scriptDone() {
synchronized (this) {
done = true;
handler.scriptDone();
}
}
public void registerElement(Element e, String desc) {
registerObjectDesc(e, desc);
UpdateManager um = getTheCanvas().getUpdateManager();
BridgeContext bc = um.getBridgeContext();
GraphicsNode gn = bc.getGraphicsNode(e);
if (gn != null)
registerObjectDesc(gn, desc+"_GN");
if (e instanceof SVGOMElement) {
SVGOMElement svge = (SVGOMElement)e;
SVGContext svgctx = svge.getSVGContext();
if (svgctx != null) {
registerObjectDesc(svgctx, desc+"_CTX");
}
}
}
public void registerResourceContext(String uriSubstring, String desc) {
UpdateManager um = getTheCanvas().getUpdateManager();
BridgeContext bc = um.getBridgeContext();
BridgeContext[] ctxs = bc.getChildContexts();
for (int i = 0; i < ctxs.length; i++) {
bc = ctxs[i];
if (bc == null) {
continue;
}
String url = ((SVGOMDocument) bc.getDocument()).getURL();
if (url.indexOf(uriSubstring) != -1) {
registerObjectDesc(ctxs[i], desc);
}
}
}
/* JSVGCanvasHandler.Delegate Interface */
public boolean canvasInit(JSVGCanvas canvas) {
// System.err.println("In Init");
setTheCanvas(canvas);
theFrame = handler.getFrame();
File f = new File(getId());
try {
canvas.setURI(f.toURL().toString());
} catch (MalformedURLException mue) {
}
registerObjectDesc(canvas, "JSVGCanvas");
registerObjectDesc(handler.getFrame(), "JFrame");
return true;
}
public void canvasLoaded(JSVGCanvas canvas) {
// System.err.println("Loaded");
registerObjectDesc(canvas.getSVGDocument(), "SVGDoc");
}
public void canvasRendered(JSVGCanvas canvas) {
// System.err.println("Rendered");
registerObjectDesc(canvas.getGraphicsNode(), "GVT");
UpdateManager um = canvas.getUpdateManager();
if (um == null) {
return;
}
BridgeContext bc = um.getBridgeContext();
registerObjectDesc(um, "updateManager");
registerObjectDesc(bc, "bridgeContext");
BridgeContext[] subCtxs = bc.getChildContexts();
for (int i = 0; i < subCtxs.length; i++) {
if (subCtxs[i] != null) {
SVGOMDocument doc = (SVGOMDocument) subCtxs[i].getDocument();
registerObjectDesc(subCtxs[i], "BridgeContext_" + doc.getURL());
}
}
}
public boolean canvasUpdated(JSVGCanvas canvas) {
// System.err.println("Updated");
synchronized (this) {
return done;
}
}
public void canvasDone(final JSVGCanvas canvas) {
// System.err.println("Done");
}
public void failure(TestReport report) {
synchronized (this) {
done = true;
failReport = report;
}
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.cluster.failover;
import java.util.ArrayList;
import java.util.List;
import org.apache.activemq.artemis.api.core.ActiveMQDuplicateIdException;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.ActiveMQTransactionOutcomeUnknownException;
import org.apache.activemq.artemis.api.core.ActiveMQTransactionRolledBackException;
import org.apache.activemq.artemis.api.core.ActiveMQUnBlockedException;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger;
import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryInternal;
import org.apache.activemq.artemis.core.client.impl.ClientSessionInternal;
import org.apache.activemq.artemis.core.client.impl.DelegatingSession;
import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
import org.apache.activemq.artemis.tests.util.CountDownSessionFailureListener;
import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils;
import org.junit.Assert;
import org.junit.Test;
/**
* A MultiThreadFailoverTest
* <br>
* Test Failover where failure is prompted by another thread
*/
public class AsynchronousFailoverTest extends FailoverTestBase
{
private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER;
private volatile CountDownSessionFailureListener listener;
private volatile ClientSessionFactoryInternal sf;
private final Object lockFail = new Object();
@Test
public void testNonTransactional() throws Throwable
{
runTest(new TestRunner()
{
public void run()
{
try
{
doTestNonTransactional(this);
}
catch (Throwable e)
{
AsynchronousFailoverTest.log.error("Test failed", e);
addException(e);
}
}
});
}
@Test
public void testTransactional() throws Throwable
{
runTest(new TestRunner()
{
volatile boolean running = false;
public void run()
{
try
{
assertFalse(running);
running = true;
try
{
doTestTransactional(this);
}
finally
{
running = false;
}
}
catch (Throwable e)
{
AsynchronousFailoverTest.log.error("Test failed", e);
addException(e);
}
}
});
}
abstract class TestRunner implements Runnable
{
volatile boolean failed;
ArrayList<Throwable> errors = new ArrayList<Throwable>();
boolean isFailed()
{
return failed;
}
void setFailed()
{
failed = true;
}
void reset()
{
failed = false;
}
synchronized void addException(Throwable e)
{
errors.add(e);
}
void checkForExceptions() throws Throwable
{
if (errors.size() > 0)
{
log.warn("Exceptions on test:");
for (Throwable e : errors)
{
log.warn(e.getMessage(), e);
}
// throwing the first error that happened on the Runnable
throw errors.get(0);
}
}
}
private void runTest(final TestRunner runnable) throws Throwable
{
final int numIts = 1;
DelegatingSession.debug = true;
try
{
for (int i = 0; i < numIts; i++)
{
AsynchronousFailoverTest.log.info("Iteration " + i);
ServerLocator locator = getServerLocator()
.setBlockOnNonDurableSend(true)
.setBlockOnDurableSend(true)
.setReconnectAttempts(-1)
.setConfirmationWindowSize(10 * 1024 * 1024);
sf = createSessionFactoryAndWaitForTopology(locator, 2);
try
{
ClientSession createSession = sf.createSession(true, true);
createSession.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, true);
RemotingConnection conn = ((ClientSessionInternal) createSession).getConnection();
Thread t = new Thread(runnable);
t.setName("MainTEST");
t.start();
long randomDelay = (long) (2000 * Math.random());
AsynchronousFailoverTest.log.info("Sleeping " + randomDelay);
Thread.sleep(randomDelay);
AsynchronousFailoverTest.log.info("Failing asynchronously");
// Simulate failure on connection
synchronized (lockFail)
{
if (log.isDebugEnabled())
{
log.debug("#test crashing test");
}
crash(createSession);
}
/*if (listener != null)
{
boolean ok = listener.latch.await(10000, TimeUnit.MILLISECONDS);
Assert.assertTrue(ok);
}*/
runnable.setFailed();
AsynchronousFailoverTest.log.info("Fail complete");
t.join();
runnable.checkForExceptions();
createSession.close();
if (sf.numSessions() != 0)
{
DelegatingSession.dumpSessionCreationStacks();
}
Assert.assertEquals(0, sf.numSessions());
locator.close();
}
finally
{
locator.close();
Assert.assertEquals(0, sf.numConnections());
}
if (i != numIts - 1)
{
tearDown();
runnable.checkForExceptions();
runnable.reset();
setUp();
}
}
}
finally
{
DelegatingSession.debug = false;
}
}
protected void addPayload(ClientMessage msg)
{
}
private void doTestNonTransactional(final TestRunner runner) throws Exception
{
while (!runner.isFailed())
{
AsynchronousFailoverTest.log.info("looping");
ClientSession session = sf.createSession(true, true, 0);
listener = new CountDownSessionFailureListener(session);
session.addFailureListener(listener);
ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);
final int numMessages = 1000;
for (int i = 0; i < numMessages; i++)
{
boolean retry = false;
do
{
try
{
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("message" + i);
message.putIntProperty("counter", i);
addPayload(message);
producer.send(message);
retry = false;
}
catch (ActiveMQUnBlockedException ube)
{
AsynchronousFailoverTest.log.info("exception when sending message with counter " + i);
ube.printStackTrace();
retry = true;
}
catch (ActiveMQException e)
{
fail("Invalid Exception type:" + e.getType());
}
}
while (retry);
}
// create the consumer with retry if failover occurs during createConsumer call
ClientConsumer consumer = null;
boolean retry = false;
do
{
try
{
consumer = session.createConsumer(FailoverTestBase.ADDRESS);
retry = false;
}
catch (ActiveMQUnBlockedException ube)
{
AsynchronousFailoverTest.log.info("exception when creating consumer");
retry = true;
}
catch (ActiveMQException e)
{
fail("Invalid Exception type:" + e.getType());
}
}
while (retry);
session.start();
List<Integer> counts = new ArrayList<Integer>(1000);
int lastCount = -1;
boolean counterGap = false;
while (true)
{
ClientMessage message = consumer.receive(500);
if (message == null)
{
break;
}
// messages must remain ordered but there could be a "jump" if messages
// are missing or duplicated
int count = message.getIntProperty("counter");
counts.add(count);
if (count != lastCount + 1)
{
if (counterGap)
{
Assert.fail("got a another counter gap at " + count + ": " + counts);
}
else
{
if (lastCount != -1)
{
AsynchronousFailoverTest.log.info("got first counter gap at " + count);
counterGap = true;
}
}
}
lastCount = count;
message.acknowledge();
}
session.close();
this.listener = null;
}
}
private void doTestTransactional(final TestRunner runner) throws Throwable
{
// For duplication detection
int executionId = 0;
while (!runner.isFailed())
{
ClientSession session = null;
executionId++;
log.info("#test doTestTransactional starting now. Execution " + executionId);
try
{
boolean retry = false;
final int numMessages = 1000;
session = sf.createSession(false, false);
listener = new CountDownSessionFailureListener(session);
session.addFailureListener(listener);
do
{
try
{
ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);
for (int i = 0; i < numMessages; i++)
{
ClientMessage message = session.createMessage(true);
message.getBodyBuffer().writeString("message" + i);
message.putIntProperty("counter", i);
message.putStringProperty(Message.HDR_DUPLICATE_DETECTION_ID, new SimpleString("id:" + i +
",exec:" +
executionId));
addPayload(message);
if (log.isDebugEnabled())
{
log.debug("Sending message " + message);
}
producer.send(message);
}
log.debug("Sending commit");
session.commit();
retry = false;
}
catch (ActiveMQDuplicateIdException die)
{
logAndSystemOut("#test duplicate id rejected on sending");
break;
}
catch (ActiveMQTransactionRolledBackException trbe)
{
log.info("#test transaction rollback retrying on sending");
// OK
retry = true;
}
catch (ActiveMQUnBlockedException ube)
{
log.info("#test transaction rollback retrying on sending");
// OK
retry = true;
}
catch (ActiveMQTransactionOutcomeUnknownException toue)
{
log.info("#test transaction rollback retrying on sending");
// OK
retry = true;
}
catch (ActiveMQException e)
{
log.info("#test Exception " + e, e);
throw e;
}
}
while (retry);
logAndSystemOut("#test Finished sending, starting consumption now");
boolean blocked = false;
retry = false;
ClientConsumer consumer = null;
do
{
ArrayList<Integer> msgs = new ArrayList<Integer>();
try
{
if (consumer == null)
{
consumer = session.createConsumer(FailoverTestBase.ADDRESS);
session.start();
}
for (int i = 0; i < numMessages; i++)
{
if (log.isDebugEnabled())
{
log.debug("Consumer receiving message " + i);
}
ClientMessage message = consumer.receive(10000);
if (message == null)
{
break;
}
if (log.isDebugEnabled())
{
log.debug("Received message " + message);
}
int count = message.getIntProperty("counter");
if (count != i)
{
log.warn("count was received out of order, " + count + "!=" + i);
}
msgs.add(count);
message.acknowledge();
}
log.info("#test commit");
try
{
session.commit();
}
catch (ActiveMQTransactionRolledBackException trbe)
{
//we know the tx has been rolled back so we just consume again
retry = true;
continue;
}
catch (ActiveMQException e)
{
// This could eventually happen
// We will get rid of this when we implement 2 phase commit on failover
log.warn("exception during commit, it will be ignored for now" + e.getMessage(), e);
}
try
{
if (blocked)
{
assertTrue("msgs.size is expected to be 0 or " + numMessages + " but it was " + msgs.size(),
msgs.size() == 0 || msgs.size() == numMessages);
}
else
{
assertTrue("msgs.size is expected to be " + numMessages + " but it was " + msgs.size(),
msgs.size() == numMessages);
}
}
catch (Throwable e)
{
log.info(threadDump("Thread dump, messagesReceived = " + msgs.size()));
logAndSystemOut(e.getMessage() + " messages received");
for (Integer msg : msgs)
{
logAndSystemOut(msg.toString());
}
throw e;
}
int i = 0;
for (Integer msg : msgs)
{
assertEquals(i++, (int) msg);
}
retry = false;
blocked = false;
}
catch (ActiveMQTransactionRolledBackException trbe)
{
logAndSystemOut("Transaction rolled back with " + msgs.size(), trbe);
// TODO: https://jira.jboss.org/jira/browse/HORNETQ-369
// ATM RolledBack exception is being called with the transaction is committed.
// the test will fail if you remove this next line
blocked = true;
retry = true;
}
catch (ActiveMQTransactionOutcomeUnknownException tou)
{
logAndSystemOut("Transaction rolled back with " + msgs.size(), tou);
// TODO: https://jira.jboss.org/jira/browse/HORNETQ-369
// ATM RolledBack exception is being called with the transaction is committed.
// the test will fail if you remove this next line
blocked = true;
retry = true;
}
catch (ActiveMQUnBlockedException ube)
{
logAndSystemOut("Unblocked with " + msgs.size(), ube);
// TODO: https://jira.jboss.org/jira/browse/HORNETQ-369
// This part of the test is never being called.
blocked = true;
retry = true;
}
catch (ActiveMQException e)
{
logAndSystemOut(e.getMessage(), e);
throw e;
}
}
while (retry);
}
finally
{
if (session != null)
{
session.close();
}
}
listener = null;
}
}
@Override
protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live)
{
return TransportConfigurationUtils.getInVMAcceptor(live);
}
@Override
protected TransportConfiguration getConnectorTransportConfiguration(final boolean live)
{
return TransportConfigurationUtils.getInVMConnector(live);
}
}
|
|
package gov.va.jmeadows;
import gov.va.cpe.idn.PatientIds;
import gov.va.cpe.vpr.AllergyComment;
import gov.va.cpe.vpr.AllergyProduct;
import gov.va.cpe.vpr.JdsCode;
import gov.va.cpe.vpr.PidUtils;
import gov.va.cpe.vpr.UidUtils;
import gov.va.cpe.vpr.pom.JSONViews.JDBView;
import gov.va.cpe.vpr.sync.vista.VistaDataChunk;
import gov.va.med.jmeadows.webservice.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import static gov.va.jmeadows.JMeadowsClientUtils.QueryBeanParams.PATIENT;
import static gov.va.jmeadows.JMeadowsClientUtils.QueryBeanParams.USER;
import static gov.va.jmeadows.JMeadowsClientUtils.*;
/**
* JMeadows Allergy Retriever Service
*/
@Service
public class JMeadowsAllergyService implements IJMeadowsAllergyService {
public static final String DOMAIN_ALLERGY = "allergy";
private static final Logger LOG = LoggerFactory.getLogger(JMeadowsAllergyService.class);
private JMeadowsData jMeadowsClient;
/**
* Constructs a JMeadowsAllergyService instance.
*/
@Autowired
public JMeadowsAllergyService(JMeadowsConfiguration jMeadowsConfiguration) {
jMeadowsClient = JMeadowsClientFactory.getInstance(jMeadowsConfiguration);
}
/**
* Sets JMeadowsClient
*
* @param jMeadowsClient JMeadows client instance.
*/
public void setJMeadowsClient(JMeadowsData jMeadowsClient) {
this.jMeadowsClient = jMeadowsClient;
}
/**
* This routine will calculate the total number of allergies that are in the result set. It does this by
* counting all the allergies that are part of the DoD domain. We ignore all that are from any VistA site.
*
* @param oaAllergy The list of allergies returned.
* @return The number of allergies that are from a DoD site.
*/
private int calculateNumAllergies(List<Allergy> oaAllergy) {
int iNumAllergies = 0;
if ((oaAllergy != null) && (oaAllergy.size() > 0)) {
for (Allergy oAllergy : oaAllergy) {
iNumAllergies++;
}
}
return iNumAllergies;
}
/**
* Retrieve DoD allergy data and format it into a VistaChunk to be included into the set of data returned to the system.
*
* @param query JMeadows query bean.
* @param patientIds Patient identifier bean.
* @return The VistaDataChunk list that contains the allergy data.
* @throws JMeadowsException_Exception If a serious error occurs.
* @throws IllegalArgumentException if required parameters are missing or invalid.
*/
@Override
public List<VistaDataChunk> fetchDodPatientAllergies(JMeadowsQuery query, PatientIds patientIds) throws JMeadowsException_Exception {
LOG.debug("JMeadowsAllergyService.fetchDodPatientAllergies - Entering method...");
validateParams(query, patientIds, USER, PATIENT);
List<VistaDataChunk> oaAllergyChunk = new ArrayList<VistaDataChunk>();
List<Allergy> oaAllergy = jMeadowsClient.getPatientAllergies(query);
LOG.debug("JMeadowsAllergyService.fetchDodPatientAllergies: " +
((oaAllergy == null) ? "NO" : "" + oaAllergy.size()) +
" results retrieved from JMeadows.");
if ((oaAllergy != null) && (oaAllergy.size() > 0)) {
//remove DoD adaptor status report
oaAllergy = (List<Allergy>) filterOnSourceProtocol(oaAllergy, SOURCE_PROTOCOL_DODADAPTER);
int iNumAllergies = calculateNumAllergies(oaAllergy);
int iCurAllergyIdx = 1; // One based index
for (Allergy oAllergy : oaAllergy) {
LOG.debug("JMeadowsAllergyService.fetchDodPatientAllergies: Found DoD Allergy - Processing it... idx: " + iCurAllergyIdx);
VistaDataChunk oAllergyChunk = transformAllergyChunk(oAllergy, patientIds, iNumAllergies, iCurAllergyIdx);
if (oAllergyChunk != null) {
oaAllergyChunk.add(oAllergyChunk);
iCurAllergyIdx++;
}
}
}
return oaAllergyChunk;
}
/**
* Create an instance of a VistaDataChunk that represents this allergy.
*
* @param oAllergy The allergy that was returned from JMeadows
* @param oPatientIds Patient identifiers.
* @param iNumAllergies The number of allergies
* @param iCurAllergyIdx The index of this allergy in the list.
* @return The VistaDataChunk for this allergy.
*/
private VistaDataChunk transformAllergyChunk(Allergy oAllergy, PatientIds oPatientIds, int iNumAllergies, int iCurAllergyIdx) {
LOG.debug("JMeadowsAllergyService.transformAllergyChunk - Entering method...");
VistaDataChunk oAllergyChunk = new VistaDataChunk();
oAllergyChunk.setBatch(false);
oAllergyChunk.setDomain(DOMAIN_ALLERGY);
oAllergyChunk.setItemCount(iNumAllergies);
oAllergyChunk.setItemIndex(iCurAllergyIdx);
// oAllergyChunk.setJson(null);
String sSystemId = "";
String sLocalPatientId = "";
if (StringUtils.hasText(oPatientIds.getUid())) {
sSystemId = UidUtils.getSystemIdFromPatientUid(oPatientIds.getUid());
sLocalPatientId = UidUtils.getLocalPatientIdFromPatientUid(oPatientIds.getUid());
oAllergyChunk.setLocalPatientId(sLocalPatientId);
oAllergyChunk.setSystemId(sSystemId);
HashMap<String, String> oParams = new HashMap<String, String>();
oParams.put("vistaId", sSystemId);
oParams.put("patientDfn", sLocalPatientId);
oAllergyChunk.setParams(oParams);
}
oAllergyChunk.setPatientIcn(oPatientIds.getIcn());
oAllergyChunk.setPatientId(PidUtils.getPid("DOD", oPatientIds.getEdipi()));
oAllergyChunk.setRpcUri("vrpcb://9E7A/HMP SYNCHRONIZATION CONTEXT/HMPDJFS API");
oAllergyChunk.setType(VistaDataChunk.NEW_OR_UPDATE);
oAllergyChunk.setContent(transformAllergyJson(oAllergy, "DOD", oPatientIds.getEdipi()));
return oAllergyChunk;
}
/**
* This method will transform the allergy from the DoD JMeadows format to the VPR format and return it as a
* JSON string.
*
* @param oAllergy The DoD JMeadows format of the data.
* @param sSystemId The site system ID
* @param sEdipi The patient EDIPI
* @return The JSON for this allergy data in VPR format.
*/
private String transformAllergyJson(Allergy oAllergy, String sSystemId, String sEdipi) {
LOG.debug("JMeadowsAllergyService.transformAllergyJson - Entering method...");
gov.va.cpe.vpr.Allergy oVprAllergy = new gov.va.cpe.vpr.Allergy();
List<AllergyProduct> oaProduct = new ArrayList<AllergyProduct>();
AllergyProduct oProduct = new AllergyProduct();
oaProduct.add(oProduct);
if ((oAllergy.getAllergyName() != null) && (oAllergy.getAllergyName().length() > 0)) {
oProduct.setData("name", oAllergy.getAllergyName());
}
oVprAllergy.setData("products", oaProduct);
// Extract the codes
//--------------------
if ((oAllergy.getCodes() != null) &&
(oAllergy.getCodes().size() > 0)) {
List<JdsCode> oaJdsCode = new ArrayList<JdsCode>();
for (Code oCode : oAllergy.getCodes()) {
boolean bHasData = false;
JdsCode oJdsCode = new JdsCode();
if ((oCode.getCode() != null) && (oCode.getCode().length() > 0)) {
oJdsCode.setCode(oCode.getCode());
bHasData = true;
}
if ((oCode.getSystem() != null) && (oCode.getSystem().length() > 0)) {
JLVTerminologySystem termSystem = JLVTerminologySystem.getSystemByName(oCode.getSystem());
//pass OID urn if one exists
if (termSystem != null) {
oJdsCode.setSystem(termSystem.getUrn());
}
//default to code system display name
else oJdsCode.setSystem(oCode.getSystem());
bHasData = true;
}
if ((oCode.getDisplay() != null) && (oCode.getDisplay().length() > 0)) {
oJdsCode.setDisplay(oCode.getDisplay());
bHasData = true;
}
if (bHasData) {
oaJdsCode.add(oJdsCode);
}
}
if (CollectionUtils.isNotEmpty(oaJdsCode)) {
oVprAllergy.setData("codes", oaJdsCode);
}
}
if ((oAllergy.getComment() != null) && (oAllergy.getComment().length() > 0)) {
AllergyComment allergyComment = new AllergyComment();
allergyComment.setData("comment", oAllergy.getComment());
List<AllergyComment> allergyCommentList = Arrays.asList(allergyComment);
oVprAllergy.setData("comments", allergyCommentList);
}
oVprAllergy.setData("facilityName", sSystemId);
oVprAllergy.setData("facilityCode", sSystemId);
oVprAllergy.setData("uid",UidUtils.getAllergyUid(sSystemId, sEdipi, oAllergy.getCdrEventId()));
String sAllergyJson = oVprAllergy.toJSON(JDBView.class);
LOG.debug("JMeadowsAllergyService.transformAllergyJson - Returning JSON String: " + sAllergyJson);
return sAllergyJson;
}
}
|
|
/* The following code was generated by JFlex 1.4.3 on 6/16/16 11:49 AM */
/*
* Copyright 2000-2008 JetBrains s.r.o.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.scala.lang.scaladoc.lexer;
import com.intellij.lexer.FlexLexer;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.plugins.scala.lang.scaladoc.lexer.docsyntax.*;
import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes;
/**
* This class is a scanner generated by
* <a href="http://www.jflex.de/">JFlex</a> 1.4.3
* on 6/16/16 11:49 AM from the specification file
* <tt>../../scaladoc/lexer/scaladoc.flex</tt>
*/
public class _ScalaDocLexer implements FlexLexer, ScalaDocTokenType, ScalaTokenTypes {
/** initial size of the lookahead buffer */
private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */
public static final int INNER_CODE_WHITESPACE = 40;
public static final int CODE_BAD_LINK = 32;
public static final int COMMENT_DATA = 4;
public static final int PARAM_DOC_TAG_VALUE = 16;
public static final int COMMENT_DATA_START = 2;
public static final int DOC_TAG_VALUE_IN_PAREN = 20;
public static final int PARAM_DOC_THROWS_TAG_VALUE = 18;
public static final int CODE_LINK_INNER = 30;
public static final int HTTP_LINK_INNER = 34;
public static final int DOC_TAG_VALUE = 14;
public static final int INLINE_TAG_NAME = 24;
public static final int PARAM_TAG_DOC_SPACE = 8;
public static final int DOC_TAG_VALUE_IN_LTGT = 22;
public static final int PARAM_THROWS_TAG_DOC_SPACE = 10;
public static final int COMMENT_INNER_CODE = 38;
public static final int DOC_TAG_VALUE_SPACE = 36;
public static final int YYINITIAL = 0;
public static final int PARAM_TAG_SPACE = 12;
public static final int TAG_DOC_SPACE = 6;
public static final int INLINE_DOC_TAG_VALUE = 26;
public static final int INLINE_TAG_DOC_SPACE = 28;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line
* l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = {
0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7,
8, 8, 9, 9, 10, 10, 6, 6, 11, 11, 12, 12, 13, 13, 14, 14,
15, 15, 6, 6, 16, 16, 17, 17, 18, 18
};
/**
* Translates characters to character classes
*/
private static final String ZZ_CMAP_PACKED =
"\11\20\1\2\1\1\1\0\1\2\1\1\16\20\4\0\1\2\1\6"+
"\1\17\1\7\1\30\2\6\1\23\1\37\1\40\1\10\1\6\1\24"+
"\1\11\1\5\1\15\10\3\2\3\1\13\1\0\1\6\1\27\1\6"+
"\1\6\1\41\32\4\1\25\1\14\1\36\1\12\1\21\1\22\1\45"+
"\2\4\1\47\1\50\1\51\1\4\1\32\1\52\3\4\1\46\1\53"+
"\1\43\1\34\1\4\1\42\1\35\1\33\2\4\1\44\3\4\1\26"+
"\1\6\1\31\1\6\6\20\1\16\32\20\2\0\4\4\1\6\2\0"+
"\1\6\1\4\1\0\1\6\1\20\1\6\1\0\1\6\1\6\3\0"+
"\1\4\4\0\1\4\5\0\27\4\1\6\37\4\1\6\u01ca\4\4\0"+
"\14\4\16\0\5\4\7\0\1\4\1\0\1\4\21\0\160\20\5\4"+
"\1\0\2\4\2\0\4\4\10\0\1\4\1\0\3\4\1\0\1\4"+
"\1\0\24\4\1\0\123\4\1\6\213\4\1\6\5\20\2\0\236\4"+
"\11\0\46\4\2\0\1\4\7\0\47\4\7\0\1\4\1\0\55\20"+
"\1\0\1\20\1\0\2\20\1\0\2\20\1\0\1\20\10\0\33\4"+
"\5\0\3\4\15\0\5\20\1\0\3\6\2\0\1\4\2\0\2\6"+
"\13\20\5\0\53\4\37\20\4\0\2\4\1\20\143\4\1\0\1\4"+
"\10\20\1\6\6\20\2\4\2\20\1\6\4\20\2\4\12\20\3\4"+
"\2\6\1\4\17\0\1\20\1\4\1\20\36\4\33\20\2\0\131\4"+
"\13\20\1\4\16\0\12\20\41\4\11\20\2\4\1\6\3\0\1\4"+
"\5\0\26\4\4\20\1\4\11\20\1\4\3\20\1\4\5\20\22\0"+
"\31\4\3\20\104\0\1\4\1\0\13\4\67\0\33\20\1\0\4\20"+
"\66\4\3\20\1\4\22\20\1\4\7\20\12\4\2\20\2\0\12\20"+
"\1\0\7\4\1\0\7\4\1\0\3\20\1\0\10\4\2\0\2\4"+
"\2\0\26\4\1\0\7\4\1\0\1\4\3\0\4\4\2\0\1\20"+
"\1\4\7\20\2\0\2\20\2\0\3\20\1\4\10\0\1\20\4\0"+
"\2\4\1\0\3\4\2\20\2\0\12\20\4\4\6\0\1\6\1\4"+
"\5\0\3\20\1\0\6\4\4\0\2\4\2\0\26\4\1\0\7\4"+
"\1\0\2\4\1\0\2\4\1\0\2\4\2\0\1\20\1\0\5\20"+
"\4\0\2\20\2\0\3\20\3\0\1\20\7\0\4\4\1\0\1\4"+
"\7\0\14\20\3\4\1\20\13\0\3\20\1\0\11\4\1\0\3\4"+
"\1\0\26\4\1\0\7\4\1\0\2\4\1\0\5\4\2\0\1\20"+
"\1\4\10\20\1\0\3\20\1\0\3\20\2\0\1\4\17\0\2\4"+
"\2\20\2\0\12\20\1\0\1\4\17\0\3\20\1\0\10\4\2\0"+
"\2\4\2\0\26\4\1\0\7\4\1\0\2\4\1\0\5\4\2\0"+
"\1\20\1\4\7\20\2\0\2\20\2\0\3\20\10\0\2\20\4\0"+
"\2\4\1\0\3\4\2\20\2\0\12\20\1\6\1\4\20\0\1\20"+
"\1\4\1\0\6\4\3\0\3\4\1\0\4\4\3\0\2\4\1\0"+
"\1\4\1\0\2\4\3\0\2\4\3\0\3\4\3\0\14\4\4\0"+
"\5\20\3\0\3\20\1\0\4\20\2\0\1\4\6\0\1\20\16\0"+
"\12\20\3\0\6\6\1\4\1\6\6\0\3\20\1\0\10\4\1\0"+
"\3\4\1\0\27\4\1\0\12\4\1\0\5\4\3\0\1\4\7\20"+
"\1\0\3\20\1\0\4\20\7\0\2\20\1\0\2\4\6\0\2\4"+
"\2\20\2\0\12\20\17\0\1\6\2\0\2\20\1\0\10\4\1\0"+
"\3\4\1\0\27\4\1\0\12\4\1\0\5\4\2\0\1\20\1\4"+
"\7\20\1\0\3\20\1\0\4\20\7\0\2\20\7\0\1\4\1\0"+
"\2\4\2\20\2\0\12\20\1\0\2\4\17\0\2\20\1\0\10\4"+
"\1\0\3\4\1\0\51\4\2\0\1\4\7\20\1\0\3\20\1\0"+
"\4\20\1\4\10\0\1\20\10\0\2\4\2\20\2\0\12\20\11\0"+
"\1\6\6\4\2\0\2\20\1\0\22\4\3\0\30\4\1\0\11\4"+
"\1\0\1\4\2\0\7\4\3\0\1\20\4\0\6\20\1\0\1\20"+
"\1\0\10\20\22\0\2\20\15\0\60\4\1\20\2\4\7\20\4\0"+
"\10\4\10\20\1\0\12\20\47\0\2\4\1\0\1\4\2\0\2\4"+
"\1\0\1\4\2\0\1\4\6\0\4\4\1\0\7\4\1\0\3\4"+
"\1\0\1\4\1\0\1\4\2\0\2\4\1\0\4\4\1\20\2\4"+
"\6\20\1\0\2\20\1\4\2\0\5\4\1\0\1\4\1\0\6\20"+
"\2\0\12\20\2\0\4\4\40\0\1\4\3\6\17\0\1\6\1\0"+
"\3\6\2\20\6\6\12\20\12\0\1\6\1\20\1\6\1\20\1\6"+
"\1\20\4\0\2\20\10\4\1\0\44\4\4\0\24\20\1\0\2\20"+
"\5\4\13\20\1\0\44\20\1\0\10\6\1\20\6\6\1\0\2\6"+
"\5\0\4\6\47\0\53\4\24\20\1\4\12\20\6\0\6\4\4\20"+
"\4\4\3\20\1\4\3\20\2\4\7\20\3\4\4\20\15\4\14\20"+
"\1\4\17\20\2\6\46\4\1\0\1\4\5\0\1\4\2\0\53\4"+
"\1\0\u014d\4\1\0\4\4\2\0\7\4\1\0\1\4\1\0\4\4"+
"\2\0\51\4\1\0\4\4\2\0\41\4\1\0\4\4\2\0\7\4"+
"\1\0\1\4\1\0\4\4\2\0\17\4\1\0\71\4\1\0\4\4"+
"\2\0\103\4\2\0\3\20\40\0\20\4\12\6\6\0\125\4\14\0"+
"\u026c\4\2\0\21\4\1\0\32\4\5\0\113\4\3\0\3\4\17\0"+
"\15\4\1\0\4\4\3\20\13\0\22\4\3\20\13\0\22\4\2\20"+
"\14\0\15\4\1\0\3\4\1\0\2\20\14\0\64\4\40\20\3\0"+
"\1\4\3\0\2\4\1\20\2\0\12\20\41\0\3\20\2\0\12\20"+
"\6\0\130\4\10\0\51\4\1\20\1\4\5\0\106\4\12\0\35\4"+
"\3\0\14\20\4\0\14\20\4\0\1\6\5\0\12\20\36\4\2\0"+
"\5\4\13\0\54\4\4\0\21\20\7\4\2\20\6\0\12\20\4\0"+
"\42\6\27\4\5\20\4\0\65\4\12\20\1\0\35\20\2\0\13\20"+
"\6\0\12\20\15\0\1\4\130\0\5\20\57\4\21\20\7\4\4\0"+
"\12\20\7\0\12\6\11\20\11\6\3\0\3\20\36\4\15\20\2\4"+
"\12\20\54\4\16\20\14\0\44\4\24\20\10\0\12\20\3\0\3\4"+
"\12\20\44\4\122\0\3\20\1\0\25\20\4\4\1\20\4\4\3\20"+
"\2\4\11\0\300\4\47\20\25\0\4\20\u0116\4\2\0\6\4\2\0"+
"\46\4\2\0\6\4\2\0\10\4\1\0\1\4\1\0\1\4\1\0"+
"\1\4\1\0\37\4\2\0\65\4\1\0\7\4\1\0\1\4\3\0"+
"\3\4\1\0\7\4\3\0\4\4\2\0\6\4\4\0\15\4\5\0"+
"\3\4\1\0\7\4\16\0\5\20\30\0\1\17\1\17\5\20\20\0"+
"\2\4\3\0\1\6\15\0\1\6\1\0\1\4\13\0\5\20\5\0"+
"\6\20\1\0\1\4\10\0\3\6\2\0\1\4\12\0\3\6\3\0"+
"\15\4\3\0\33\4\25\0\15\20\4\0\1\20\3\0\14\20\17\0"+
"\2\6\1\4\4\6\1\4\2\6\12\4\1\6\1\4\2\6\1\6"+
"\5\4\6\6\1\4\1\6\1\4\1\6\1\4\1\6\4\4\1\6"+
"\13\4\2\6\4\4\5\6\5\4\1\6\1\6\2\6\1\4\1\6"+
"\20\0\51\4\7\0\5\6\5\6\2\6\4\6\1\6\2\6\1\6"+
"\2\6\1\6\7\6\1\6\37\6\2\6\2\6\1\6\1\6\1\6"+
"\37\6\u010c\6\10\6\4\6\24\6\2\6\7\6\2\0\121\6\1\6"+
"\36\6\31\6\50\6\6\6\22\6\14\0\47\6\31\0\13\6\121\0"+
"\116\6\26\0\267\6\1\6\11\6\1\6\66\6\10\6\157\6\1\6"+
"\220\6\1\0\147\6\54\0\54\6\5\6\2\0\37\6\12\0\20\6"+
"\u0100\6\203\6\26\0\77\6\4\0\40\6\2\0\u0102\6\60\6\25\6"+
"\2\6\6\6\3\0\12\6\246\0\57\4\1\0\57\4\1\0\205\4"+
"\6\6\4\4\3\20\2\4\14\0\46\4\1\0\1\4\5\0\1\4"+
"\2\0\70\4\7\0\1\4\17\0\1\20\27\4\11\0\7\4\1\0"+
"\7\4\1\0\7\4\1\0\7\4\1\0\7\4\1\0\7\4\1\0"+
"\7\4\1\0\7\4\1\0\40\20\57\0\1\4\120\0\32\6\1\0"+
"\131\6\14\0\326\6\32\0\14\6\10\0\1\6\3\4\12\0\2\6"+
"\14\0\1\6\11\4\6\20\1\0\5\4\2\6\5\4\1\0\2\6"+
"\1\0\126\4\2\0\2\20\2\0\3\4\1\0\132\4\1\0\4\4"+
"\5\0\51\4\3\0\136\4\1\0\2\6\4\0\12\6\33\4\5\0"+
"\44\6\14\0\20\4\37\6\13\0\36\6\10\0\1\6\17\0\40\6"+
"\12\0\47\6\17\0\77\6\1\0\u0100\6\u19b6\4\12\0\100\6\u51cd\4"+
"\63\0\u048d\4\3\0\67\6\11\0\56\4\2\0\u010d\4\3\0\20\4"+
"\12\20\2\4\24\0\57\4\1\20\4\0\12\20\1\0\31\4\7\0"+
"\1\20\120\4\2\20\45\0\11\4\2\0\147\4\2\0\4\4\1\0"+
"\4\4\14\0\13\4\115\0\12\4\1\20\3\4\1\20\4\4\1\20"+
"\27\4\5\20\4\6\12\0\2\6\1\4\1\6\6\0\64\4\14\0"+
"\2\20\62\4\21\20\13\0\12\20\6\0\22\20\6\4\3\0\1\4"+
"\4\0\12\20\34\4\10\20\2\0\27\4\15\20\14\0\35\4\3\0"+
"\4\20\57\4\16\20\16\0\1\4\12\20\46\0\51\4\16\20\11\0"+
"\3\4\1\20\10\4\2\20\2\0\12\20\6\0\27\4\3\6\1\4"+
"\1\20\4\0\60\4\1\20\1\4\3\20\2\4\2\20\5\4\2\20"+
"\1\4\1\20\1\4\30\0\3\4\2\0\13\4\5\20\2\0\3\4"+
"\2\20\12\0\6\4\2\0\6\4\2\0\6\4\11\0\7\4\1\0"+
"\7\4\221\0\43\4\10\20\1\0\2\20\2\0\12\20\6\0\u2ba4\4"+
"\14\0\27\4\4\0\61\4\u2104\0\u016e\4\2\0\152\4\46\0\7\4"+
"\14\0\5\4\5\0\1\4\1\20\12\4\1\6\15\4\1\0\5\4"+
"\1\0\1\4\1\0\2\4\1\0\2\4\1\0\154\4\41\0\u016b\4"+
"\22\0\100\4\2\0\66\4\50\0\15\4\1\6\2\0\20\20\20\0"+
"\7\20\14\0\2\4\30\0\3\4\22\0\1\6\1\0\3\6\2\0"+
"\1\4\6\0\5\4\1\0\207\4\2\0\1\20\4\0\1\4\6\0"+
"\1\6\4\0\12\20\2\0\3\6\2\0\32\4\4\0\1\4\1\0"+
"\32\4\1\0\1\6\1\0\1\6\7\0\131\4\3\0\6\4\2\0"+
"\6\4\2\0\6\4\2\0\3\4\3\0\2\4\1\6\1\0\1\6"+
"\2\4\1\0\1\6\4\6\2\6\12\0\3\20\2\6\2\0";
/**
* Translates characters to character classes
*/
private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
/**
* Translates DFA states to action switch labels.
*/
private static final int [] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\23\0\3\1\1\2\1\3\1\2\1\4\1\2\1\5"+
"\4\2\1\6\3\2\1\7\1\10\1\11\1\1\1\12"+
"\1\13\1\14\1\15\1\16\1\17\1\20\2\21\1\1"+
"\1\22\1\23\1\22\1\1\1\24\1\1\1\7\1\25"+
"\1\26\2\27\2\1\1\30\2\31\2\32\1\0\1\33"+
"\1\0\1\34\1\35\1\36\1\37\2\0\1\40\1\41"+
"\4\42\1\21\2\0\1\21\1\43\1\22\2\0\1\22"+
"\1\44\1\27\3\0\1\27\1\0\1\45\1\46\1\0"+
"\1\47\1\50\3\42\1\21\1\22\1\51\1\27\1\52"+
"\2\0\3\42\2\43\3\0\3\42\1\51\1\53\1\0"+
"\1\42\1\54\1\42\1\55\1\0\1\56";
private static int [] zzUnpackAction() {
int [] result = new int[134];
int offset = 0;
offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/**
* Translates a state to a row index in the transition table
*/
private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\54\0\130\0\204\0\260\0\334\0\u0108\0\u0134"+
"\0\u0160\0\u018c\0\u01b8\0\u01e4\0\u0210\0\u023c\0\u0268\0\u0294"+
"\0\u02c0\0\u02ec\0\u0318\0\u0318\0\u0344\0\u0370\0\u0318\0\u039c"+
"\0\u0344\0\u0318\0\u03c8\0\u0318\0\u03f4\0\u0420\0\u044c\0\u0478"+
"\0\u04a4\0\u04d0\0\u04fc\0\u0528\0\u0554\0\u0580\0\u05ac\0\u044c"+
"\0\u05d8\0\u0604\0\u0630\0\u065c\0\u0318\0\u0318\0\u0318\0\u0688"+
"\0\u06b4\0\u06e0\0\u070c\0\u0318\0\u0738\0\u0764\0\u0318\0\u0790"+
"\0\u07bc\0\u0318\0\u07e8\0\u0814\0\u0840\0\u086c\0\u04fc\0\u0898"+
"\0\u0318\0\u0344\0\u0318\0\u08c4\0\u0344\0\u0318\0\u08f0\0\u0318"+
"\0\u091c\0\u0318\0\u0948\0\u0974\0\u09a0\0\u09cc\0\u0318\0\u09f8"+
"\0\u0a24\0\u0a50\0\u0a7c\0\u0aa8\0\u06e0\0\u0ad4\0\u0318\0\u0318"+
"\0\u0b00\0\u0764\0\u0b2c\0\u0b58\0\u0b84\0\u0bb0\0\u0bdc\0\u086c"+
"\0\u0c08\0\u0c34\0\u0c60\0\u0318\0\u0c8c\0\u0cb8\0\u0318\0\u0ce4"+
"\0\u0d10\0\u0d3c\0\u0d68\0\u06e0\0\u0d94\0\u0318\0\u0dc0\0\u0318"+
"\0\u0dec\0\u0e18\0\u0e44\0\u0e70\0\u0e9c\0\u0764\0\u086c\0\u0ec8"+
"\0\u0ef4\0\u0f20\0\u0f4c\0\u0f78\0\u0fa4\0\u086c\0\u0318\0\u0fd0"+
"\0\u0ffc\0\u09f8\0\u1028\0\u0318\0\u1054\0\u09f8";
private static int [] zzUnpackRowMap() {
int [] result = new int[134];
int offset = 0;
offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int high = packed.charAt(i++) << 16;
result[j++] = high | packed.charAt(i++);
}
return j;
}
/**
* The transition table of the DFA
*/
private static final int [] ZZ_TRANS = zzUnpackTrans();
private static final String ZZ_TRANS_PACKED_0 =
"\10\24\1\25\4\24\1\26\36\24\1\27\2\30\5\27"+
"\1\31\1\27\1\32\6\27\1\33\1\34\1\35\1\36"+
"\1\37\1\40\1\41\1\42\5\27\1\43\2\27\1\44"+
"\13\27\1\30\1\45\5\27\1\31\1\27\1\32\6\27"+
"\1\33\1\34\1\35\1\36\1\37\1\40\1\46\1\42"+
"\5\27\1\43\15\27\1\24\2\47\5\24\1\25\14\24"+
"\1\50\27\24\1\51\1\52\5\24\1\25\44\24\1\51"+
"\1\53\5\24\1\25\53\24\1\25\43\24\1\27\2\51"+
"\3\54\1\27\1\55\1\31\10\27\1\54\2\27\1\56"+
"\1\54\2\27\1\54\1\27\5\54\1\57\2\27\12\54"+
"\4\24\1\60\1\24\10\61\3\24\1\60\1\62\4\24"+
"\1\61\1\60\1\24\4\60\3\24\1\61\12\60\4\24"+
"\1\63\1\64\10\65\3\24\1\63\1\66\4\24\1\65"+
"\1\63\1\24\4\63\3\24\1\65\12\63\1\24\2\30"+
"\3\54\2\24\1\25\10\24\1\54\2\24\1\56\1\54"+
"\2\24\1\54\1\24\5\54\1\24\1\67\1\24\12\54"+
"\10\24\1\25\30\24\1\70\12\24\31\71\1\72\22\71"+
"\1\24\2\73\5\24\1\25\20\24\1\72\26\24\1\74"+
"\1\64\10\75\3\24\1\74\1\76\4\24\1\75\1\74"+
"\1\24\4\74\1\77\2\24\1\75\12\74\1\24\1\100"+
"\6\24\1\25\25\24\1\77\15\24\1\101\2\51\5\101"+
"\1\102\43\101\1\103\1\30\27\103\1\104\22\103\64\0"+
"\1\105\4\0\1\106\46\0\1\107\44\0\2\30\72\0"+
"\1\110\55\0\1\111\54\0\1\112\54\0\1\113\54\0"+
"\1\114\12\0\1\115\41\0\1\41\30\0\1\116\14\0"+
"\1\116\6\0\1\116\1\0\4\116\4\0\12\116\36\0"+
"\1\117\21\0\1\120\14\0\1\120\6\0\1\120\1\0"+
"\1\120\1\121\1\122\1\120\4\0\5\120\1\123\4\120"+
"\2\0\1\45\100\0\1\46\25\0\2\47\52\0\2\51"+
"\52\0\1\51\1\52\52\0\1\51\1\53\54\0\3\54"+
"\13\0\1\54\3\0\1\54\2\0\1\54\1\0\5\54"+
"\3\0\12\54\3\0\2\60\11\0\1\60\1\0\1\60"+
"\1\124\6\0\1\60\1\0\4\60\4\0\12\60\6\0"+
"\10\61\11\0\1\61\11\0\1\61\12\0\1\125\1\0"+
"\12\125\1\126\1\125\2\0\2\125\1\127\31\125\3\0"+
"\2\63\1\130\10\0\1\63\1\0\1\63\1\131\6\0"+
"\1\63\1\0\4\63\4\0\12\63\5\0\1\130\10\65"+
"\11\0\1\65\11\0\1\65\12\0\1\132\1\0\12\132"+
"\1\133\1\132\2\0\2\132\1\134\31\132\4\0\1\135"+
"\14\0\1\135\6\0\1\135\1\0\4\135\4\0\12\135"+
"\31\71\1\0\22\71\1\0\2\73\54\0\2\74\1\130"+
"\10\0\1\74\1\0\1\74\1\136\6\0\1\74\1\0"+
"\4\74\1\137\3\0\12\74\5\0\1\130\10\75\11\0"+
"\1\75\6\0\1\137\2\0\1\75\12\0\1\140\1\0"+
"\12\140\1\141\1\140\2\0\2\140\1\142\31\140\1\0"+
"\2\100\102\0\1\143\32\0\1\144\66\0\1\145\62\0"+
"\1\146\47\0\1\147\31\0\1\150\14\0\1\150\6\0"+
"\1\150\1\0\4\150\4\0\12\150\3\0\3\116\3\0"+
"\1\116\1\0\1\116\5\0\1\116\6\0\1\116\1\0"+
"\4\116\4\0\12\116\3\0\3\120\3\0\1\120\1\0"+
"\1\120\5\0\1\120\6\0\1\120\1\0\4\120\4\0"+
"\12\120\3\0\3\120\3\0\1\120\1\0\1\120\5\0"+
"\1\120\6\0\1\120\1\0\1\151\1\120\1\122\1\120"+
"\4\0\12\120\3\0\3\120\3\0\1\120\1\0\1\120"+
"\5\0\1\120\6\0\1\120\1\0\4\120\4\0\3\120"+
"\1\152\6\120\3\0\3\120\3\0\1\120\1\0\1\120"+
"\5\0\1\120\6\0\1\120\1\0\4\120\4\0\6\120"+
"\1\153\3\120\3\0\2\60\1\0\10\61\1\60\1\0"+
"\1\60\1\124\5\0\1\61\1\60\1\0\4\60\3\0"+
"\1\61\12\60\1\125\1\0\12\125\1\126\5\125\1\154"+
"\31\125\3\0\2\63\1\130\10\65\1\63\1\0\1\63"+
"\1\131\5\0\1\65\1\63\1\0\4\63\3\0\1\65"+
"\12\63\1\132\1\0\12\132\1\133\5\132\1\155\31\132"+
"\5\0\1\130\51\0\3\135\3\0\1\135\1\0\1\135"+
"\5\0\1\135\6\0\1\135\1\0\4\135\4\0\12\135"+
"\3\0\2\74\1\130\10\75\1\74\1\0\1\74\1\136"+
"\5\0\1\75\1\74\1\0\4\74\1\137\2\0\1\75"+
"\12\74\36\0\1\156\15\0\1\140\1\0\12\140\1\141"+
"\5\140\1\157\31\140\5\0\1\130\30\0\1\137\46\0"+
"\1\160\45\0\1\161\63\0\1\162\23\0\3\150\3\0"+
"\1\150\1\0\1\150\5\0\1\150\6\0\1\150\1\0"+
"\4\150\4\0\12\150\3\0\3\120\3\0\1\120\1\0"+
"\1\120\5\0\1\120\6\0\1\120\1\0\4\120\4\0"+
"\1\163\11\120\3\0\3\120\3\0\1\120\1\0\1\120"+
"\5\0\1\120\6\0\1\120\1\0\4\120\4\0\1\164"+
"\11\120\3\0\3\120\3\0\1\120\1\0\1\120\5\0"+
"\1\120\6\0\1\120\1\0\4\120\4\0\7\120\1\165"+
"\2\120\1\132\1\0\3\132\1\166\6\132\1\133\1\132"+
"\2\0\2\132\1\134\31\132\1\140\1\0\3\140\1\167"+
"\6\140\1\141\1\140\2\0\2\140\1\142\13\140\1\170"+
"\15\140\23\0\1\171\63\0\1\172\23\0\3\120\3\0"+
"\1\120\1\0\1\120\5\0\1\120\6\0\1\120\1\0"+
"\4\120\4\0\1\120\1\173\10\120\3\0\3\120\3\0"+
"\1\120\1\0\1\120\5\0\1\120\6\0\1\120\1\0"+
"\4\120\4\0\3\120\1\174\6\120\3\0\3\120\3\0"+
"\1\120\1\0\1\120\5\0\1\120\6\0\1\120\1\0"+
"\4\120\4\0\10\120\1\175\1\120\1\140\1\0\12\140"+
"\1\141\1\140\2\0\2\140\1\142\13\140\1\176\15\140"+
"\23\177\1\0\30\177\34\0\1\200\22\0\3\120\3\0"+
"\1\120\1\0\1\120\5\0\1\120\6\0\1\120\1\0"+
"\4\120\4\0\2\120\1\201\7\120\3\0\3\120\3\0"+
"\1\120\1\0\1\120\5\0\1\120\6\0\1\120\1\0"+
"\4\120\4\0\4\120\1\202\5\120\3\0\3\120\3\0"+
"\1\120\1\0\1\120\5\0\1\120\6\0\1\120\1\0"+
"\4\120\4\0\11\120\1\203\13\0\1\204\21\0\1\205"+
"\21\0\3\120\3\0\1\120\1\0\1\120\5\0\1\120"+
"\6\0\1\120\1\0\3\120\1\206\4\0\12\120\3\0"+
"\3\120\3\0\1\120\1\0\1\120\5\0\1\120\6\0"+
"\1\120\1\0\4\120\4\0\6\120\1\202\3\120\13\0"+
"\1\204\40\0";
private static int [] zzUnpackTrans() {
int [] result = new int[4224];
int offset = 0;
offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
return result;
}
private static int zzUnpackTrans(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
value--;
do result[j++] = value; while (--count > 0);
}
return j;
}
/* error codes */
private static final int ZZ_UNKNOWN_ERROR = 0;
private static final int ZZ_NO_MATCH = 1;
private static final int ZZ_PUSHBACK_2BIG = 2;
private static final char[] EMPTY_BUFFER = new char[0];
private static final int YYEOF = -1;
private static java.io.Reader zzReader = null; // Fake
/* error messages for the codes above */
private static final String ZZ_ERROR_MSG[] = {
"Unkown internal scanner error",
"Error: could not match input",
"Error: pushback value was too large"
};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\22\0\1\10\1\11\2\1\1\11\2\1\1\11\1\1"+
"\1\11\20\1\3\11\4\1\1\11\2\1\1\11\2\1"+
"\1\11\6\1\1\11\1\1\1\11\1\1\1\0\1\11"+
"\1\0\1\11\1\1\1\11\1\1\2\0\1\1\1\11"+
"\5\1\2\0\2\11\1\1\2\0\3\1\3\0\1\1"+
"\1\0\1\11\1\1\1\0\1\11\6\1\1\11\1\1"+
"\1\11\2\0\5\1\3\0\4\1\1\11\1\0\3\1"+
"\1\11\1\0\1\1";
private static int [] zzUnpackAttribute() {
int [] result = new int[134];
int offset = 0;
offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int [] result) {
int i = 0; /* index in packed string */
int j = offset; /* index in unpacked array */
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
}
return j;
}
/** the current state of the DFA */
private int zzState;
/** the current lexical state */
private int zzLexicalState = YYINITIAL;
/** this buffer contains the current text to be matched and is
the source of the yytext() string */
private CharSequence zzBuffer = "";
/** this buffer may contains the current text array to be matched when it is cheap to acquire it */
private char[] zzBufferArray;
/** the textposition at the last accepting state */
private int zzMarkedPos;
/** the textposition at the last state to be included in yytext */
private int zzPushbackPos;
/** the current text position in the buffer */
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
private int zzStartRead;
/** endRead marks the last character in the buffer, that has been read
from input */
private int zzEndRead;
/**
* zzAtBOL == true <=> the scanner is currently at the beginning of a line
*/
private boolean zzAtBOL = true;
/** zzAtEOF == true <=> the scanner is at the EOF */
private boolean zzAtEOF;
/** denotes if the user-EOF-code has already been executed */
private boolean zzEOFDone;
/* user code: */
private boolean isOddItalicBold = false;;
public _ScalaDocLexer() {
this((java.io.Reader)null);
}
public boolean checkAhead(char c) {
if (zzMarkedPos >= zzBuffer.length()) return false;
return zzBuffer.charAt(zzMarkedPos) == c;
}
public void goTo(int offset) {
zzCurrentPos = zzMarkedPos = zzStartRead = offset;
zzPushbackPos = 0;
zzAtEOF = offset < zzEndRead;
}
/**
* Creates a new scanner
*
* @param in the java.io.Reader to read input from.
*/
public _ScalaDocLexer(java.io.Reader in) {
this.zzReader = in;
}
/**
* Unpacks the compressed character translation table.
*
* @param packed the packed character translation table
* @return the unpacked character translation table
*/
private static char [] zzUnpackCMap(String packed) {
char [] map = new char[0x10000];
int i = 0; /* index in packed string */
int j = 0; /* index in unpacked array */
while (i < 2598) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
}
return map;
}
public final int getTokenStart(){
return zzStartRead;
}
public final int getTokenEnd(){
return getTokenStart() + yylength();
}
public void reset(CharSequence buffer, int start, int end,int initialState){
zzBuffer = buffer;
zzBufferArray = com.intellij.util.text.CharArrayUtil.fromSequenceWithoutCopying(buffer);
zzCurrentPos = zzMarkedPos = zzStartRead = start;
zzPushbackPos = 0;
zzAtEOF = false;
zzAtBOL = true;
zzEndRead = end;
yybegin(initialState);
}
// For Demetra compatibility
public void reset(CharSequence buffer, int initialState){
zzBuffer = buffer;
zzBufferArray = null;
zzCurrentPos = zzMarkedPos = zzStartRead = 0;
zzPushbackPos = 0;
zzAtEOF = false;
zzAtBOL = true;
zzEndRead = buffer.length();
yybegin(initialState);
}
/**
* Refills the input buffer.
*
* @return <code>false</code>, iff there was new input.
*
* @exception java.io.IOException if any I/O-Error occurs
*/
private boolean zzRefill() throws java.io.IOException {
return true;
}
/**
* Returns the current lexical state.
*/
public final int yystate() {
return zzLexicalState;
}
/**
* Enters a new lexical state
*
* @param newState the new lexical state
*/
public final void yybegin(int newState) {
zzLexicalState = newState;
}
/**
* Returns the text matched by the current regular expression.
*/
public final CharSequence yytext() {
return zzBuffer.subSequence(zzStartRead, zzMarkedPos);
}
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
*
* It is equivalent to yytext().charAt(pos), but faster
*
* @param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
*
* @return the character at position pos
*/
public final char yycharat(int pos) {
return zzBufferArray != null ? zzBufferArray[zzStartRead+pos]:zzBuffer.charAt(zzStartRead+pos);
}
/**
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos-zzStartRead;
}
/**
* Reports an error that occured while scanning.
*
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
*
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
*
* @param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
}
catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Error(message);
}
/**
* Pushes the specified amount of characters back into the input stream.
*
* They will be read again by then next call of the scanning method
*
* @param number the number of characters to be read again.
* This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if ( number > yylength() )
zzScanError(ZZ_PUSHBACK_2BIG);
zzMarkedPos -= number;
}
/**
* Contains user EOF-code, which will be executed exactly once,
* when the end of file is reached
*/
private void zzDoEOF() {
if (!zzEOFDone) {
zzEOFDone = true;
}
}
/**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
*
* @return the next token
* @exception java.io.IOException if any I/O-Error occurs
*/
public IElementType advance() throws java.io.IOException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
CharSequence zzBufferL = zzBuffer;
char[] zzBufferArrayL = zzBufferArray;
char [] zzCMapL = ZZ_CMAP;
int [] zzTransL = ZZ_TRANS;
int [] zzRowMapL = ZZ_ROWMAP;
int [] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL)
zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++));
else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
}
else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
}
else {
zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++));
}
}
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
int zzAttributes = zzAttrL[zzState];
if ( (zzAttributes & 1) == 1 ) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ( (zzAttributes & 8) == 8 ) break zzForAction;
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 28:
{ return DOC_UNDERLINE_TAG;
}
case 47: break;
case 17:
{ yybegin(DOC_TAG_VALUE_SPACE); return DOC_TAG_VALUE_TOKEN;
}
case 48: break;
case 1:
{ return DOC_COMMENT_BAD_CHARACTER;
}
case 49: break;
case 39:
{ yybegin(COMMENT_INNER_CODE);
return DOC_INNER_CODE_TAG;
}
case 50: break;
case 11:
{ yybegin(PARAM_DOC_TAG_VALUE); return DOC_COMMENT_DATA;
}
case 51: break;
case 19:
{ return tDOT;
}
case 52: break;
case 7:
{ return DOC_COMMENT_DATA;
}
case 53: break;
case 29:
{ return DOC_ITALIC_TAG;
}
case 54: break;
case 12:
{ yybegin(PARAM_DOC_THROWS_TAG_VALUE); return DOC_COMMENT_DATA;
}
case 55: break;
case 36:
{ yybegin(INLINE_TAG_DOC_SPACE); return DOC_TAG_NAME;
}
case 56: break;
case 23:
{ yybegin(CODE_BAD_LINK);
return tIDENTIFIER;
}
case 57: break;
case 33:
{ yybegin(COMMENT_DATA);
return DOC_LINK_CLOSE_TAG;
}
case 58: break;
case 32:
{ return DOC_MACROS;
}
case 59: break;
case 13:
{ return DOC_TAG_VALUE_TOKEN;
}
case 60: break;
case 27:
{ return DOC_COMMENT_END;
}
case 61: break;
case 42:
{ yybegin(COMMENT_DATA);
return DOC_INNER_CLOSE_CODE_TAG;
}
case 62: break;
case 14:
{ return DOC_TAG_VALUE_SHARP_TOKEN;
}
case 63: break;
case 18:
{ yybegin(DOC_TAG_VALUE_SPACE);
return tIDENTIFIER;
}
case 64: break;
case 25:
{ yybegin(COMMENT_DATA); return DOC_COMMENT_DATA;
}
case 65: break;
case 6:
{ return VALID_DOC_HEADER;
}
case 66: break;
case 37:
{ yybegin(COMMENT_DATA_START); return DOC_COMMENT_START;
}
case 67: break;
case 46:
{ yybegin(PARAM_THROWS_TAG_DOC_SPACE); return DOC_TAG_NAME;
}
case 68: break;
case 41:
// lookahead expression with fixed lookahead length
yypushback(2);
{ return tIDENTIFIER;
}
case 69: break;
case 35:
// lookahead expression with fixed lookahead length
yypushback(1);
{ return tIDENTIFIER;
}
case 70: break;
case 26:
{ yybegin(COMMENT_INNER_CODE);
return DOC_INNER_CODE;
}
case 71: break;
case 24:
{ yybegin(COMMENT_DATA);
return DOC_WHITESPACE;
}
case 72: break;
case 8:
{ return DOC_HEADER;
}
case 73: break;
case 30:
{ return DOC_SUBSCRIPT_TAG;
}
case 74: break;
case 16:
{ yybegin(DOC_TAG_VALUE_IN_PAREN); return DOC_TAG_VALUE_LPAREN;
}
case 75: break;
case 40:
// lookahead expression with fixed base length
zzMarkedPos = zzStartRead + 1;
{ yybegin(INLINE_TAG_NAME);
return DOC_INLINE_TAG_START;
}
case 76: break;
case 15:
{ return DOC_TAG_VALUE_COMMA;
}
case 77: break;
case 38:
{ return DOC_BOLD_TAG;
}
case 78: break;
case 34:
{ yybegin(TAG_DOC_SPACE); return DOC_TAG_NAME;
}
case 79: break;
case 9:
{ yybegin(COMMENT_DATA);
return DOC_WHITESPACE;
}
case 80: break;
case 44:
{ yybegin(PARAM_TAG_DOC_SPACE); return DOC_TAG_NAME;
}
case 81: break;
case 10:
{ yybegin(COMMENT_DATA); return DOC_WHITESPACE;
}
case 82: break;
case 31:
{ yybegin(CODE_LINK_INNER);
return DOC_LINK_TAG;
}
case 83: break;
case 43:
// lookahead expression with fixed base length
zzMarkedPos = zzStartRead + 3;
{ if (isOddItalicBold) {
isOddItalicBold = false;
yypushback(1);
return DOC_ITALIC_TAG;
}
isOddItalicBold = true;
return DOC_BOLD_TAG;
}
case 84: break;
case 22:
{ yybegin(INLINE_DOC_TAG_VALUE);
return DOC_WHITESPACE;
}
case 85: break;
case 21:
{ yybegin(COMMENT_DATA); return DOC_INLINE_TAG_END;
}
case 86: break;
case 4:
{ return DOC_SUPERSCRIPT_TAG;
}
case 87: break;
case 3:
{ return DOC_WHITESPACE;
}
case 88: break;
case 5:
{ return DOC_MONOSPACE_TAG;
}
case 89: break;
case 20:
{ yybegin(DOC_TAG_VALUE); return DOC_TAG_VALUE_RPAREN;
}
case 90: break;
case 45:
// lookahead expression with fixed base length
zzMarkedPos = zzStartRead + 2;
{ yybegin(COMMENT_DATA);
return DOC_HTTP_LINK_TAG;
}
case 91: break;
case 2:
{ yybegin(COMMENT_DATA);
return DOC_COMMENT_DATA;
}
case 92: break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
zzDoEOF();
return null;
}
else {
zzScanError(ZZ_NO_MATCH);
}
}
}
}
}
|
|
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import com.google.android.libraries.social.avatars.ui.AvatarView;
import com.google.android.libraries.social.media.ui.MediaView;
import java.util.ArrayList;
public final class dzn
extends ViewGroup
implements View.OnClickListener, lxj
{
public final loj a;
llv b;
boolean c;
long d;
int e;
String f;
dzo g;
final ArrayList<AvatarView> h;
Button i;
ImageView j;
ipf k;
MediaView l;
int m;
int n;
TextView o;
gik p;
public dzn(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
this.a = loj.a(paramContext);
this.g = new dzo(paramContext);
if (!this.c) {}
for (int i1 = 19;; i1 = 10)
{
Button localButton = lur.a(paramContext, paramAttributeSet, paramInt, i1, this.a.aQ, 0);
localButton.setSingleLine(true);
localButton.setEllipsize(TextUtils.TruncateAt.END);
localButton.setCompoundDrawablePadding(this.a.n);
localButton.setOnClickListener(this);
this.i = localButton;
this.i.setText(getContext().getString(aau.iJ));
this.l = new MediaView(paramContext, paramAttributeSet, paramInt);
this.l.setOnClickListener(this);
this.l.setContentDescription(getResources().getString(aau.dg));
this.h = new ArrayList();
this.j = new ImageView(paramContext, paramAttributeSet, paramInt);
this.j.setImageBitmap(this.a.f);
this.j.setScaleType(ImageView.ScaleType.CENTER);
this.o = new TextView(paramContext, paramAttributeSet, paramInt);
return;
}
}
private final int c()
{
if (this.e > 0) {
return efj.r(getContext(), 2) + this.a.m;
}
return 0;
}
private final int d()
{
return ((git)mbb.a(getContext(), git.class)).c();
}
private void e()
{
for (int i1 = 0; i1 < this.h.size(); i1++) {
((AvatarView)this.h.get(i1)).ap_();
}
if (this.k != null) {
this.l.ap_();
}
}
public final void D_()
{
e();
this.e = 0;
this.g.D_();
this.h.clear();
this.m = 0;
this.n = 0;
this.k = null;
this.d = 0L;
removeAllViews();
this.f = null;
this.p = null;
}
final boolean b()
{
hyi localhyi = (hyi)mbb.a(getContext(), hyi.class);
return (this.b.i) && (localhyi.b(bwb.d, d()));
}
protected final void onAttachedToWindow()
{
super.onAttachedToWindow();
if (lwo.a(this))
{
for (int i1 = 0; i1 < this.h.size(); i1++) {
((AvatarView)this.h.get(i1)).b();
}
if (this.k != null) {
this.l.a(this.k);
}
}
}
public final void onClick(View paramView)
{
Context localContext = getContext();
int i1 = d();
if ((efj.B(localContext)) && (this.p != null) && (this.p.f())) {
this.p.E_();
}
label163:
do
{
return;
if ((paramView instanceof AvatarView))
{
localContext.startActivity(efj.a(localContext, i1, ((AvatarView)paramView).a, null, false));
return;
}
if (paramView == this.i)
{
String str1 = this.b.a;
Intent localIntent2 = efj.a(localContext, "vnd.google.android.hangouts/vnd.google.android.hangout_privileged", i1, true);
String str2;
if (localIntent2 != null)
{
str2 = String.valueOf(str1);
if (str2.length() == 0) {
break label163;
}
}
for (String str3 = "https://plus.google.com/hangouts/_/".concat(str2);; str3 = new String("https://plus.google.com/hangouts/_/"))
{
localIntent2.putExtra("hangout_uri", Uri.parse(str3));
localIntent2.putExtra("hangout_start_source", 29);
efj.b(localContext, localIntent2);
return;
}
}
} while (paramView != this.l);
Uri localUri = Uri.parse(this.f);
Intent localIntent1 = new Intent("android.intent.action.VIEW", localUri);
if (b())
{
localContext.startActivity(localIntent1);
return;
}
localIntent1.addFlags(524288);
if (dtz.a(localContext, "com.google.android.youtube"))
{
localIntent1.setPackage("com.google.android.youtube");
if (getContext().getPackageManager().resolveActivity(localIntent1, 0) == null) {
localIntent1.setPackage(null);
}
}
try
{
localContext.startActivity(localIntent1);
return;
}
catch (ActivityNotFoundException localActivityNotFoundException)
{
localContext.startActivity(new Intent("android.intent.action.VIEW", localUri));
}
}
protected final void onDetachedFromWindow()
{
super.onDetachedFromWindow();
e();
}
protected final void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
int i12;
if (this.b != null)
{
if (this.e <= 0) {
break label438;
}
i12 = ((AvatarView)this.h.get(0)).c;
int i13 = paramInt1 + this.a.z;
int i14 = this.a.m;
int i15 = 0;
int i16 = i13;
while (i15 < this.e)
{
AvatarView localAvatarView = (AvatarView)this.h.get(i15);
localAvatarView.layout(i16, i14, i16 + localAvatarView.getMeasuredWidth(), i14 + i12);
i16 += localAvatarView.getWidth() + this.a.G;
i15++;
}
}
label438:
for (int i1 = i12 + this.a.m;; i1 = 0)
{
if (this.c) {
i1 = this.l.getMeasuredHeight() + this.a.m;
}
this.g.layout(paramInt1, i1, paramInt3, paramInt4);
if (this.c)
{
int i3 = this.l.getMeasuredWidth();
int i4 = this.l.getMeasuredHeight();
int i5 = this.j.getMeasuredWidth();
int i6 = i3 / 2 - i5 / 2;
int i7 = i4 / 2 - i5 / 2;
this.j.layout(paramInt1 + i6, i7, i6 + i5, i7 + this.j.getMeasuredHeight());
this.l.layout(paramInt1, 0, paramInt1 + this.l.getMeasuredWidth(), this.l.getMeasuredHeight());
int i8 = this.b.g;
int i9 = 0;
if (i8 == 0) {
i9 = 1;
}
if ((i9 != 0) || (b()))
{
int i10 = paramInt3 - this.o.getMeasuredWidth() - this.a.z;
int i11 = this.a.z;
this.o.layout(i10, i11, i10 + this.o.getMeasuredWidth(), i11 + this.o.getMeasuredHeight());
}
return;
}
int i2 = c() + this.g.getMeasuredHeight();
this.i.layout(paramInt1 + this.a.z, i2, paramInt1 + this.a.z + this.i.getMeasuredWidth(), i2 + this.i.getMeasuredHeight());
return;
}
}
protected final void onMeasure(int paramInt1, int paramInt2)
{
int i1 = View.MeasureSpec.getSize(paramInt1);
if (this.b != null)
{
int i4;
if (this.c)
{
this.j.measure(View.MeasureSpec.makeMeasureSpec(i1, -2147483648), View.MeasureSpec.makeMeasureSpec(0, 0));
this.l.measure(View.MeasureSpec.makeMeasureSpec(this.n, 1073741824), View.MeasureSpec.makeMeasureSpec(this.m, 1073741824));
if (this.b.g == 0)
{
i4 = 1;
if ((i4 != 0) || (b())) {
this.o.measure(View.MeasureSpec.makeMeasureSpec(this.n, -2147483648), View.MeasureSpec.makeMeasureSpec(this.n, -2147483648));
}
}
}
for (;;)
{
this.g.measure(View.MeasureSpec.makeMeasureSpec(i1, -2147483648), View.MeasureSpec.makeMeasureSpec(0, -2147483648));
for (int i3 = 0; i3 < this.e; i3++) {
((AvatarView)this.h.get(i3)).measure(View.MeasureSpec.makeMeasureSpec(i1, -2147483648), View.MeasureSpec.makeMeasureSpec(efj.i(getContext()), -2147483648));
}
i4 = 0;
break;
this.i.measure(View.MeasureSpec.makeMeasureSpec(i1, -2147483648), View.MeasureSpec.makeMeasureSpec(0, 0));
}
}
int i2 = this.a.m + c() + this.g.getMeasuredHeight();
if ((this.c) && (this.l.getParent() == this)) {
i2 += this.l.getMeasuredHeight();
}
if ((TextUtils.isEmpty(this.b.e)) && (this.i.getParent() == this)) {
i2 += this.i.getMeasuredHeight();
}
setMeasuredDimension(i1, i2);
}
}
/* Location: F:\apktool\apktool\com.google.android.apps.plus\classes-dex2jar.jar
* Qualified Name: dzn
* JD-Core Version: 0.7.0.1
*/
|
|
/*
* Copyright (C) 2013 Dr. John Lindsay <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package plugins;
import java.io.*;
import whitebox.geospatialfiles.ShapeFile;
import whitebox.geospatialfiles.shapefile.*;
import whitebox.interfaces.WhiteboxPlugin;
import whitebox.interfaces.WhiteboxPluginHost;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.gml2.*;
import whitebox.interfaces.InteropPlugin;
/**
* This tool can be used to export a vector shapefile file to an Geography Markup Language (GML) file.
*
* @author Dr. John Lindsay email: [email protected]
*/
public class ExportGML implements WhiteboxPlugin, InteropPlugin {
private WhiteboxPluginHost myHost = null;
private String[] args;
/**
* Used to retrieve the plugin tool's name. This is a short, unique name
* containing no spaces.
*
* @return String containing plugin name.
*/
@Override
public String getName() {
return "ExportGML";
}
/**
* Used to retrieve the plugin tool's descriptive name. This can be a longer
* name (containing spaces) and is used in the interface to list the tool.
*
* @return String containing the plugin descriptive name.
*/
@Override
public String getDescriptiveName() {
return "Export Geography Markup Language (GML)";
}
/**
* Used to retrieve a short description of what the plugin tool does.
*
* @return String containing the plugin's description.
*/
@Override
public String getToolDescription() {
return "Exports a vector to a geography markup language (GML) format.";
}
/**
* Used to identify which toolboxes this plugin tool should be listed in.
*
* @return Array of Strings.
*/
@Override
public String[] getToolbox() {
String[] ret = {"IOTools"};
return ret;
}
/**
* Sets the WhiteboxPluginHost to which the plugin tool is tied. This is the
* class that the plugin will send all feedback messages, progress updates,
* and return objects.
*
* @param host The WhiteboxPluginHost that called the plugin tool.
*/
@Override
public void setPluginHost(WhiteboxPluginHost host) {
myHost = host;
}
/**
* Used to communicate feedback pop-up messages between a plugin tool and
* the main Whitebox user-interface.
*
* @param feedback String containing the text to display.
*/
private void showFeedback(String message) {
if (myHost != null) {
myHost.showFeedback(message);
} else {
System.out.println(message);
}
}
/**
* Used to communicate a return object from a plugin tool to the main
* Whitebox user-interface.
*
* @return Object, such as an output WhiteboxRaster.
*/
private void returnData(Object ret) {
if (myHost != null) {
myHost.returnData(ret);
}
}
private int previousProgress = 0;
private String previousProgressLabel = "";
/**
* Used to communicate a progress update between a plugin tool and the main
* Whitebox user interface.
*
* @param progressLabel A String to use for the progress label.
* @param progress Float containing the progress value (between 0 and 100).
*/
private void updateProgress(String progressLabel, int progress) {
if (myHost != null && ((progress != previousProgress)
|| (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel, progress);
}
previousProgress = progress;
previousProgressLabel = progressLabel;
}
/**
* Used to communicate a progress update between a plugin tool and the main
* Whitebox user interface.
*
* @param progress Float containing the progress value (between 0 and 100).
*/
private void updateProgress(int progress) {
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress = progress;
}
/**
* Sets the arguments (parameters) used by the plugin.
*
* @param args An array of string arguments.
*/
@Override
public void setArgs(String[] args) {
this.args = args.clone();
}
private boolean cancelOp = false;
/**
* Used to communicate a cancel operation from the Whitebox GUI.
*
* @param cancel Set to true if the plugin should be canceled.
*/
@Override
public void setCancelOp(boolean cancel) {
cancelOp = cancel;
}
private void cancelOperation() {
showFeedback("Operation cancelled.");
updateProgress("Progress: ", 0);
}
private boolean amIActive = false;
/**
* Used by the Whitebox GUI to tell if this plugin is still running.
*
* @return a boolean describing whether or not the plugin is actively being
* used.
*/
@Override
public boolean isActive() {
return amIActive;
}
/**
* Used to execute this plugin tool.
*/
@Override
public void run() {
amIActive = true;
String ouptutFile = null;
String shapefileName = null;
int i = 0;
int row, col, rows, cols;
InputStream inStream = null;
OutputStream outStream = null;
int progress = 0;
Geometry[] JTSGeometries;
GMLWriter gmlWriter = new GMLWriter();
String str1 = null;
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
String inputFilesString = args[0];
// check to see that the inputHeader and outputHeader are not null.
if (inputFilesString.isEmpty()) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
String[] imageFiles = inputFilesString.split(";");
int numFiles = imageFiles.length;
try {
for (i = 0; i < numFiles; i++) {
if (numFiles > 1) {
progress = (int) (100f * i / (numFiles - 1));
updateProgress("Loop " + (i + 1) + " of " + numFiles + ":", progress);
}
shapefileName = imageFiles[i];
if (!((new File(shapefileName)).exists())) {
showFeedback("Vector file does not exist.");
break;
}
ShapeFile shapefile = new ShapeFile(shapefileName);
// arc file name.
ouptutFile = shapefileName.replace(".shp", ".gml");
// see if it exists, and if so, delete it.
(new File(ouptutFile)).delete();
fw = new FileWriter(ouptutFile, false);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw, true);
progress = 0;
int n = 0;
int onePercentOfRecs = shapefile.getNumberOfRecords() / 100;
for (ShapeFileRecord record : shapefile.records) {
if (record.getShapeType() != ShapeType.NULLSHAPE) {
JTSGeometries = record.getGeometry().getJTSGeometries();
for (int a = 0; a < JTSGeometries.length; a++) {
str1 = gmlWriter.write(JTSGeometries[a]);
out.println(str1);
}
}
if (cancelOp) {
cancelOperation();
return;
}
n++;
if (n == onePercentOfRecs) {
n = 0;
progress++;
updateProgress("Exporting shapefile data:", progress);
}
}
}
showFeedback("Operation complete!");
} catch (OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
} catch (Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(), e);
} finally {
if (out != null || bw != null) {
out.flush();
out.close();
}
updateProgress("Progress: ", 0);
// tells the main application that this process is completed.
amIActive = false;
myHost.pluginComplete();
}
}
/**
* Used to retrieve the necessary extensions.
* @return String containing the extensions.
*/
@Override
public String[] getExtensions() {
return new String[]{ "txt" };
}
/**
* Used to retrieve the file type name.
* @return String containing the file type name.
*/
@Override
public String getFileTypeName() {
return "ArcGIS ASCII Grid";
}
/**
* Used to check if the file is raster format.
* @return Boolean true if file is raster format.
*/
@Override
public boolean isRasterFormat() {
return true;
}
/**
* Used to retrieve the interoperable plugin type.
* @return
*/
@Override
public InteropPlugin.InteropPluginType getInteropPluginType() {
return InteropPlugin.InteropPluginType.exportPlugin;
}
}
|
|
/*
* Copyright (c) 2021 VMware, Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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 reactor.netty.http.server;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.FileUpload;
import io.netty.handler.codec.http.multipart.HttpData;
import io.netty.handler.codec.http.multipart.HttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder;
import io.netty.handler.codec.http.multipart.HttpPostStandardRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.InterfaceHttpPostRequestDecoder;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.util.annotation.Nullable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* A configuration builder to fine tune the HTTP form decoder.
*
* @author Violeta Georgieva
* @since 1.0.11
*/
public final class HttpServerFormDecoderProvider {
public interface Builder {
/**
* Sets the directory where to store disk {@link Attribute}/{@link FileUpload}.
* Default to generated temp directory.
*
* @param baseDirectory directory where to store disk {@link Attribute}/{@link FileUpload}
* @return {@code this}
*/
Builder baseDirectory(Path baseDirectory);
/**
* Set the {@link Charset} for {@link Attribute}/{@link FileUpload}. Default to {@link StandardCharsets#UTF_8}.
*
* @param charset the charset for {@link Attribute}/{@link FileUpload}
* @return {@code this}
*/
Builder charset(Charset charset);
/**
* Sets the maximum in-memory size per {@link Attribute}/{@link FileUpload} i.e. the data is written
* on disk if the size is greater than {@code maxInMemorySize}, else it is in memory.
* Default to {@link DefaultHttpDataFactory#MINSIZE}.
* <p>Note:
* <ul>
* <li>If set to {@code -1} the entire contents is stored in memory</li>
* <li>If set to {@code 0} the entire contents is stored on disk</li>
* </ul>
*
* @param maxInMemorySize the maximum in-memory size
* @return {@code this}
*/
Builder maxInMemorySize(long maxInMemorySize);
/**
* Set the maximum size per {@link Attribute}/{@link FileUpload}. When the limit is reached, an exception is raised.
* Default to {@link DefaultHttpDataFactory#MAXSIZE} - unlimited.
* <p>Note: If set to {@code -1} this means no limitation.
*
* @param maxSize the maximum size allowed for an individual attribute/fileUpload
* @return {@code this}
*/
Builder maxSize(long maxSize);
/**
* Sets the scheduler to be used for offloading disk operations in the decoding phase.
* Default to {@link Schedulers#boundedElastic()}
*
* @param scheduler the scheduler to be used for offloading disk operations in the decoding phase
* @return {@code this}
*/
Builder scheduler(Scheduler scheduler);
/**
* When set to {@code true}, the data is streamed directly from the parsed input buffer stream,
* which means it is not stored either in memory or file.
* When {@code false}, parts are backed by in-memory and/or file storage. Default to {@code false}.
* <p><strong>NOTE</strong> that with streaming enabled, the provided {@link Attribute}/{@link FileUpload}
* might not be in a complete state i.e. {@link HttpData#isCompleted()} has to be checked.
* <p>Also note that enabling this property effectively ignores
* {@link #maxInMemorySize(long)},
* {@link #baseDirectory(Path)}, and
* {@link #scheduler(Scheduler)}.
*/
Builder streaming(boolean enable);
}
final Path baseDirectory;
final Charset charset;
final long maxInMemorySize;
final long maxSize;
final Scheduler scheduler;
final boolean streaming;
private volatile Mono<Path> defaultTempDirectory = createDefaultTempDirectory();
HttpServerFormDecoderProvider(Build build) {
this.baseDirectory = build.baseDirectory;
this.charset = build.charset;
this.maxInMemorySize = !build.streaming ? build.maxInMemorySize : -1;
this.maxSize = build.maxSize;
this.scheduler = build.scheduler;
this.streaming = build.streaming;
}
/**
* Returns the configured directory where to store disk {@link Attribute}/{@link FileUpload}.
*
* @return the configured directory where to store disk {@link Attribute}/{@link FileUpload}
* @see Builder#baseDirectory(Path)
*/
@Nullable
public Path baseDirectory() {
return baseDirectory;
}
/**
* Returns the configured charset for {@link Attribute}/{@link FileUpload}.
*
* @return the configured charset for {@link Attribute}/{@link FileUpload}
* @see Builder#charset(Charset)
*/
public Charset charset() {
return charset;
}
/**
* Returns the configured maximum size after which an {@link Attribute}/{@link FileUpload} starts being stored on disk rather than in memory.
*
* @return the configured maximum size after which an {@link Attribute}/{@link FileUpload} starts being stored on disk rather than in memory
* @see Builder#maxInMemorySize(long)
*/
public long maxInMemorySize() {
return maxInMemorySize;
}
/**
* Returns the configured maximum allowed size of individual {@link Attribute}/{@link FileUpload}.
*
* @return the configured maximum allowed size of individual {@link Attribute}/{@link FileUpload}
* @see Builder#maxSize(long)
*/
public long maxSize() {
return maxSize;
}
/**
* Returns the configured scheduler to be used for offloading disk operations in the decoding phase.
*
* @return the configured scheduler to be used for offloading disk operations in the decoding phase
* @see Builder#scheduler(Scheduler)
*/
public Scheduler scheduler() {
return scheduler;
}
/**
* Returns whether the streaming mode is enabled.
*
* @return whether the streaming mode is enabled
* @see Builder#streaming(boolean)
*/
public boolean streaming() {
return streaming;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof HttpServerFormDecoderProvider)) {
return false;
}
HttpServerFormDecoderProvider that = (HttpServerFormDecoderProvider) o;
return maxInMemorySize == that.maxInMemorySize &&
maxSize == that.maxSize &&
streaming == that.streaming &&
Objects.equals(baseDirectory, that.baseDirectory) &&
charset.equals(that.charset) &&
scheduler.equals(that.scheduler);
}
@Override
public int hashCode() {
return Objects.hash(baseDirectory, charset, maxInMemorySize, maxSize, scheduler, streaming);
}
Mono<Path> createDefaultTempDirectory() {
return Mono.fromCallable(() -> Files.createTempDirectory(DEFAULT_TEMP_DIRECTORY_PREFIX))
.cache();
}
Mono<Path> defaultTempDirectory() {
return defaultTempDirectory
.flatMap(dir -> {
if (!Files.exists(dir)) {
Mono<Path> newDirectory = createDefaultTempDirectory();
defaultTempDirectory = newDirectory;
return newDirectory;
}
else {
return Mono.just(dir);
}
})
.subscribeOn(scheduler);
}
Mono<ReactorNettyHttpPostRequestDecoder> newHttpPostRequestDecoder(HttpRequest request, boolean isMultipart) {
if (maxInMemorySize > -1) {
Mono<Path> directoryMono;
if (baseDirectory == null) {
directoryMono = defaultTempDirectory();
}
else {
directoryMono = Mono.just(baseDirectory);
}
return directoryMono.map(directory -> createNewHttpPostRequestDecoder(request, isMultipart, directory));
}
else {
return Mono.just(createNewHttpPostRequestDecoder(request, isMultipart, null));
}
}
ReactorNettyHttpPostRequestDecoder createNewHttpPostRequestDecoder(HttpRequest request, boolean isMultipart,
@Nullable Path baseDirectory) {
DefaultHttpDataFactory factory = maxInMemorySize > 0 ?
new DefaultHttpDataFactory(maxInMemorySize, charset) :
new DefaultHttpDataFactory(maxInMemorySize == 0, charset);
factory.setMaxLimit(maxSize);
if (baseDirectory != null) {
factory.setBaseDir(baseDirectory.toFile().getAbsolutePath());
}
return isMultipart ?
new ReactorNettyHttpPostMultipartRequestDecoder(factory, request) :
new ReactorNettyHttpPostStandardRequestDecoder(factory, request);
}
static final HttpServerFormDecoderProvider DEFAULT_FORM_DECODER_SPEC = new HttpServerFormDecoderProvider.Build().build();
static final String DEFAULT_TEMP_DIRECTORY_PREFIX = "RN_form_";
interface ReactorNettyHttpPostRequestDecoder extends InterfaceHttpPostRequestDecoder {
void cleanCurrentHttpData(boolean onlyCompleted);
List<HttpData> currentHttpData(boolean onlyCompleted);
}
static final class Build implements Builder {
static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
static final long DEFAULT_MAX_IN_MEMORY_SIZE = DefaultHttpDataFactory.MINSIZE;
static final long DEFAULT_MAX_SIZE = DefaultHttpDataFactory.MAXSIZE;
static final Scheduler DEFAULT_SCHEDULER = Schedulers.boundedElastic();
static final boolean DEFAULT_STREAMING = false;
Path baseDirectory;
Charset charset = DEFAULT_CHARSET;
long maxInMemorySize = DEFAULT_MAX_IN_MEMORY_SIZE;
long maxSize = DEFAULT_MAX_SIZE;
Scheduler scheduler = DEFAULT_SCHEDULER;
boolean streaming = DEFAULT_STREAMING;
@Override
public Builder baseDirectory(Path baseDirectory) {
this.baseDirectory = Objects.requireNonNull(baseDirectory, "baseDirectory");
return this;
}
@Override
public Builder charset(Charset charset) {
this.charset = Objects.requireNonNull(charset, "charset");
return this;
}
@Override
public Builder maxInMemorySize(long maxInMemorySize) {
if (maxInMemorySize < -1) {
throw new IllegalArgumentException("Maximum in-memory size must be greater or equal to -1");
}
this.maxInMemorySize = maxInMemorySize;
return this;
}
@Override
public Builder maxSize(long maxSize) {
if (maxSize < -1) {
throw new IllegalArgumentException("Maximum size must be be greater or equal to -1");
}
this.maxSize = maxSize;
return this;
}
@Override
public Builder scheduler(Scheduler scheduler) {
this.scheduler = Objects.requireNonNull(scheduler, "scheduler");
return this;
}
@Override
public Builder streaming(boolean enable) {
this.streaming = enable;
return this;
}
HttpServerFormDecoderProvider build() {
return new HttpServerFormDecoderProvider(this);
}
}
static final class ReactorNettyHttpPostMultipartRequestDecoder extends HttpPostMultipartRequestDecoder
implements ReactorNettyHttpPostRequestDecoder {
/**
* Current {@link HttpData} from the body (only the completed {@link HttpData}).
*/
final List<HttpData> currentCompletedHttpData = new ArrayList<>();
ReactorNettyHttpPostMultipartRequestDecoder(HttpDataFactory factory, HttpRequest request) {
super(factory, request);
}
@Override
protected void addHttpData(InterfaceHttpData data) {
if (data instanceof HttpData) {
currentCompletedHttpData.add((HttpData) data);
}
}
@Override
public void cleanCurrentHttpData(boolean onlyCompleted) {
for (HttpData data : currentCompletedHttpData) {
removeHttpDataFromClean(data);
data.release();
}
currentCompletedHttpData.clear();
if (!onlyCompleted) {
InterfaceHttpData partial = currentPartialHttpData();
if (partial instanceof HttpData) {
((HttpData) partial).delete();
}
}
}
@Override
public List<HttpData> currentHttpData(boolean onlyCompleted) {
if (!onlyCompleted) {
InterfaceHttpData partial = currentPartialHttpData();
if (partial instanceof HttpData) {
currentCompletedHttpData.add(((HttpData) partial).retainedDuplicate());
}
}
return currentCompletedHttpData;
}
@Override
public void destroy() {
super.destroy();
InterfaceHttpData partial = currentPartialHttpData();
if (partial != null) {
partial.release();
}
}
}
static final class ReactorNettyHttpPostStandardRequestDecoder extends HttpPostStandardRequestDecoder
implements ReactorNettyHttpPostRequestDecoder {
/**
* Current {@link HttpData} from the body (only the completed {@link HttpData}).
*/
final List<HttpData> currentCompletedHttpData = new ArrayList<>();
ReactorNettyHttpPostStandardRequestDecoder(HttpDataFactory factory, HttpRequest request) {
super(factory, request);
}
@Override
protected void addHttpData(InterfaceHttpData data) {
if (data instanceof HttpData) {
currentCompletedHttpData.add((HttpData) data);
}
}
@Override
public void cleanCurrentHttpData(boolean onlyCompleted) {
for (HttpData data : currentCompletedHttpData) {
removeHttpDataFromClean(data);
data.release();
}
currentCompletedHttpData.clear();
if (!onlyCompleted) {
InterfaceHttpData partial = currentPartialHttpData();
if (partial instanceof HttpData) {
((HttpData) partial).delete();
}
}
}
@Override
public List<HttpData> currentHttpData(boolean onlyCompleted) {
if (!onlyCompleted) {
InterfaceHttpData partial = currentPartialHttpData();
if (partial instanceof HttpData) {
currentCompletedHttpData.add(((HttpData) partial).retainedDuplicate());
}
}
return currentCompletedHttpData;
}
@Override
public void destroy() {
super.destroy();
InterfaceHttpData partial = currentPartialHttpData();
if (partial != null) {
partial.release();
}
}
}
}
|
|
package com.nukesz.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import java.awt.*;
public class GameScreen extends ScreenAdapter {
private static final float WORLD_WIDTH = 640;
private static final float WORLD_HEIGHT = 480;
private static final String GAME_OVER_TEXT = "Game Over... Tap space to restart!";
private static final int POINTS_PER_APPLE = 10;
private static final int RIGHT = 0;
private static final int LEFT = 1;
private static final int UP = 2;
private static final int DOWN = 3;
private int snakeDirection = UP;
private Viewport viewport;
private Camera camera;
private static final float MOVE_TIME = 0.2F;
private static final int SNAKE_MOVEMENT = 32;
private static final int GRID_CELL = 32;
private float timer = MOVE_TIME;
private int snakeX = 0;
private int snakeY = 0;
private SpriteBatch batch;
private ShapeRenderer shapeRenderer;
private BitmapFont bitmapFont;
private GlyphLayout layout = new GlyphLayout();
private Texture snakeHead;
private Texture snakeBody;
private Texture apple;
private boolean appleAvailable = false;
private int appleX;
private int appleY;
private Array<BodyPart> bodyParts = new Array<BodyPart>();
private int snakeXBeforeUpdate;
private int snakeYBeforeUpdate;
private boolean directionSet = false;
private State state = State.PLAYING;
private int score = 0;
@Override
public void show() {
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2, 0);
//camera.update();
viewport = new FitViewport(WORLD_WIDTH, WORLD_HEIGHT, camera);
viewport.apply();
shapeRenderer = new ShapeRenderer();
batch = new SpriteBatch();
bitmapFont = new BitmapFont();
snakeHead = new Texture(Gdx.files.internal("snakehead_resized.png"));
snakeBody = new Texture(Gdx.files.internal("snakebody.png"));
apple = new Texture(Gdx.files.internal("apple.png"));
}
@Override
public void resize(int width, int height){
viewport.update(width, height);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
}
@Override
public void render(float delta) {
switch (state) {
case PLAYING:
queryInput();
updateSnake(delta);
checkAppleCollision();
checkAndPlaceApple();
break;
case GAME_OVER:
checkForRestart();
break;
}
clearScreen();
//drawGrid();
draw();
}
private void updateSnake(float delta) {
timer -= delta;
if (timer <= 0) {
timer = MOVE_TIME;
moveSnake();
checkForOutOfBounds();
updateBodyPartsPosition();
checkSnakeBodyCollision();
directionSet = false;
}
}
private void drawGrid() {
shapeRenderer.setProjectionMatrix(camera.projection);
shapeRenderer.setTransformMatrix(camera.view);
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
for (int x = 0; x < viewport.getWorldWidth(); x += GRID_CELL) {
for (int y = 0; y < viewport.getWorldHeight(); y += GRID_CELL) {
shapeRenderer.rect(x, y, GRID_CELL, GRID_CELL);
}
}
shapeRenderer.end();
}
private void draw() {
batch.setProjectionMatrix(camera.projection);
batch.setTransformMatrix(camera.view);
batch.begin();
batch.draw(snakeHead, snakeX, snakeY);
for (BodyPart bodyPart : bodyParts) {
bodyPart.draw(batch, snakeX, snakeY);
}
if (appleAvailable) {
batch.draw(apple, appleX, appleY);
}
if (state == State.GAME_OVER) {
layout.setText(bitmapFont, GAME_OVER_TEXT);
bitmapFont.draw(batch, GAME_OVER_TEXT, (viewport.getWorldWidth() -
layout.width) / 2, (viewport.getWorldHeight() - layout.height) / 2);
}
drawScore();
batch.end();
}
private void clearScreen() {
Gdx.gl.glClearColor(Color.BLACK.getRed(), Color.BLACK.getGreen(), Color.BLACK.getBlue(), Color.BLACK.getAlpha());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
private void checkAppleCollision() {
if (appleAvailable && appleX == snakeX && appleY == snakeY) {
BodyPart bodyPart = new BodyPart(snakeBody);
bodyPart.updateBodyPosition(snakeX, snakeY);
bodyParts.insert(0, bodyPart);
addToScore();
appleAvailable = false;
}
}
private void updateBodyPartsPosition() {
if (bodyParts.size > 0) {
BodyPart bodyPart = bodyParts.removeIndex(0);
bodyPart.updateBodyPosition(snakeXBeforeUpdate, snakeYBeforeUpdate);
bodyParts.add(bodyPart);
}
}
private void checkAndPlaceApple() {
if (!appleAvailable) {
do {
appleX = MathUtils.random((int) viewport.getWorldWidth()
/ SNAKE_MOVEMENT - 1) * SNAKE_MOVEMENT;
appleY = MathUtils.random((int) viewport.getWorldHeight()
/ SNAKE_MOVEMENT - 1) * SNAKE_MOVEMENT;
appleAvailable = true;
} while (appleX == snakeX && appleY == snakeY);
}
}
private void checkForOutOfBounds() {
if (snakeX >= viewport.getWorldWidth()) {
snakeX = 0;
}
if (snakeX < 0) {
snakeX = (int) viewport.getWorldWidth() - SNAKE_MOVEMENT;
}
if (snakeY >= viewport.getWorldHeight()) {
snakeY = 0;
}
if (snakeY < 0) {
snakeY = (int) viewport.getWorldHeight() - SNAKE_MOVEMENT;
}
}
private void moveSnake() {
snakeXBeforeUpdate = snakeX;
snakeYBeforeUpdate = snakeY;
switch (snakeDirection) {
case RIGHT:
snakeX += SNAKE_MOVEMENT;
break;
case LEFT:
snakeX -= SNAKE_MOVEMENT;
break;
case UP:
snakeY += SNAKE_MOVEMENT;
break;
case DOWN:
snakeY -= SNAKE_MOVEMENT;
break;
}
}
private void queryInput() {
boolean lPressed = Gdx.input.isKeyPressed(Input.Keys.LEFT);
boolean rPressed = Gdx.input.isKeyPressed(Input.Keys.RIGHT);
boolean uPressed = Gdx.input.isKeyPressed(Input.Keys.UP);
boolean dPressed = Gdx.input.isKeyPressed(Input.Keys.DOWN);
if (lPressed) updateDirection(LEFT);
if (rPressed) updateDirection(RIGHT);
if (uPressed) updateDirection(UP);
if (dPressed) updateDirection(DOWN);
}
private void updateIfNotOppositeDirection(int newSnakeDirection, int oppositeDirection) {
if (snakeDirection != oppositeDirection || bodyParts.size == 0) {
snakeDirection = newSnakeDirection;
}
}
private void updateDirection(int newSnakeDirection) {
if (!directionSet && snakeDirection != newSnakeDirection) {
directionSet = true;
switch (newSnakeDirection) {
case LEFT:
updateIfNotOppositeDirection(newSnakeDirection, RIGHT);
break;
case RIGHT:
updateIfNotOppositeDirection(newSnakeDirection, LEFT);
break;
case UP:
updateIfNotOppositeDirection(newSnakeDirection, DOWN);
break;
case DOWN:
updateIfNotOppositeDirection(newSnakeDirection, UP);
break;
}
}
}
private void checkSnakeBodyCollision() {
for (BodyPart bodyPart : bodyParts) {
if (bodyPart.x == snakeX && bodyPart.y == snakeY) {
state = State.GAME_OVER;
}
}
}
private void checkForRestart() {
if (Gdx.input.isKeyPressed(Input.Keys.SPACE)) {
doRestart();
}
}
private void doRestart() {
state = State.PLAYING;
bodyParts.clear();
snakeDirection = RIGHT;
directionSet = false;
timer = MOVE_TIME;
snakeX = 0;
snakeY = 0;
snakeXBeforeUpdate = 0;
snakeYBeforeUpdate = 0;
appleAvailable = false;
score = 0;
}
private void addToScore() {
score += POINTS_PER_APPLE;
}
private void drawScore() {
if (state == State.PLAYING) {
String scoreAsString = Integer.toString(score);
layout.setText(bitmapFont, scoreAsString);
bitmapFont.draw(batch, scoreAsString, (viewport.getWorldWidth() - layout.width) / 2, (4 * viewport.getWorldHeight() / 5) -
layout.height / 2);
}
}
}
|
|
/*
* Copyright 2016 RedRoma, 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 tech.redroma.google.places;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sir.wellington.alchemy.collections.lists.Lists;
import tech.redroma.google.places.data.Location;
import tech.redroma.google.places.data.Photo;
import tech.redroma.google.places.data.Place;
import tech.redroma.google.places.data.PlaceDetails;
import tech.redroma.google.places.requests.GetPhotoRequest;
import tech.redroma.google.places.requests.GetPlaceDetailsRequest;
import tech.redroma.google.places.requests.NearbySearchRequest;
import tech.redroma.google.places.responses.GetPlaceDetailsResponse;
import tech.redroma.google.places.responses.NearbySearchResponse;
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner;
import static com.google.common.base.Strings.isNullOrEmpty;
/**
*
* @author SirWellington
*/
@RunWith(AlchemyTestRunner.class)
public class GooglePlacesAPIIT
{
private final Logger LOG = LoggerFactory.getLogger(this.getClass());
private final String apiKey = "";
private Location location;
private Place place;
private Photo photo;
private GooglePlacesAPI instance;
@Before
public void setUp() throws Exception
{
if (!isNullOrEmpty(apiKey))
{
instance = GooglePlacesAPI.create(apiKey);
}
location = Location.of(40.814697, -73.908013);
}
@Test
public void testSearchNearbyPlaces()
{
if (instance == null)
{
return;
}
NearbySearchRequest request = NearbySearchRequest.newBuilder()
.withKeyword("grocery")
.withRadiusInMeters(5_000)
.withLocation(location)
.build();
NearbySearchResponse result = instance.searchNearbyPlaces(request);
LOG.info("Found [{}] results for request: [{}]", result, request);
place = Lists.oneOf(result.getResults());
photo = loadAPhotoFrom(result.getResults());
}
@Test
public void testSimpleSearchNearbyPlaces()
{
if (instance == null)
{
return;
}
NearbySearchRequest request = NearbySearchRequest.newBuilder()
.withKeyword("library")
.withRadiusInMeters(5_000)
.withLocation(location)
.build();
List<Place> results = instance.simpleSearchNearbyPlaces(request);
LOG.info("Found {} results for request: [{}]", results.size(), request);
place = Lists.oneOf(results);
photo = loadAPhotoFrom(results);
}
@Test
public void testGetPlaceDetails()
{
if (instance == null || place == null)
{
return;
}
GetPlaceDetailsRequest request = GetPlaceDetailsRequest.newBuilder()
.withPlaceID(place.placeId)
.build();
GetPlaceDetailsResponse result = instance.getPlaceDetails(request);
LOG.info("Got place details: [{}]", result);
}
@Test
public void testSimpleGetPlaceDetails()
{
if (instance == null || place == null)
{
return;
}
PlaceDetails details = instance.simpleGetPlaceDetails(place);
LOG.info("Retrieved details for place: [{}]", details);
}
@Test
public void testGetPhoto()
{
if (instance == null)
{
return;
}
NearbySearchRequest searchRequest = NearbySearchRequest.newBuilder()
.withKeyword("library")
.withRadiusInMeters(5_000)
.withLocation(location)
.build();
List<Place> results = instance.simpleSearchNearbyPlaces(searchRequest);
photo = loadAPhotoFrom(results);
if (Objects.isNull(photo))
{
return;
}
GetPhotoRequest request = GetPhotoRequest.newBuilder()
.withPhotoReference(photo.photoReference)
.withMaxHeight(GetPhotoRequest.Builder.MAX_HEIGHT)
.build();
URL result = instance.getPhoto(request);
LOG.info("Got photo URL [{}] for request: [{}]", result, request);
}
@Test
public void testDownloadPhoto()
{
if (instance == null)
{
return;
}
NearbySearchRequest searchRequest = NearbySearchRequest.newBuilder()
.withKeyword("library")
.withRadiusInMeters(5_000)
.withLocation(location)
.build();
List<Place> results = instance.simpleSearchNearbyPlaces(searchRequest);
photo = loadAPhotoFrom(results);
if (Objects.isNull(photo))
{
return;
}
byte[] binary = instance.downloadPhoto(photo);
LOG.info("Downloaded photo [{}] with {} bytes", photo, binary.length);
}
private Photo loadAPhotoFrom(List<Place> results)
{
Optional<Photo> optionalPhoto = results.stream()
.filter(Place::hasPhotos)
.limit(1)
.flatMap(place -> place.photos.stream())
.filter(Objects::nonNull)
.findAny();
return optionalPhoto.orElse(null);
}
}
|
|
/* Copyright (C) 2013-2014 Computer Sciences Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
/*
* Copyright (c) 2008-2014 MongoDB, 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.
*/
// ObjectId.java
package org.bson.types;
import java.net.NetworkInterface;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.Enumeration;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A globally unique identifier for objects.
* <p>Consists of 12 bytes, divided as follows:
* <blockquote><pre>
* <table border="1">
* <tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td>
* <td>7</td><td>8</td><td>9</td><td>10</td><td>11</td></tr>
* <tr><td colspan="4">time</td><td colspan="3">machine</td>
* <td colspan="2">pid</td><td colspan="3">inc</td></tr>
* </table>
* </pre></blockquote>
*
* @dochub objectids
*/
public class ObjectId implements Comparable<ObjectId> , java.io.Serializable {
private static final long serialVersionUID = -4415279469780082174L;
static final Logger LOGGER = Logger.getLogger( "org.bson.ObjectId" );
/** Gets a new object id.
* @return the new id
*/
public static ObjectId get(){
return new ObjectId();
}
/**
* Creates an ObjectId using time, machine and inc values. The Java driver has done it this way for a long time, but it
* does not match the <a href="http://docs.mongodb.org/manual/reference/object-id/">ObjectId specification</a>,
* which requires four values, not three. The next major release of the Java driver will conform to this specification,
* but will still need to support clients that are relying on the current behavior. To that end,
* the constructors that takes these three arguments are now deprecated in favor of this more explicit factory method,
* and in the next major release those constructors will be removed.
* <p>
* NOTE: This will not break any application that use ObjectIds. The 12-byte representation will be round-trippable from old to new
* driver releases.
*
* </p>
*
* @param time time in seconds
* @param machine machine ID
* @param inc incremental value
* @see org.bson.types.ObjectId#ObjectId(int, int, int)
* @since 2.12.0
*/
public static ObjectId createFromLegacyFormat(final int time, final int machine, final int inc) {
return new ObjectId(time, machine, inc);
}
/** Checks if a string could be an <code>ObjectId</code>.
* @return whether the string could be an object id
*/
public static boolean isValid( String s ){
if ( s == null )
return false;
final int len = s.length();
if ( len != 24 )
return false;
for ( int i=0; i<len; i++ ){
char c = s.charAt( i );
if ( c >= '0' && c <= '9' )
continue;
if ( c >= 'a' && c <= 'f' )
continue;
if ( c >= 'A' && c <= 'F' )
continue;
return false;
}
return true;
}
/** Turn an object into an <code>ObjectId</code>, if possible.
* Strings will be converted into <code>ObjectId</code>s, if possible, and <code>ObjectId</code>s will
* be cast and returned. Passing in <code>null</code> returns <code>null</code>.
* @param o the object to convert
* @return an <code>ObjectId</code> if it can be massaged, null otherwise
*
* @deprecated This method is NOT a part of public API and will be dropped in 3.x versions.
*/
@Deprecated
public static ObjectId massageToObjectId( Object o ){
if ( o == null )
return null;
if ( o instanceof ObjectId )
return (ObjectId)o;
if ( o instanceof String ){
String s = o.toString();
if ( isValid( s ) )
return new ObjectId( s );
}
return null;
}
public ObjectId( Date time ){
this(time, _genmachine, _nextInc.getAndIncrement());
}
public ObjectId( Date time , int inc ){
this( time , _genmachine , inc );
}
/**
* Constructs an ObjectId using time, machine and inc values. The Java driver has done it this way for a long time, but it
* does not match the <a href="http://docs.mongodb.org/manual/reference/object-id/">ObjectId specification</a>,
* which requires four values, not three. The next major release of the Java driver will conform to this specification,
* but will still need to support clients that are relying on the current behavior. To that end,
* this constructor is now deprecated in favor of the more explicit factory method ObjectId#createFromLegacyFormat(int, int, int)},
* and in the next major release this constructor will be removed.
*
* @see ObjectId#createFromLegacyFormat(int, int, int)
* @deprecated {@code ObjectId}'s constructed this way do not conform to
* the <a href="http://docs.mongodb.org/manual/reference/object-id/">ObjectId specification</a>.
* Please use {@link org.bson.types.ObjectId#ObjectId(byte[])} or
* {@link ObjectId#createFromLegacyFormat(int, int, int)} instead.
*/
@Deprecated
public ObjectId( Date time , int machine , int inc ){
_time = (int)(time.getTime() / 1000);
_machine = machine;
_inc = inc;
_new = false;
}
/** Creates a new instance from a string.
* @param s the string to convert
* @throws IllegalArgumentException if the string is not a valid id
*/
public ObjectId( String s ){
this( s , false );
}
/**
* Constructs a new instance of {@code ObjectId} from a string.
* @param s the string representation of ObjectId. Can contains only [0-9]|[a-f]|[A-F] characters.
* @param babble if {@code true} - convert to 'babble' objectId format
*
* @deprecated 'babble' format is deprecated. Please use {@link #ObjectId(String)} instead.
*/
@Deprecated
public ObjectId( String s , boolean babble ){
if ( ! isValid( s ) )
throw new IllegalArgumentException( "invalid ObjectId [" + s + "]" );
if ( babble )
s = babbleToMongod( s );
byte b[] = new byte[12];
for ( int i=0; i<b.length; i++ ){
b[i] = (byte)Integer.parseInt( s.substring( i*2 , i*2 + 2) , 16 );
}
ByteBuffer bb = ByteBuffer.wrap( b );
_time = bb.getInt();
_machine = bb.getInt();
_inc = bb.getInt();
_new = false;
}
/**
* Constructs an ObjectId given its 12-byte binary representation.
* @param b a byte array of length 12
*/
public ObjectId( byte[] b ){
if ( b.length != 12 )
throw new IllegalArgumentException( "need 12 bytes" );
ByteBuffer bb = ByteBuffer.wrap( b );
_time = bb.getInt();
_machine = bb.getInt();
_inc = bb.getInt();
_new = false;
}
/**
* Constructs an ObjectId using time, machine and inc values. The Java driver has done it this way for a long time, but it
* does not match the <a href="http://docs.mongodb.org/manual/reference/object-id/">ObjectId specification</a>,
* which requires four values, not three. The next major release of the Java driver will conform to this specification,
* but we will still need to support clients that are relying on the current behavior. To that end,
* this constructor is now deprecated in favor of the more explicit factory method ObjectId#createFromLegacyFormat(int, int, int)},
* and in the next major release this constructor will be removed.
*
* @param time time in seconds
* @param machine machine ID
* @param inc incremental value
* @see ObjectId#createFromLegacyFormat(int, int, int)
* @deprecated {@code ObjectId}'s constructed this way do not conform to
* the <a href="http://docs.mongodb.org/manual/reference/object-id/">ObjectId specification</a>.
* Please use {@link org.bson.types.ObjectId#ObjectId(byte[])} or
* {@link ObjectId#createFromLegacyFormat(int, int, int)} instead.
*/
@Deprecated
public ObjectId(int time, int machine, int inc) {
_time = time;
_machine = machine;
_inc = inc;
_new = false;
}
/** Create a new object id.
*/
public ObjectId(){
_time = (int) (System.currentTimeMillis() / 1000);
_machine = _genmachine;
_inc = _nextInc.getAndIncrement();
_new = true;
}
public int hashCode(){
int x = _time;
x += ( _machine * 111 );
x += ( _inc * 17 );
return x;
}
public boolean equals( Object o ){
if ( this == o )
return true;
ObjectId other = massageToObjectId( o );
if ( other == null )
return false;
return
_time == other._time &&
_machine == other._machine &&
_inc == other._inc;
}
/**
* @deprecated 'babble' format is deprecated. Please use {@link #toHexString()} instead.
*/
@Deprecated
public String toStringBabble(){
return babbleToMongod( toStringMongod() );
}
/**
* Converts this instance into a 24-byte hexadecimal string representation.
*
* @return a string representation of the ObjectId in hexadecimal format
*/
public String toHexString() {
final StringBuilder buf = new StringBuilder(24);
for (final byte b : toByteArray()) {
buf.append(String.format("%02x", b & 0xff));
}
return buf.toString();
}
/**
* @return a string representation of the ObjectId in hexadecimal format
*
* @deprecated Please use {@link #toHexString()} instead.
*/
@Deprecated
public String toStringMongod(){
byte b[] = toByteArray();
StringBuilder buf = new StringBuilder(24);
for ( int i=0; i<b.length; i++ ){
int x = b[i] & 0xFF;
String s = Integer.toHexString( x );
if ( s.length() == 1 )
buf.append( "0" );
buf.append( s );
}
return buf.toString();
}
public byte[] toByteArray(){
byte b[] = new byte[12];
ByteBuffer bb = ByteBuffer.wrap( b );
// by default BB is big endian like we need
bb.putInt( _time );
bb.putInt( _machine );
bb.putInt( _inc );
return b;
}
static String _pos( String s , int p ){
return s.substring( p * 2 , ( p * 2 ) + 2 );
}
/**
* @deprecated This method is NOT a part of public API and will be dropped in 3.x versions.
*/
@Deprecated
public static String babbleToMongod( String b ){
if ( ! isValid( b ) )
throw new IllegalArgumentException( "invalid object id: " + b );
StringBuilder buf = new StringBuilder( 24 );
for ( int i=7; i>=0; i-- )
buf.append( _pos( b , i ) );
for ( int i=11; i>=8; i-- )
buf.append( _pos( b , i ) );
return buf.toString();
}
public String toString(){
return toStringMongod();
}
int _compareUnsigned( int i , int j ){
long li = 0xFFFFFFFFL;
li = i & li;
long lj = 0xFFFFFFFFL;
lj = j & lj;
long diff = li - lj;
if (diff < Integer.MIN_VALUE)
return Integer.MIN_VALUE;
if (diff > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
return (int) diff;
}
public int compareTo( ObjectId id ){
if ( id == null )
return -1;
int x = _compareUnsigned( _time , id._time );
if ( x != 0 )
return x;
x = _compareUnsigned( _machine , id._machine );
if ( x != 0 )
return x;
return _compareUnsigned( _inc , id._inc );
}
/**
* Gets the timestamp (number of seconds since the Unix epoch).
*
* @return the timestamp
*/
public int getTimestamp() {
return _time;
}
/**
* Gets the timestamp as a {@code Date} instance.
*
* @return the Date
*/
public Date getDate() {
return new Date(_time * 1000L);
}
/**
* Gets the time of this ID, in milliseconds
*
* @deprecated Please use {@link #getDate()} ()} instead.
*/
@Deprecated
public long getTime(){
return _time * 1000L;
}
/**
* Gets the time of this ID, in seconds.
* @deprecated Please use {@link #getTimestamp()} ()} instead.
*/
@Deprecated
public int getTimeSecond() {
return _time;
}
/**
* Gets the counter.
*
* @return the counter
* @deprecated Please use the {@link #toByteArray()} instead.
*/
@Deprecated
public int getInc() {
return _inc;
}
/**
* Gets the timestamp.
*
* @return the timestamp
* @deprecated Please use {@link #getTimestamp()} ()} instead.
*/
@Deprecated
public int _time(){
return _time;
}
/**
* Gets the machine identifier.
*
* @return the machine identifier
* @see #createFromLegacyFormat(int, int, int)
* @deprecated Please use {@code #toByteArray()} instead.
*/
@Deprecated
public int getMachine() {
return _machine;
}
/**
* Gets the machine identifier.
*
* @return the machine identifier
* @see #createFromLegacyFormat(int, int, int)
* @deprecated Please use {@link #toByteArray()} instead.
*/
@Deprecated
public int _machine(){
return _machine;
}
/**
* Gets the counter.
*
* @return the counter
* @see #createFromLegacyFormat(int, int, int)
* @deprecated Please use {@link #toByteArray()} instead.
*/
@Deprecated
public int _inc(){
return _inc;
}
/**
* @deprecated 'new' flag breaks the immutability of the {@code ObjectId} class
* and will be dropped in 3.x versions of the driver
*/
@Deprecated
public boolean isNew() {
return _new;
}
/**
* @deprecated 'new' flag breaks the immutability of the {@code ObjectId} class
* and will be dropped in 3.x versions of the driver
*/
@Deprecated
public void notNew(){
_new = false;
}
/**
* Gets the machine identifier.
*
* @return the machine identifier
* @see #createFromLegacyFormat(int, int, int)
* @deprecated
*/
@Deprecated
public static int getGenMachineId() {
return _genmachine;
}
/**
* Gets the current value of the auto-incrementing counter.
*/
public static int getCurrentCounter() {
return _nextInc.get();
}
/**
* Gets the current value of the auto-incrementing counter.
*
* @deprecated Please use {@link #getCurrentCounter()} instead.
*/
@Deprecated
public static int getCurrentInc() {
return _nextInc.get();
}
final int _time;
final int _machine;
final int _inc;
boolean _new;
/**
* @deprecated This method is NOT a part of public API and will be dropped in 3.x versions.
*/
@Deprecated
public static int _flip( int x ){
int z = 0;
z |= ( ( x << 24 ) & 0xFF000000 );
z |= ( ( x << 8 ) & 0x00FF0000 );
z |= ( ( x >> 8 ) & 0x0000FF00 );
z |= ( ( x >> 24 ) & 0x000000FF );
return z;
}
private static AtomicInteger _nextInc = new AtomicInteger( (new java.util.Random()).nextInt() );
private static final int _genmachine;
static {
try {
// build a 2-byte machine piece based on NICs info
int machinePiece;
{
try {
StringBuilder sb = new StringBuilder();
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while ( e.hasMoreElements() ){
NetworkInterface ni = e.nextElement();
sb.append( ni.toString() );
}
machinePiece = sb.toString().hashCode() << 16;
} catch (Throwable e) {
// exception sometimes happens with IBM JVM, use random
LOGGER.log(Level.WARNING, e.getMessage(), e);
machinePiece = (new Random().nextInt()) << 16;
}
LOGGER.fine( "machine piece post: " + Integer.toHexString( machinePiece ) );
}
// add a 2 byte process piece. It must represent not only the JVM but the class loader.
// Since static var belong to class loader there could be collisions otherwise
final int processPiece;
{
int processId = new java.util.Random().nextInt();
try {
processId = java.lang.management.ManagementFactory.getRuntimeMXBean().getName().hashCode();
}
catch ( Throwable t ){
}
ClassLoader loader = ObjectId.class.getClassLoader();
int loaderId = loader != null ? System.identityHashCode(loader) : 0;
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(processId));
sb.append(Integer.toHexString(loaderId));
processPiece = sb.toString().hashCode() & 0xFFFF;
LOGGER.fine( "process piece: " + Integer.toHexString( processPiece ) );
}
_genmachine = machinePiece | processPiece;
LOGGER.fine( "machine : " + Integer.toHexString( _genmachine ) );
}
catch ( Exception e ){
throw new RuntimeException( e );
}
}
}
|
|
/*
* Copyright 2002-2021 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.web.reactive.function.server;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.context.ApplicationContext;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.Hints;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.multipart.Part;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import org.springframework.web.util.UriUtils;
/**
* Default {@link ServerRequest.Builder} implementation.
*
* @author Arjen Poutsma
* @author Sam Brannen
* @since 5.1
*/
class DefaultServerRequestBuilder implements ServerRequest.Builder {
private final List<HttpMessageReader<?>> messageReaders;
private final ServerWebExchange exchange;
private HttpMethod method;
private URI uri;
private final HttpHeaders headers = new HttpHeaders();
private final MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>();
private final Map<String, Object> attributes = new LinkedHashMap<>();
private Flux<DataBuffer> body = Flux.empty();
DefaultServerRequestBuilder(ServerRequest other) {
Assert.notNull(other, "ServerRequest must not be null");
this.messageReaders = other.messageReaders();
this.exchange = other.exchange();
this.method = other.method();
this.uri = other.uri();
this.headers.addAll(other.headers().asHttpHeaders());
this.cookies.addAll(other.cookies());
this.attributes.putAll(other.attributes());
}
@Override
public ServerRequest.Builder method(HttpMethod method) {
Assert.notNull(method, "HttpMethod must not be null");
this.method = method;
return this;
}
@Override
public ServerRequest.Builder uri(URI uri) {
Assert.notNull(uri, "URI must not be null");
this.uri = uri;
return this;
}
@Override
public ServerRequest.Builder header(String headerName, String... headerValues) {
for (String headerValue : headerValues) {
this.headers.add(headerName, headerValue);
}
return this;
}
@Override
public ServerRequest.Builder headers(Consumer<HttpHeaders> headersConsumer) {
headersConsumer.accept(this.headers);
return this;
}
@Override
public ServerRequest.Builder cookie(String name, String... values) {
for (String value : values) {
this.cookies.add(name, new HttpCookie(name, value));
}
return this;
}
@Override
public ServerRequest.Builder cookies(Consumer<MultiValueMap<String, HttpCookie>> cookiesConsumer) {
cookiesConsumer.accept(this.cookies);
return this;
}
@Override
public ServerRequest.Builder body(Flux<DataBuffer> body) {
Assert.notNull(body, "Body must not be null");
releaseBody();
this.body = body;
return this;
}
@Override
public ServerRequest.Builder body(String body) {
Assert.notNull(body, "Body must not be null");
releaseBody();
this.body = Flux.just(body).
map(s -> {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
return DefaultDataBufferFactory.sharedInstance.wrap(bytes);
});
return this;
}
private void releaseBody() {
this.body.subscribe(DataBufferUtils.releaseConsumer());
}
@Override
public ServerRequest.Builder attribute(String name, Object value) {
this.attributes.put(name, value);
return this;
}
@Override
public ServerRequest.Builder attributes(Consumer<Map<String, Object>> attributesConsumer) {
attributesConsumer.accept(this.attributes);
return this;
}
@Override
public ServerRequest build() {
ServerHttpRequest serverHttpRequest = new BuiltServerHttpRequest(this.exchange.getRequest().getId(),
this.method, this.uri, this.headers, this.cookies, this.body);
ServerWebExchange exchange = new DelegatingServerWebExchange(
serverHttpRequest, this.attributes, this.exchange, this.messageReaders);
return new DefaultServerRequest(exchange, this.messageReaders);
}
private static class BuiltServerHttpRequest implements ServerHttpRequest {
private static final Pattern QUERY_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
private final String id;
private final HttpMethod method;
private final URI uri;
private final RequestPath path;
private final MultiValueMap<String, String> queryParams;
private final HttpHeaders headers;
private final MultiValueMap<String, HttpCookie> cookies;
private final Flux<DataBuffer> body;
public BuiltServerHttpRequest(String id, HttpMethod method, URI uri, HttpHeaders headers,
MultiValueMap<String, HttpCookie> cookies, Flux<DataBuffer> body) {
this.id = id;
this.method = method;
this.uri = uri;
this.path = RequestPath.parse(uri, null);
this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
this.cookies = unmodifiableCopy(cookies);
this.queryParams = parseQueryParams(uri);
this.body = body;
}
private static <K, V> MultiValueMap<K, V> unmodifiableCopy(MultiValueMap<K, V> original) {
return CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<>(original));
}
private static MultiValueMap<String, String> parseQueryParams(URI uri) {
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
String query = uri.getRawQuery();
if (query != null) {
Matcher matcher = QUERY_PATTERN.matcher(query);
while (matcher.find()) {
String name = UriUtils.decode(matcher.group(1), StandardCharsets.UTF_8);
String eq = matcher.group(2);
String value = matcher.group(3);
if (value != null) {
value = UriUtils.decode(value, StandardCharsets.UTF_8);
}
else {
value = (StringUtils.hasLength(eq) ? "" : null);
}
queryParams.add(name, value);
}
}
return queryParams;
}
@Override
public String getId() {
return this.id;
}
@Override
public HttpMethod getMethod() {
return this.method;
}
@Override
@Deprecated
public String getMethodValue() {
return this.method.name();
}
@Override
public URI getURI() {
return this.uri;
}
@Override
public RequestPath getPath() {
return this.path;
}
@Override
public HttpHeaders getHeaders() {
return this.headers;
}
@Override
public MultiValueMap<String, HttpCookie> getCookies() {
return this.cookies;
}
@Override
public MultiValueMap<String, String> getQueryParams() {
return this.queryParams;
}
@Override
public Flux<DataBuffer> getBody() {
return this.body;
}
}
private static class DelegatingServerWebExchange implements ServerWebExchange {
private static final ResolvableType FORM_DATA_TYPE =
ResolvableType.forClassWithGenerics(MultiValueMap.class, String.class, String.class);
private static final ResolvableType MULTIPART_DATA_TYPE = ResolvableType.forClassWithGenerics(
MultiValueMap.class, String.class, Part.class);
private static final Mono<MultiValueMap<String, String>> EMPTY_FORM_DATA =
Mono.just(CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<String, String>(0))).cache();
private static final Mono<MultiValueMap<String, Part>> EMPTY_MULTIPART_DATA =
Mono.just(CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<String, Part>(0))).cache();
private final ServerHttpRequest request;
private final Map<String, Object> attributes;
private final ServerWebExchange delegate;
private final Mono<MultiValueMap<String, String>> formDataMono;
private final Mono<MultiValueMap<String, Part>> multipartDataMono;
DelegatingServerWebExchange(ServerHttpRequest request, Map<String, Object> attributes,
ServerWebExchange delegate, List<HttpMessageReader<?>> messageReaders) {
this.request = request;
this.attributes = attributes;
this.delegate = delegate;
this.formDataMono = initFormData(request, messageReaders);
this.multipartDataMono = initMultipartData(request, messageReaders);
}
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, String>> initFormData(ServerHttpRequest request,
List<HttpMessageReader<?>> readers) {
try {
MediaType contentType = request.getHeaders().getContentType();
if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) {
return ((HttpMessageReader<MultiValueMap<String, String>>) readers.stream()
.filter(reader -> reader.canRead(FORM_DATA_TYPE, MediaType.APPLICATION_FORM_URLENCODED))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No form data HttpMessageReader.")))
.readMono(FORM_DATA_TYPE, request, Hints.none())
.switchIfEmpty(EMPTY_FORM_DATA)
.cache();
}
}
catch (InvalidMediaTypeException ex) {
// Ignore
}
return EMPTY_FORM_DATA;
}
@SuppressWarnings("unchecked")
private static Mono<MultiValueMap<String, Part>> initMultipartData(ServerHttpRequest request,
List<HttpMessageReader<?>> readers) {
try {
MediaType contentType = request.getHeaders().getContentType();
if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) {
return ((HttpMessageReader<MultiValueMap<String, Part>>) readers.stream()
.filter(reader -> reader.canRead(MULTIPART_DATA_TYPE, MediaType.MULTIPART_FORM_DATA))
.findFirst()
.orElseThrow(() -> new IllegalStateException("No multipart HttpMessageReader.")))
.readMono(MULTIPART_DATA_TYPE, request, Hints.none())
.switchIfEmpty(EMPTY_MULTIPART_DATA)
.cache();
}
}
catch (InvalidMediaTypeException ex) {
// Ignore
}
return EMPTY_MULTIPART_DATA;
}
@Override
public ServerHttpRequest getRequest() {
return this.request;
}
@Override
public Map<String, Object> getAttributes() {
return this.attributes;
}
@Override
public Mono<MultiValueMap<String, String>> getFormData() {
return this.formDataMono;
}
@Override
public Mono<MultiValueMap<String, Part>> getMultipartData() {
return this.multipartDataMono;
}
// Delegating methods
@Override
public ServerHttpResponse getResponse() {
return this.delegate.getResponse();
}
@Override
public Mono<WebSession> getSession() {
return this.delegate.getSession();
}
@Override
public <T extends Principal> Mono<T> getPrincipal() {
return this.delegate.getPrincipal();
}
@Override
public LocaleContext getLocaleContext() {
return this.delegate.getLocaleContext();
}
@Nullable
@Override
public ApplicationContext getApplicationContext() {
return this.delegate.getApplicationContext();
}
@Override
public boolean isNotModified() {
return this.delegate.isNotModified();
}
@Override
public boolean checkNotModified(Instant lastModified) {
return this.delegate.checkNotModified(lastModified);
}
@Override
public boolean checkNotModified(String etag) {
return this.delegate.checkNotModified(etag);
}
@Override
public boolean checkNotModified(@Nullable String etag, Instant lastModified) {
return this.delegate.checkNotModified(etag, lastModified);
}
@Override
public String transformUrl(String url) {
return this.delegate.transformUrl(url);
}
@Override
public void addUrlTransformer(Function<String, String> transformer) {
this.delegate.addUrlTransformer(transformer);
}
@Override
public String getLogPrefix() {
return this.delegate.getLogPrefix();
}
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.utils.memory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.rows.*;
import org.apache.cassandra.utils.concurrent.OpOrder;
/**
* This NativeAllocator uses global slab allocation strategy
* with slab size that scales exponentially from 8kb to 1Mb to
* serve allocation of up to 128kb.
* <p>
* </p>
* The slab allocation reduces heap fragmentation from small
* long-lived objects.
*
*/
public class NativeAllocator extends MemtableAllocator
{
private final static int MAX_REGION_SIZE = 1 * 1024 * 1024;
private final static int MAX_CLONED_SIZE = 128 * 1024; // bigger than this don't go in the region
private final static int MIN_REGION_SIZE = 8 * 1024;
// globally stash any Regions we allocate but are beaten to using, and use these up before allocating any more
private static final Map<Integer, RaceAllocated> RACE_ALLOCATED = new HashMap<>();
static
{
for(int i = MIN_REGION_SIZE ; i <= MAX_REGION_SIZE; i *= 2)
RACE_ALLOCATED.put(i, new RaceAllocated());
}
private final AtomicReference<Region> currentRegion = new AtomicReference<>();
private final ConcurrentLinkedQueue<Region> regions = new ConcurrentLinkedQueue<>();
private final EnsureOnHeap.CloneToHeap cloneToHeap = new EnsureOnHeap.CloneToHeap();
protected NativeAllocator(NativePool pool)
{
super(pool.onHeap.newAllocator(), pool.offHeap.newAllocator());
}
private static class CloningBTreeRowBuilder extends BTreeRow.Builder
{
final OpOrder.Group writeOp;
final NativeAllocator allocator;
private CloningBTreeRowBuilder(OpOrder.Group writeOp, NativeAllocator allocator)
{
super(true);
this.writeOp = writeOp;
this.allocator = allocator;
}
@Override
public void newRow(Clustering clustering)
{
if (clustering != Clustering.STATIC_CLUSTERING)
clustering = new NativeClustering(allocator, writeOp, clustering);
super.newRow(clustering);
}
@Override
public void addCell(Cell cell)
{
super.addCell(new NativeCell(allocator, writeOp, cell));
}
}
public Row.Builder rowBuilder(OpOrder.Group opGroup)
{
return new CloningBTreeRowBuilder(opGroup, this);
}
public DecoratedKey clone(DecoratedKey key, OpOrder.Group writeOp)
{
return new NativeDecoratedKey(key.getToken(), this, writeOp, key.getKey());
}
@Override
public MemtableAllocator.DataReclaimer reclaimer()
{
return NO_OP;
}
public EnsureOnHeap ensureOnHeap()
{
return cloneToHeap;
}
public long allocate(int size, OpOrder.Group opGroup)
{
assert size >= 0;
offHeap().allocate(size, opGroup);
// satisfy large allocations directly from JVM since they don't cause fragmentation
// as badly, and fill up our regions quickly
if (size > MAX_CLONED_SIZE)
return allocateOversize(size);
while (true)
{
Region region = currentRegion.get();
long peer;
if (region != null && (peer = region.allocate(size)) > 0)
return peer;
trySwapRegion(region, size);
}
}
private void trySwapRegion(Region current, int minSize)
{
// decide how big we want the new region to be:
// * if there is no prior region, we set it to min size
// * otherwise we double its size; if it's too small to fit the allocation, we round it up to 4-8x its size
int size;
if (current == null) size = MIN_REGION_SIZE;
else size = current.capacity * 2;
if (minSize > size)
size = Integer.highestOneBit(minSize) << 3;
size = Math.min(MAX_REGION_SIZE, size);
// first we try and repurpose a previously allocated region
RaceAllocated raceAllocated = RACE_ALLOCATED.get(size);
Region next = raceAllocated.poll();
// if there are none, we allocate one
if (next == null)
next = new Region(MemoryUtil.allocate(size), size);
// we try to swap in the region we've obtained;
// if we fail to swap the region, we try to stash it for repurposing later; if we're out of stash room, we free it
if (currentRegion.compareAndSet(current, next))
regions.add(next);
else if (!raceAllocated.stash(next))
MemoryUtil.free(next.peer);
}
private long allocateOversize(int size)
{
// satisfy large allocations directly from JVM since they don't cause fragmentation
// as badly, and fill up our regions quickly
Region region = new Region(MemoryUtil.allocate(size), size);
regions.add(region);
long peer;
if ((peer = region.allocate(size)) == -1)
throw new AssertionError();
return peer;
}
public void setDiscarded()
{
for (Region region : regions)
MemoryUtil.free(region.peer);
super.setDiscarded();
}
// used to ensure we don't keep loads of race allocated regions around indefinitely. keeps the total bound on wasted memory low.
private static class RaceAllocated
{
final ConcurrentLinkedQueue<Region> stash = new ConcurrentLinkedQueue<>();
final Semaphore permits = new Semaphore(8);
boolean stash(Region region)
{
if (!permits.tryAcquire())
return false;
stash.add(region);
return true;
}
Region poll()
{
Region next = stash.poll();
if (next != null)
permits.release();
return next;
}
}
/**
* A region of memory out of which allocations are sliced.
*
* This serves two purposes:
* - to provide a step between initialization and allocation, so that racing to CAS a
* new region in is harmless
* - encapsulates the allocation offset
*/
private static class Region
{
/**
* Actual underlying data
*/
private final long peer;
private final int capacity;
/**
* Offset for the next allocation, or the sentinel value -1
* which implies that the region is still uninitialized.
*/
private final AtomicInteger nextFreeOffset = new AtomicInteger(0);
/**
* Total number of allocations satisfied from this buffer
*/
private final AtomicInteger allocCount = new AtomicInteger();
/**
* Create an uninitialized region. Note that memory is not allocated yet, so
* this is cheap.
*
* @param peer peer
*/
private Region(long peer, int capacity)
{
this.peer = peer;
this.capacity = capacity;
}
/**
* Try to allocate <code>size</code> bytes from the region.
*
* @return the successful allocation, or null to indicate not-enough-space
*/
long allocate(int size)
{
while (true)
{
int oldOffset = nextFreeOffset.get();
if (oldOffset + size > capacity) // capacity == remaining
return -1;
// Try to atomically claim this region
if (nextFreeOffset.compareAndSet(oldOffset, oldOffset + size))
{
// we got the alloc
allocCount.incrementAndGet();
return peer + oldOffset;
}
// we raced and lost alloc, try again
}
}
@Override
public String toString()
{
return "Region@" + System.identityHashCode(this) +
" allocs=" + allocCount.get() + "waste=" +
(capacity - nextFreeOffset.get());
}
}
}
|
|
/*
* Copyright 2016 Johan Walles <[email protected]>
*
* 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.gmail.walles.johan.batterylogger;
import junit.framework.TestCase;
import org.junit.Assert;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
public class SystemStateTest extends TestCase {
private final Date now = new Date();
private final Date then = new Date(now.getTime() - History.FIVE_MINUTES_MS);
private final Date bootTimestamp = new Date(then.getTime() - History.FIVE_MINUTES_MS);
public void testConstructor() {
try {
new SystemState(then, 27, false, now);
Assert.fail("Expected IAE when boot is in the future");
} catch (IllegalArgumentException ignored) {
// Expected exception intentionally ignored
}
}
public void testEquals() {
Assert.assertTrue(new SystemState(now, 27, true, bootTimestamp).equals(new SystemState(now, 27, true, bootTimestamp)));
Assert.assertFalse(new SystemState(now, 27, true, bootTimestamp).equals(new SystemState(then, 27, true, bootTimestamp)));
Assert.assertFalse(new SystemState(now, 27, true, bootTimestamp).equals(new SystemState(now, 36, true, bootTimestamp)));
Assert.assertFalse(new SystemState(now, 27, true, bootTimestamp).equals(new SystemState(now, 27, false, bootTimestamp)));
Assert.assertFalse(new SystemState(now, 27, true, bootTimestamp).equals(new SystemState(now, 27, false, then)));
SystemState a = new SystemState(now, 27, false, bootTimestamp);
a.addInstalledApp("a.b.c", "Griseknoa", "1.2.3");
SystemState b = new SystemState(now, 27, false, bootTimestamp);
b.addInstalledApp("a.b.c", "Griseknoa", "1.2.3");
Assert.assertEquals(a, b);
SystemState c = new SystemState(now, 27, false, bootTimestamp);
c.addInstalledApp("x.y.z", "Griseknoa", "1.2.3");
Assert.assertFalse(a.equals(c));
SystemState d = new SystemState(now, 27, false, bootTimestamp);
d.addInstalledApp("a.b.c", "Charles-Ingvar", "1.2.3");
Assert.assertFalse(a.equals(d));
SystemState e = new SystemState(now, 27, false, bootTimestamp);
e.addInstalledApp("a.b.c", "Griseknoa", "4.5.6");
Assert.assertFalse(a.equals(e));
}
public void testUnorderedEquals() {
SystemState a = new SystemState(now, 27, false, bootTimestamp);
a.addInstalledApp("a.b.c", "Griseknoa", "1.2.3");
a.addInstalledApp("d.e.f", "Snickarboa", "4.5.6");
SystemState b = new SystemState(now, 27, false, bootTimestamp);
b.addInstalledApp("d.e.f", "Snickarboa", "4.5.6");
b.addInstalledApp("a.b.c", "Griseknoa", "1.2.3");
Assert.assertEquals(a, b);
}
private void assertEvents(Collection<HistoryEvent> testMe, HistoryEvent ... expected) {
Assert.assertNotNull("Events must be non-null, were null", testMe);
String expectedString = Arrays.toString(expected);
String actualString = Arrays.toString(testMe.toArray());
Assert.assertEquals(expectedString, actualString);
}
private void assertNoEvents(Collection<HistoryEvent> testMe) {
assertEvents(testMe);
}
public void testBatteryEvent() {
SystemState a = new SystemState(then, 27, false, bootTimestamp);
SystemState b = new SystemState(now, 26, false, bootTimestamp);
assertEvents(b.getEventsSince(a), HistoryEvent.createBatteryLevelEvent(now, 26));
SystemState c = new SystemState(now, 28, true, bootTimestamp);
assertEvents(c.getEventsSince(a),
HistoryEvent.createStartChargingEvent(between(then, now)),
HistoryEvent.createBatteryLevelEvent(now, 28));
SystemState d = new SystemState(now, 29, true, bootTimestamp);
assertNoEvents(d.getEventsSince(c));
}
public void testStartChargingEvent() {
SystemState a = new SystemState(then, 27, false, bootTimestamp);
SystemState b = new SystemState(now, 27, true, bootTimestamp);
assertEvents(b.getEventsSince(a), HistoryEvent.createStartChargingEvent(between(then, now)));
}
public void testStopChargingEvent() {
SystemState a = new SystemState(then, 27, true, bootTimestamp);
SystemState b = new SystemState(now, 27, false, bootTimestamp);
assertEvents(b.getEventsSince(a), HistoryEvent.createStopChargingEvent(between(then, now)));
}
private static Date between(Date t0, Date t1) {
return new Date((t0.getTime() + t1.getTime()) / 2);
}
public void testInstallEvent() {
SystemState a = new SystemState(then, 27, false, bootTimestamp);
SystemState b = new SystemState(now, 27, false, bootTimestamp);
b.addInstalledApp("a.b.c", "ABC", "1.2.3");
assertEvents(b.getEventsSince(a), HistoryEvent.createInfoEvent(between(then, now), "ABC 1.2.3 installed"));
}
public void testUninstallEvent() {
SystemState a = new SystemState(then, 27, false, bootTimestamp);
a.addInstalledApp("a.b.c", "ABC", "1.2.3");
SystemState b = new SystemState(now, 27, false, bootTimestamp);
assertEvents(b.getEventsSince(a), HistoryEvent.createInfoEvent(between(then, now), "ABC 1.2.3 uninstalled"));
}
public void testUpgradeEvent() {
SystemState a = new SystemState(then, 27, false, bootTimestamp);
a.addInstalledApp("a.b.c", "ABC", "1.2.3");
SystemState b = new SystemState(now, 27, false, bootTimestamp);
b.addInstalledApp("a.b.c", "ABC", "2.3.4");
assertEvents(b.getEventsSince(a), HistoryEvent.createInfoEvent(between(then, now), "ABC upgraded from 1.2.3 to 2.3.4"));
}
public void testPersistence() throws Exception {
File tempFile = File.createTempFile("systemstate-", ".txt");
try {
SystemState a = new SystemState(then, 27, false, bootTimestamp);
a.addInstalledApp("a.b.c", "ABC", "1.2.3");
a.writeToFile(tempFile);
SystemState b = SystemState.readFromFile(tempFile);
Assert.assertEquals(a, b);
} finally {
//noinspection ConstantConditions
if (tempFile != null) {
//noinspection ResultOfMethodCallIgnored
tempFile.delete();
}
}
}
public void testHaltAndBootEvents() {
Date boot1 = new Date(0);
Date sample1 = new Date(100000);
Date boot2 = new Date(200000);
Date sample2 = new Date(300000);
SystemState beforeReboot = new SystemState(sample1, 27, false, boot1);
SystemState afterReboot = new SystemState(sample2, 27, false, boot2);
assertEvents(afterReboot.getEventsSince(beforeReboot),
HistoryEvent.createSystemHaltingEvent(new Date(sample1.getTime() + 1)),
HistoryEvent.createSystemBootingEvent(boot2, false));
}
public void testHaltAndBootAndChargeEvents() {
Date boot1 = new Date(0);
Date sample1 = new Date(100000);
Date boot2 = new Date(200000);
Date sample2 = new Date(300000);
SystemState beforeReboot = new SystemState(sample1, 27, false, boot1);
SystemState afterReboot = new SystemState(sample2, 27, true, boot2);
assertEvents(afterReboot.getEventsSince(beforeReboot),
HistoryEvent.createSystemHaltingEvent(new Date(sample1.getTime() + 1)),
HistoryEvent.createSystemBootingEvent(boot2, true));
}
/**
* Verify that different events resulting in text in the graph don't overlap each other.
*/
public void testPreventOverlappingEvents() {
SystemState a = new SystemState(then, 27, true, bootTimestamp);
a.addInstalledApp("a.b.c", "Upgrader", "1.2.3");
a.addInstalledApp("d.e.f", "Remover", "2.3.4");
SystemState b = new SystemState(now, 26, false, bootTimestamp);
b.addInstalledApp("a.b.c", "Upgrader", "1.2.5");
b.addInstalledApp("g.h.i", "Adder", "5.6.7");
Date datesBetween[] = SystemState.between(then, now, 4);
// Note that the actual order here is arbitrary
assertEvents(b.getEventsSince(a),
HistoryEvent.createStopChargingEvent(datesBetween[0]),
HistoryEvent.createInfoEvent(datesBetween[1], "Adder 5.6.7 installed"),
HistoryEvent.createInfoEvent(datesBetween[2], "Remover 2.3.4 uninstalled"),
HistoryEvent.createInfoEvent(datesBetween[3], "Upgrader upgraded from 1.2.3 to 1.2.5"),
HistoryEvent.createBatteryLevelEvent(now, 26));
}
public void testBetween() {
Date dates[] = SystemState.between(then, now, 1);
Assert.assertEquals(1, dates.length);
Assert.assertEquals(between(then, now), dates[0]);
}
/**
* Two SystemStates should be equal even if their boot timestamps are a little bit off. Since the boot timestamps
* are calculated will millisecond precision we need some margin of error.
*/
public void testBootTimeLeniency() {
SystemState a = new SystemState(now, 27, false, new Date(0));
SystemState b = new SystemState(now, 27, false, new Date(10 * 1000));
Assert.assertEquals(a, b);
SystemState c = new SystemState(now, 27, false, new Date(100 * 1000));
Assert.assertFalse(a.equals(c));
}
}
|
|
package org.apache.solr.cloud;
/*
* 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.File;
import java.net.ServerSocket;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.lucene.util.LuceneTestCase.AwaitsFix;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.solr.SolrTestCaseJ4.SuppressSSL;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.util.NamedList;
import org.junit.After;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//@AwaitsFix(bugUrl = "https://issues.apache.org/jira/browse/SOLR-6157")
/**
* Tests a client application's ability to get replication factor
* information back from the cluster after an add or update.
*/
@Slow
@SuppressSSL(bugUrl = "https://issues.apache.org/jira/browse/SOLR-5776")
public class ReplicationFactorTest extends AbstractFullDistribZkTestBase {
private static final transient Logger log =
LoggerFactory.getLogger(ReplicationFactorTest.class);
public ReplicationFactorTest() {
super();
sliceCount = 3;
shardCount = 3;
}
@Before
@Override
public void setUp() throws Exception {
super.setUp();
System.setProperty("numShards", Integer.toString(sliceCount));
}
@Override
@After
public void tearDown() throws Exception {
log.info("tearing down replicationFactorTest!");
System.clearProperty("numShards");
try {
super.tearDown();
} catch (Exception exc) {}
resetExceptionIgnores();
log.info("super.tearDown complete, closing all socket proxies");
if (!proxies.isEmpty()) {
for (SocketProxy proxy : proxies.values()) {
proxy.close();
}
}
}
/**
* Overrides the parent implementation so that we can configure a socket proxy
* to sit infront of each Jetty server, which gives us the ability to simulate
* network partitions without having to fuss with IPTables (which is not very
* cross platform friendly).
*/
@Override
public JettySolrRunner createJetty(File solrHome, String dataDir,
String shardList, String solrConfigOverride, String schemaOverride)
throws Exception {
return createProxiedJetty(solrHome, dataDir, shardList, solrConfigOverride, schemaOverride);
}
protected int getNextAvailablePort() throws Exception {
int port = -1;
try (ServerSocket s = new ServerSocket(0)) {
port = s.getLocalPort();
}
return port;
}
@Override
public void doTest() throws Exception {
log.info("replication factor test running");
waitForThingsToLevelOut(30000);
// test a 1x3 collection
log.info("Testing replication factor handling for repfacttest_c8n_1x3");
testRf3();
waitForThingsToLevelOut(30000);
// test handling when not using direct updates
log.info("Now testing replication factor handling for repfacttest_c8n_2x2");
testRf2NotUsingDirectUpdates();
waitForThingsToLevelOut(30000);
log.info("replication factor testing complete! final clusterState is: "+
cloudClient.getZkStateReader().getClusterState());
}
protected void testRf2NotUsingDirectUpdates() throws Exception {
int numShards = 2;
int replicationFactor = 2;
int maxShardsPerNode = 1;
String testCollectionName = "repfacttest_c8n_2x2";
String shardId = "shard1";
int minRf = 2;
createCollection(testCollectionName, numShards, replicationFactor, maxShardsPerNode);
cloudClient.setDefaultCollection(testCollectionName);
List<Replica> replicas =
ensureAllReplicasAreActive(testCollectionName, shardId, numShards, replicationFactor, 30);
assertTrue("Expected active 1 replicas for "+testCollectionName, replicas.size() == 1);
List<SolrInputDocument> batch = new ArrayList<SolrInputDocument>(10);
for (int i=0; i < 15; i++) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField(id, String.valueOf(i));
doc.addField("a_t", "hello" + i);
batch.add(doc);
}
// send directly to the leader using HttpSolrServer instead of CloudSolrServer (to test support for non-direct updates)
UpdateRequest up = new UpdateRequest();
up.setParam(UpdateRequest.MIN_REPFACT, String.valueOf(minRf));
up.add(batch);
Replica leader = cloudClient.getZkStateReader().getLeaderRetry(testCollectionName, shardId);
sendNonDirectUpdateRequestReplica(leader, up, 2, testCollectionName);
sendNonDirectUpdateRequestReplica(replicas.get(0), up, 2, testCollectionName);
// so now kill the replica of shard2 and verify the achieved rf is only 1
List<Replica> shard2Replicas =
ensureAllReplicasAreActive(testCollectionName, "shard2", numShards, replicationFactor, 30);
assertTrue("Expected active 1 replicas for "+testCollectionName, replicas.size() == 1);
getProxyForReplica(shard2Replicas.get(0)).close();
Thread.sleep(2000);
// shard1 will have rf=2 but shard2 will only have rf=1
sendNonDirectUpdateRequestReplica(leader, up, 1, testCollectionName);
sendNonDirectUpdateRequestReplica(replicas.get(0), up, 1, testCollectionName);
// heal the partition
getProxyForReplica(shard2Replicas.get(0)).reopen();
Thread.sleep(2000);
}
@SuppressWarnings("rawtypes")
protected void sendNonDirectUpdateRequestReplica(Replica replica, UpdateRequest up, int expectedRf, String collection) throws Exception {
HttpSolrClient solrServer = null;
try {
ZkCoreNodeProps zkProps = new ZkCoreNodeProps(replica);
String url = zkProps.getBaseUrl() + "/" + collection;
solrServer = new HttpSolrClient(url);
NamedList resp = solrServer.request(up);
NamedList hdr = (NamedList) resp.get("responseHeader");
Integer batchRf = (Integer)hdr.get(UpdateRequest.REPFACT);
assertTrue("Expected rf="+expectedRf+" for batch but got "+
batchRf+"; clusterState: "+printClusterStateInfo(), batchRf == expectedRf);
} finally {
if (solrServer != null)
solrServer.shutdown();
}
}
protected void testRf3() throws Exception {
int numShards = 1;
int replicationFactor = 3;
int maxShardsPerNode = 1;
String testCollectionName = "repfacttest_c8n_1x3";
String shardId = "shard1";
int minRf = 2;
createCollection(testCollectionName, numShards, replicationFactor, maxShardsPerNode);
cloudClient.setDefaultCollection(testCollectionName);
List<Replica> replicas =
ensureAllReplicasAreActive(testCollectionName, shardId, numShards, replicationFactor, 30);
assertTrue("Expected 2 active replicas for "+testCollectionName, replicas.size() == 2);
int rf = sendDoc(1, minRf);
assertRf(3, "all replicas should be active", rf);
getProxyForReplica(replicas.get(0)).close();
rf = sendDoc(2, minRf);
assertRf(2, "one replica should be down", rf);
getProxyForReplica(replicas.get(1)).close();
rf = sendDoc(3, minRf);
assertRf(1, "both replicas should be down", rf);
// heal the partitions
getProxyForReplica(replicas.get(0)).reopen();
getProxyForReplica(replicas.get(1)).reopen();
Thread.sleep(2000); // give time for the healed partition to get propagated
ensureAllReplicasAreActive(testCollectionName, shardId, numShards, replicationFactor, 30);
rf = sendDoc(4, minRf);
assertRf(3, "partitions to replicas have been healed", rf);
// now send a batch
List<SolrInputDocument> batch = new ArrayList<SolrInputDocument>(10);
for (int i=5; i < 15; i++) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField(id, String.valueOf(i));
doc.addField("a_t", "hello" + i);
batch.add(doc);
}
UpdateRequest up = new UpdateRequest();
up.setParam(UpdateRequest.MIN_REPFACT, String.valueOf(minRf));
up.add(batch);
int batchRf =
cloudClient.getMinAchievedReplicationFactor(cloudClient.getDefaultCollection(), cloudClient.request(up));
assertRf(3, "batch should have succeeded on all replicas", batchRf);
// add some chaos to the batch
getProxyForReplica(replicas.get(0)).close();
// now send a batch
batch = new ArrayList<SolrInputDocument>(10);
for (int i=15; i < 30; i++) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField(id, String.valueOf(i));
doc.addField("a_t", "hello" + i);
batch.add(doc);
}
up = new UpdateRequest();
up.setParam(UpdateRequest.MIN_REPFACT, String.valueOf(minRf));
up.add(batch);
batchRf =
cloudClient.getMinAchievedReplicationFactor(cloudClient.getDefaultCollection(), cloudClient.request(up));
assertRf(2, "batch should have succeeded on 2 replicas (only one replica should be down)", batchRf);
// close the 2nd replica, and send a 3rd batch with expected achieved rf=1
getProxyForReplica(replicas.get(1)).close();
batch = new ArrayList<SolrInputDocument>(10);
for (int i=30; i < 45; i++) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField(id, String.valueOf(i));
doc.addField("a_t", "hello" + i);
batch.add(doc);
}
up = new UpdateRequest();
up.setParam(UpdateRequest.MIN_REPFACT, String.valueOf(minRf));
up.add(batch);
batchRf =
cloudClient.getMinAchievedReplicationFactor(cloudClient.getDefaultCollection(), cloudClient.request(up));
assertRf(1, "batch should have succeeded on the leader only (both replicas should be down)", batchRf);
getProxyForReplica(replicas.get(0)).reopen();
getProxyForReplica(replicas.get(1)).reopen();
Thread.sleep(2000);
ensureAllReplicasAreActive(testCollectionName, shardId, numShards, replicationFactor, 30);
}
protected int sendDoc(int docId, int minRf) throws Exception {
UpdateRequest up = new UpdateRequest();
up.setParam(UpdateRequest.MIN_REPFACT, String.valueOf(minRf));
SolrInputDocument doc = new SolrInputDocument();
doc.addField(id, String.valueOf(docId));
doc.addField("a_t", "hello" + docId);
up.add(doc);
return cloudClient.getMinAchievedReplicationFactor(cloudClient.getDefaultCollection(), cloudClient.request(up));
}
protected void assertRf(int expected, String explain, int actual) throws Exception {
if (actual != expected) {
String assertionFailedMessage =
String.format(Locale.ENGLISH, "Expected rf=%d because %s but got %d", expected, explain, actual);
fail(assertionFailedMessage+"; clusterState: "+printClusterStateInfo());
}
}
}
|
|
/*
* Copyright 2014-present Open Networking 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.onosproject.net.intent;
import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects;
import org.onosproject.core.ApplicationId;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.OchSignal;
import org.onosproject.net.OduSignalType;
import org.onosproject.net.ResourceGroup;
import java.util.Collections;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* An optical layer intent for connectivity between two OCh ports.
* No traffic selector or traffic treatment are needed.
*/
@Beta
public final class OpticalConnectivityIntent extends Intent {
private final ConnectPoint src;
private final ConnectPoint dst;
private final OduSignalType signalType;
private final boolean isBidirectional;
private final Optional<OchSignal> ochSignal;
/**
* Creates an optical connectivity intent between the specified
* connection points.
*
* @param appId application identification
* @param key intent key
* @param src the source transponder port
* @param dst the destination transponder port
* @param signalType signal type
* @param isBidirectional indicates if intent is unidirectional
* @param ochSignal optional OCh signal
* @param priority priority to use for flows from this intent
* @param resourceGroup resource group of this intent
*/
protected OpticalConnectivityIntent(ApplicationId appId,
Key key,
ConnectPoint src,
ConnectPoint dst,
OduSignalType signalType,
boolean isBidirectional,
Optional<OchSignal> ochSignal,
int priority,
ResourceGroup resourceGroup) {
super(appId, key, Collections.emptyList(), priority, resourceGroup);
this.src = checkNotNull(src);
this.dst = checkNotNull(dst);
this.signalType = checkNotNull(signalType);
this.isBidirectional = isBidirectional;
this.ochSignal = ochSignal;
}
/**
* Returns a new optical connectivity intent builder.
*
* @return host to host intent builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for optical connectivity intents.
*/
public static class Builder extends Intent.Builder {
private ConnectPoint src;
private ConnectPoint dst;
private OduSignalType signalType;
private boolean isBidirectional;
private Optional<OchSignal> ochSignal = Optional.empty();
@Override
public Builder appId(ApplicationId appId) {
return (Builder) super.appId(appId);
}
@Override
public Builder key(Key key) {
return (Builder) super.key(key);
}
@Override
public Builder priority(int priority) {
return (Builder) super.priority(priority);
}
@Override
public Builder resourceGroup(ResourceGroup resourceGroup) {
return (Builder) super.resourceGroup(resourceGroup);
}
/**
* Sets the source for the intent that will be built.
*
* @param src source to use for built intent
* @return this builder
*/
public Builder src(ConnectPoint src) {
this.src = src;
return this;
}
/**
* Sets the destination for the intent that will be built.
*
* @param dst dest to use for built intent
* @return this builder
*/
public Builder dst(ConnectPoint dst) {
this.dst = dst;
return this;
}
/**
* Sets the ODU signal type for the intent that will be built.
*
* @param signalType ODU signal type
* @return this builder
*/
public Builder signalType(OduSignalType signalType) {
this.signalType = signalType;
return this;
}
/**
* Sets the directionality of the intent.
*
* @param isBidirectional true if bidirectional, false if unidirectional
* @return this builder
*/
public Builder bidirectional(boolean isBidirectional) {
this.isBidirectional = isBidirectional;
return this;
}
/**
* Sets the OCh signal of the intent.
*
* @param ochSignal the lambda
* @return this builder
*/
public Builder ochSignal(OchSignal ochSignal) {
this.ochSignal = Optional.ofNullable(ochSignal);
return this;
}
/**
* Builds an optical connectivity intent from the accumulated parameters.
*
* @return point to point intent
*/
public OpticalConnectivityIntent build() {
return new OpticalConnectivityIntent(
appId,
key,
src,
dst,
signalType,
isBidirectional,
ochSignal,
priority,
resourceGroup
);
}
}
/**
* Constructor for serializer.
*/
protected OpticalConnectivityIntent() {
super();
this.src = null;
this.dst = null;
this.signalType = null;
this.isBidirectional = false;
this.ochSignal = null;
}
/**
* Returns the source transponder port.
*
* @return source transponder port
*/
public ConnectPoint getSrc() {
return src;
}
/**
* Returns the destination transponder port.
*
* @return source transponder port
*/
public ConnectPoint getDst() {
return dst;
}
/**
* Returns the ODU signal type.
*
* @return ODU signal type
*/
public OduSignalType getSignalType() {
return signalType;
}
/**
* Returns the directionality of the intent.
*
* @return true if bidirectional, false if unidirectional
*/
public boolean isBidirectional() {
return isBidirectional;
}
/**
* Returns the OCh signal of the intent.
*
* @return the lambda
*/
public Optional<OchSignal> ochSignal() {
return ochSignal;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", id())
.add("key", key())
.add("appId", appId())
.add("priority", priority())
.add("resources", resources())
.add("src", src)
.add("dst", dst)
.add("signalType", signalType)
.add("isBidirectional", isBidirectional)
.add("ochSignal", ochSignal)
.add("resourceGroup", resourceGroup())
.toString();
}
}
|
|
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kew.engine.node.dao.impl;
import org.kuali.rice.core.api.criteria.QueryByCriteria;
import org.kuali.rice.kew.api.KEWPropertyConstants;
import org.kuali.rice.kew.engine.node.NodeState;
import org.kuali.rice.kew.engine.node.RouteNode;
import org.kuali.rice.kew.engine.node.RouteNodeInstance;
import org.kuali.rice.kew.engine.node.dao.RouteNodeDAO;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.krad.data.DataObjectService;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.PreparedStatementCreator;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static org.kuali.rice.core.api.criteria.PredicateFactory.equal;
public class RouteNodeDAOJpa implements RouteNodeDAO {
private EntityManager entityManager;
private DataObjectService dataObjectService;
public static final String FIND_INITIAL_NODE_INSTANCES_NAME = "RouteNodeInstance.FindInitialNodeInstances";
public static final String FIND_INITIAL_NODE_INSTANCES_QUERY = "select d.initialRouteNodeInstances from "
+ "DocumentRouteHeaderValue d where d.documentId = :documentId";
/**
* @return the entityManager
*/
public EntityManager getEntityManager() {
return this.entityManager;
}
/**
* @param entityManager the entityManager to set
*/
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public RouteNodeInstance findRouteNodeInstanceById(String nodeInstanceId) {
QueryByCriteria.Builder queryByCriteria = QueryByCriteria.Builder.create().setPredicates(
equal(KEWPropertyConstants.ROUTE_NODE_INSTANCE_ID,nodeInstanceId)
);
List<RouteNodeInstance> routeNodeInstances = getDataObjectService().findMatching(
RouteNodeInstance.class,queryByCriteria.build()).getResults();
if(routeNodeInstances != null && routeNodeInstances.size() > 0){
return routeNodeInstances.get(0);
}
return null;
}
@SuppressWarnings("unchecked")
public List<RouteNodeInstance> getActiveNodeInstances(String documentId) {
QueryByCriteria.Builder queryByCriteria = QueryByCriteria.Builder.create().setPredicates(
equal(KEWPropertyConstants.DOCUMENT_ID,documentId),
equal(KEWPropertyConstants.ACTIVE,true)
);
return getDataObjectService().findMatching(RouteNodeInstance.class,
queryByCriteria.build()).getResults();
}
private static final String CURRENT_ROUTE_NODE_NAMES_SQL = "SELECT rn.nm" +
" FROM krew_rte_node_t rn," +
" krew_rte_node_instn_t rni" +
" LEFT JOIN krew_rte_node_instn_lnk_t rnl" +
" ON rnl.from_rte_node_instn_id = rni.rte_node_instn_id" +
" WHERE rn.rte_node_id = rni.rte_node_id AND" +
" rni.doc_hdr_id = ? AND" +
" rnl.from_rte_node_instn_id IS NULL";
@Override
public List<String> getCurrentRouteNodeNames(final String documentId) {
final DataSource dataSource = KEWServiceLocator.getDataSource();
JdbcTemplate template = new JdbcTemplate(dataSource);
List<String> names = template.execute(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
return connection.prepareStatement(CURRENT_ROUTE_NODE_NAMES_SQL);
}
}, new PreparedStatementCallback<List<String>>() {
public List<String> doInPreparedStatement(
PreparedStatement statement) throws SQLException, DataAccessException {
List<String> routeNodeNames = new ArrayList<String>();
statement.setString(1, documentId);
ResultSet rs = statement.executeQuery();
try {
while (rs.next()) {
String name = rs.getString("nm");
routeNodeNames.add(name);
}
} finally {
if (rs != null) {
rs.close();
}
}
return routeNodeNames;
}
}
);
return names;
}
@Override
public List<String> getActiveRouteNodeNames(final String documentId) {
final DataSource dataSource = KEWServiceLocator.getDataSource();
JdbcTemplate template = new JdbcTemplate(dataSource);
List<String> names = template.execute(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement statement = connection.prepareStatement(
"SELECT rn.nm FROM krew_rte_node_t rn, krew_rte_node_instn_t rni WHERE rn.rte_node_id "
+ "= rni.rte_node_id AND rni.doc_hdr_id = ? AND rni.actv_ind = ?");
return statement;
}
},
new PreparedStatementCallback<List<String>>() {
public List<String> doInPreparedStatement(PreparedStatement statement) throws SQLException, DataAccessException {
List<String> routeNodeNames = new ArrayList<String>();
statement.setString(1, documentId);
statement.setBoolean(2, Boolean.TRUE);
ResultSet rs = statement.executeQuery();
try {
while(rs.next()) {
String name = rs.getString("nm");
routeNodeNames.add(name);
}
} finally {
if(rs != null) {
rs.close();
}
}
return routeNodeNames;
}
});
return names;
}
@SuppressWarnings("unchecked")
public List<RouteNodeInstance> getTerminalNodeInstances(String documentId) {
QueryByCriteria.Builder queryByCriteria = QueryByCriteria.Builder.create().setPredicates(
equal(KEWPropertyConstants.DOCUMENT_ID,documentId),
equal(KEWPropertyConstants.ACTIVE,false),
equal(KEWPropertyConstants.COMPLETE,true)
);
//FIXME: Can we do this better using just the JPQL query?
List<RouteNodeInstance> terminalNodes = new ArrayList<RouteNodeInstance>();
List<RouteNodeInstance> routeNodeInstances = getDataObjectService().
findMatching(RouteNodeInstance.class,queryByCriteria.build()).getResults();
for (RouteNodeInstance routeNodeInstance : routeNodeInstances) {
if (routeNodeInstance.getNextNodeInstances().isEmpty()) {
terminalNodes.add(routeNodeInstance);
}
}
return terminalNodes;
}
@Override
public List<String> getTerminalRouteNodeNames(final String documentId) {
final DataSource dataSource = KEWServiceLocator.getDataSource();
JdbcTemplate template = new JdbcTemplate(dataSource);
List<String> names = template.execute(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement statement = connection.prepareStatement("SELECT rn.nm" +
" FROM krew_rte_node_t rn," +
" krew_rte_node_instn_t rni" +
" LEFT JOIN krew_rte_node_instn_lnk_t rnl" +
" ON rnl.from_rte_node_instn_id = rni.rte_node_instn_id" +
" WHERE rn.rte_node_id = rni.rte_node_id AND" +
" rni.doc_hdr_id = ? AND" +
" rni.actv_ind = ? AND" +
" rni.cmplt_ind = ? AND" +
" rnl.from_rte_node_instn_id IS NULL");
return statement;
}
}, new PreparedStatementCallback<List<String>>() {
public List<String> doInPreparedStatement(
PreparedStatement statement) throws SQLException, DataAccessException {
List<String> routeNodeNames = new ArrayList<String>();
statement.setString(1, documentId);
statement.setBoolean(2, Boolean.FALSE);
statement.setBoolean(3, Boolean.TRUE);
ResultSet rs = statement.executeQuery();
try {
while (rs.next()) {
String name = rs.getString("nm");
routeNodeNames.add(name);
}
} finally {
if (rs != null) {
rs.close();
}
}
return routeNodeNames;
}
}
);
return names;
}
public List getInitialNodeInstances(String documentId) {
//FIXME: Not sure this query is returning what it needs to
Query query = entityManager.createNamedQuery(FIND_INITIAL_NODE_INSTANCES_NAME);
query.setParameter(KEWPropertyConstants.DOCUMENT_ID, documentId);
return (List)query.getResultList();
}
public NodeState findNodeState(Long nodeInstanceId, String key) {
QueryByCriteria.Builder queryByCriteria = QueryByCriteria.Builder.create().setPredicates(
equal(KEWPropertyConstants.ROUTE_NODE_INSTANCE_ID,nodeInstanceId.toString()),
equal(KEWPropertyConstants.KEY,key)
);
List<NodeState> nodeStates = getDataObjectService().findMatching(
NodeState.class,queryByCriteria.build()).getResults();
if(nodeStates != null && nodeStates.size() > 0){
return nodeStates.get(0);
}
return null;
}
public RouteNode findRouteNodeByName(String documentTypeId, String name) {
QueryByCriteria.Builder queryByCriteria = QueryByCriteria.Builder.create().setPredicates(
equal(KEWPropertyConstants.DOCUMENT_TYPE_ID,documentTypeId),
equal(KEWPropertyConstants.ROUTE_NODE_NAME,name)
);
List<RouteNode> routeNodes = getDataObjectService().findMatching(
RouteNode.class,queryByCriteria.build()).getResults();
if(routeNodes != null && routeNodes.size() > 0){
return routeNodes.get(0);
}
return null;
}
public List<RouteNode> findFinalApprovalRouteNodes(String documentTypeId) {
QueryByCriteria.Builder queryByCriteria = QueryByCriteria.Builder.create().setPredicates(
equal(KEWPropertyConstants.DOCUMENT_TYPE_ID,documentTypeId),
equal(KEWPropertyConstants.FINAL_APPROVAL,Boolean.TRUE)
);
return getDataObjectService().findMatching(RouteNode.class,queryByCriteria.build()).getResults();
}
public List findProcessNodeInstances(RouteNodeInstance process) {
QueryByCriteria.Builder queryByCriteria = QueryByCriteria.Builder.create().setPredicates(
equal(KEWPropertyConstants.PROCESS_ID,process.getRouteNodeInstanceId())
);
return getDataObjectService().findMatching(RouteNodeInstance.class,queryByCriteria.build()).getResults();
}
public List findRouteNodeInstances(String documentId) {
QueryByCriteria.Builder queryByCriteria = QueryByCriteria.Builder.create().setPredicates(
equal(KEWPropertyConstants.DOCUMENT_ID,documentId)
);
return getDataObjectService().findMatching(RouteNodeInstance.class,queryByCriteria.build()).getResults();
}
public void deleteLinksToPreNodeInstances(RouteNodeInstance routeNodeInstance) {
List<RouteNodeInstance> preNodeInstances = routeNodeInstance.getPreviousNodeInstances();
for (Iterator<RouteNodeInstance> preNodeInstanceIter = preNodeInstances.iterator(); preNodeInstanceIter.hasNext();) {
RouteNodeInstance preNodeInstance = (RouteNodeInstance) preNodeInstanceIter.next();
List<RouteNodeInstance> nextInstances = preNodeInstance.getNextNodeInstances();
nextInstances.remove(routeNodeInstance);
getEntityManager().merge(preNodeInstance);
}
}
public void deleteRouteNodeInstancesHereAfter(RouteNodeInstance routeNodeInstance) {
RouteNodeInstance rnInstance = findRouteNodeInstanceById(routeNodeInstance.getRouteNodeInstanceId());
entityManager.remove(rnInstance);
}
public void deleteNodeStateById(Long nodeStateId) {
QueryByCriteria.Builder queryByCriteria = QueryByCriteria.Builder.create().setPredicates(
equal(KEWPropertyConstants.ROUTE_NODE_STATE_ID,nodeStateId)
);
List<NodeState> nodeStates = getDataObjectService().findMatching(
NodeState.class,queryByCriteria.build()).getResults();
NodeState nodeState = null;
if(nodeStates != null && nodeStates.size() > 0){
nodeState = nodeStates.get(0);
}
getDataObjectService().delete(nodeState);
}
public void deleteNodeStates(List statesToBeDeleted) {
for (Iterator stateToBeDeletedIter = statesToBeDeleted.iterator(); stateToBeDeletedIter.hasNext();) {
Long stateId = (Long) stateToBeDeletedIter.next();
deleteNodeStateById(stateId);
}
}
public DataObjectService getDataObjectService() {
return dataObjectService;
}
@Required
public void setDataObjectService(DataObjectService dataObjectService) {
this.dataObjectService = dataObjectService;
}
}
|
|
// 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.
/**
* DeleteSecurityGroupResponseType.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.5.6 Built on : Aug 30, 2011 (10:01:01 CEST)
*/
package com.amazon.ec2;
/**
* DeleteSecurityGroupResponseType bean class
*/
public class DeleteSecurityGroupResponseType
implements org.apache.axis2.databinding.ADBBean{
/* This type was generated from the piece of schema that had
name = DeleteSecurityGroupResponseType
Namespace URI = http://ec2.amazonaws.com/doc/2012-08-15/
Namespace Prefix = ns1
*/
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://ec2.amazonaws.com/doc/2012-08-15/")){
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* field for RequestId
*/
protected java.lang.String localRequestId ;
/**
* Auto generated getter method
* @return java.lang.String
*/
public java.lang.String getRequestId(){
return localRequestId;
}
/**
* Auto generated setter method
* @param param RequestId
*/
public void setRequestId(java.lang.String param){
this.localRequestId=param;
}
/**
* field for _return
*/
protected boolean local_return ;
/**
* Auto generated getter method
* @return boolean
*/
public boolean get_return(){
return local_return;
}
/**
* Auto generated setter method
* @param param _return
*/
public void set_return(boolean param){
this.local_return=param;
}
/**
* isReaderMTOMAware
* @return true if the reader supports MTOM
*/
public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) {
boolean isReaderMTOMAware = false;
try{
isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE));
}catch(java.lang.IllegalArgumentException e){
isReaderMTOMAware = false;
}
return isReaderMTOMAware;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,parentQName){
public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
DeleteSecurityGroupResponseType.this.serialize(parentQName,factory,xmlWriter);
}
};
return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl(
parentQName,factory,dataSource);
}
public void serialize(final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory,
org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,factory,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory,
org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
if ((namespace != null) && (namespace.trim().length() > 0)) {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, parentQName.getLocalPart());
} else {
if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
} else {
xmlWriter.writeStartElement(parentQName.getLocalPart());
}
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2012-08-15/");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":DeleteSecurityGroupResponseType",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"DeleteSecurityGroupResponseType",
xmlWriter);
}
}
namespace = "http://ec2.amazonaws.com/doc/2012-08-15/";
if (! namespace.equals("")) {
prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
xmlWriter.writeStartElement(prefix,"requestId", namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
} else {
xmlWriter.writeStartElement(namespace,"requestId");
}
} else {
xmlWriter.writeStartElement("requestId");
}
if (localRequestId==null){
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("requestId cannot be null!!");
}else{
xmlWriter.writeCharacters(localRequestId);
}
xmlWriter.writeEndElement();
namespace = "http://ec2.amazonaws.com/doc/2012-08-15/";
if (! namespace.equals("")) {
prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
xmlWriter.writeStartElement(prefix,"return", namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
} else {
xmlWriter.writeStartElement(namespace,"return");
}
} else {
xmlWriter.writeStartElement("return");
}
if (false) {
throw new org.apache.axis2.databinding.ADBException("return cannot be null!!");
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(local_return));
}
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals(""))
{
xmlWriter.writeAttribute(attName,attValue);
}
else
{
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) {
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/",
"requestId"));
if (localRequestId != null){
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localRequestId));
} else {
throw new org.apache.axis2.databinding.ADBException("requestId cannot be null!!");
}
elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/",
"return"));
elementList.add(
org.apache.axis2.databinding.utils.ConverterUtil.convertToString(local_return));
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static DeleteSecurityGroupResponseType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
DeleteSecurityGroupResponseType object =
new DeleteSecurityGroupResponseType();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"DeleteSecurityGroupResponseType".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (DeleteSecurityGroupResponseType)com.amazon.ec2.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","requestId").equals(reader.getName())){
java.lang.String content = reader.getElementText();
object.setRequestId(
org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","return").equals(reader.getName())){
java.lang.String content = reader.getElementText();
object.set_return(
org.apache.axis2.databinding.utils.ConverterUtil.convertToBoolean(content));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.instance;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.executiongraph.Execution;
import org.apache.flink.runtime.jobmanager.scheduler.ScheduledUnit;
import org.apache.flink.runtime.jobmanager.slots.AllocatedSlot;
import org.apache.flink.runtime.jobmanager.slots.TaskManagerGateway;
import org.apache.flink.runtime.jobmaster.JobMasterId;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.resourcemanager.ResourceManagerGateway;
import org.apache.flink.runtime.resourcemanager.SlotRequest;
import org.apache.flink.runtime.resourcemanager.utils.TestingResourceManagerGateway;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.RpcUtils;
import org.apache.flink.runtime.rpc.TestingRpcService;
import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.TestLogger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static org.apache.flink.runtime.instance.AvailableSlotsTest.DEFAULT_TESTING_PROFILE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.RETURNS_MOCKS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class SlotPoolTest extends TestLogger {
private static final Logger LOG = LoggerFactory.getLogger(SlotPoolTest.class);
private final Time timeout = Time.seconds(10L);
private RpcService rpcService;
private JobID jobId;
@Before
public void setUp() throws Exception {
this.rpcService = new TestingRpcService();
this.jobId = new JobID();
}
@After
public void tearDown() throws Exception {
rpcService.stopService();
}
@Test
public void testAllocateSimpleSlot() throws Exception {
ResourceManagerGateway resourceManagerGateway = createResourceManagerGatewayMock();
final SlotPool slotPool = new SlotPool(rpcService, jobId);
try {
SlotPoolGateway slotPoolGateway = setupSlotPool(slotPool, resourceManagerGateway);
ResourceID resourceID = new ResourceID("resource");
slotPoolGateway.registerTaskManager(resourceID);
SlotPoolGateway.SlotRequestID requestId = new SlotPoolGateway.SlotRequestID();
CompletableFuture<SimpleSlot> future = slotPoolGateway.allocateSlot(requestId, mock(ScheduledUnit.class), DEFAULT_TESTING_PROFILE, null, timeout);
assertFalse(future.isDone());
ArgumentCaptor<SlotRequest> slotRequestArgumentCaptor = ArgumentCaptor.forClass(SlotRequest.class);
verify(resourceManagerGateway, Mockito.timeout(timeout.toMilliseconds())).requestSlot(any(JobMasterId.class), slotRequestArgumentCaptor.capture(), any(Time.class));
final SlotRequest slotRequest = slotRequestArgumentCaptor.getValue();
AllocatedSlot allocatedSlot = createAllocatedSlot(resourceID, slotRequest.getAllocationId(), jobId, DEFAULT_TESTING_PROFILE);
assertTrue(slotPoolGateway.offerSlot(allocatedSlot).get());
SimpleSlot slot = future.get(1, TimeUnit.SECONDS);
assertTrue(future.isDone());
assertTrue(slot.isAlive());
assertEquals(resourceID, slot.getTaskManagerID());
assertEquals(jobId, slot.getJobID());
assertEquals(slotPool.getSlotOwner(), slot.getOwner());
assertEquals(slotPool.getAllocatedSlots().get(slot.getAllocatedSlot().getSlotAllocationId()), slot);
} finally {
slotPool.shutDown();
}
}
@Test
public void testAllocationFulfilledByReturnedSlot() throws Exception {
ResourceManagerGateway resourceManagerGateway = createResourceManagerGatewayMock();
final SlotPool slotPool = new SlotPool(rpcService, jobId);
try {
SlotPoolGateway slotPoolGateway = setupSlotPool(slotPool, resourceManagerGateway);
ResourceID resourceID = new ResourceID("resource");
slotPool.registerTaskManager(resourceID);
CompletableFuture<SimpleSlot> future1 = slotPoolGateway.allocateSlot(new SlotPoolGateway.SlotRequestID(), mock(ScheduledUnit.class), DEFAULT_TESTING_PROFILE, null, timeout);
CompletableFuture<SimpleSlot> future2 = slotPoolGateway.allocateSlot(new SlotPoolGateway.SlotRequestID(), mock(ScheduledUnit.class), DEFAULT_TESTING_PROFILE, null, timeout);
assertFalse(future1.isDone());
assertFalse(future2.isDone());
ArgumentCaptor<SlotRequest> slotRequestArgumentCaptor = ArgumentCaptor.forClass(SlotRequest.class);
verify(resourceManagerGateway, Mockito.timeout(timeout.toMilliseconds()).times(2))
.requestSlot(any(JobMasterId.class), slotRequestArgumentCaptor.capture(), any(Time.class));
final List<SlotRequest> slotRequests = slotRequestArgumentCaptor.getAllValues();
AllocatedSlot allocatedSlot = createAllocatedSlot(resourceID, slotRequests.get(0).getAllocationId(), jobId, DEFAULT_TESTING_PROFILE);
assertTrue(slotPoolGateway.offerSlot(allocatedSlot).get());
SimpleSlot slot1 = future1.get(1, TimeUnit.SECONDS);
assertTrue(future1.isDone());
assertFalse(future2.isDone());
// return this slot to pool
slot1.releaseSlot();
// second allocation fulfilled by previous slot returning
SimpleSlot slot2 = future2.get(1, TimeUnit.SECONDS);
assertTrue(future2.isDone());
assertNotEquals(slot1, slot2);
assertTrue(slot1.isReleased());
assertTrue(slot2.isAlive());
assertEquals(slot1.getTaskManagerID(), slot2.getTaskManagerID());
assertEquals(slot1.getSlotNumber(), slot2.getSlotNumber());
assertEquals(slotPool.getAllocatedSlots().get(slot1.getAllocatedSlot().getSlotAllocationId()), slot2);
} finally {
slotPool.shutDown();
}
}
@Test
public void testAllocateWithFreeSlot() throws Exception {
ResourceManagerGateway resourceManagerGateway = createResourceManagerGatewayMock();
final SlotPool slotPool = new SlotPool(rpcService, jobId);
try {
SlotPoolGateway slotPoolGateway = setupSlotPool(slotPool, resourceManagerGateway);
ResourceID resourceID = new ResourceID("resource");
slotPoolGateway.registerTaskManager(resourceID);
CompletableFuture<SimpleSlot> future1 = slotPoolGateway.allocateSlot(new SlotPoolGateway.SlotRequestID(), mock(ScheduledUnit.class), DEFAULT_TESTING_PROFILE, null, timeout);
assertFalse(future1.isDone());
ArgumentCaptor<SlotRequest> slotRequestArgumentCaptor = ArgumentCaptor.forClass(SlotRequest.class);
verify(resourceManagerGateway, Mockito.timeout(timeout.toMilliseconds())).requestSlot(any(JobMasterId.class), slotRequestArgumentCaptor.capture(), any(Time.class));
final SlotRequest slotRequest = slotRequestArgumentCaptor.getValue();
AllocatedSlot allocatedSlot = createAllocatedSlot(resourceID, slotRequest.getAllocationId(), jobId, DEFAULT_TESTING_PROFILE);
assertTrue(slotPoolGateway.offerSlot(allocatedSlot).get());
SimpleSlot slot1 = future1.get(1, TimeUnit.SECONDS);
assertTrue(future1.isDone());
// return this slot to pool
slot1.releaseSlot();
CompletableFuture<SimpleSlot> future2 = slotPoolGateway.allocateSlot(new SlotPoolGateway.SlotRequestID(), mock(ScheduledUnit.class), DEFAULT_TESTING_PROFILE, null, timeout);
// second allocation fulfilled by previous slot returning
SimpleSlot slot2 = future2.get(1, TimeUnit.SECONDS);
assertTrue(future2.isDone());
assertNotEquals(slot1, slot2);
assertTrue(slot1.isReleased());
assertTrue(slot2.isAlive());
assertEquals(slot1.getTaskManagerID(), slot2.getTaskManagerID());
assertEquals(slot1.getSlotNumber(), slot2.getSlotNumber());
} finally {
slotPool.shutDown();
}
}
@Test
public void testOfferSlot() throws Exception {
ResourceManagerGateway resourceManagerGateway = createResourceManagerGatewayMock();
final SlotPool slotPool = new SlotPool(rpcService, jobId);
try {
SlotPoolGateway slotPoolGateway = setupSlotPool(slotPool, resourceManagerGateway);
ResourceID resourceID = new ResourceID("resource");
slotPoolGateway.registerTaskManager(resourceID);
CompletableFuture<SimpleSlot> future = slotPoolGateway.allocateSlot(new SlotPoolGateway.SlotRequestID(), mock(ScheduledUnit.class), DEFAULT_TESTING_PROFILE, null, timeout);
assertFalse(future.isDone());
ArgumentCaptor<SlotRequest> slotRequestArgumentCaptor = ArgumentCaptor.forClass(SlotRequest.class);
verify(resourceManagerGateway, Mockito.timeout(timeout.toMilliseconds())).requestSlot(any(JobMasterId.class), slotRequestArgumentCaptor.capture(), any(Time.class));
final SlotRequest slotRequest = slotRequestArgumentCaptor.getValue();
// slot from unregistered resource
AllocatedSlot invalid = createAllocatedSlot(new ResourceID("unregistered"), slotRequest.getAllocationId(), jobId, DEFAULT_TESTING_PROFILE);
assertFalse(slotPoolGateway.offerSlot(invalid).get());
AllocatedSlot notRequested = createAllocatedSlot(resourceID, new AllocationID(), jobId, DEFAULT_TESTING_PROFILE);
// we'll also accept non requested slots
assertTrue(slotPoolGateway.offerSlot(notRequested).get());
AllocatedSlot allocatedSlot = createAllocatedSlot(resourceID, slotRequest.getAllocationId(), jobId, DEFAULT_TESTING_PROFILE);
// accepted slot
assertTrue(slotPoolGateway.offerSlot(allocatedSlot).get());
SimpleSlot slot = future.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
assertTrue(slot.isAlive());
// duplicated offer with using slot
assertTrue(slotPoolGateway.offerSlot(allocatedSlot).get());
assertTrue(slot.isAlive());
// duplicated offer with free slot
slot.releaseSlot();
assertTrue(slotPoolGateway.offerSlot(allocatedSlot).get());
} finally {
slotPool.shutDown();
}
}
@Test
public void testReleaseResource() throws Exception {
ResourceManagerGateway resourceManagerGateway = createResourceManagerGatewayMock();
final CompletableFuture<Boolean> slotReturnFuture = new CompletableFuture<>();
final SlotPool slotPool = new SlotPool(rpcService, jobId) {
@Override
public void returnAllocatedSlot(Slot slot) {
super.returnAllocatedSlot(slot);
slotReturnFuture.complete(true);
}
};
try {
SlotPoolGateway slotPoolGateway = setupSlotPool(slotPool, resourceManagerGateway);
ResourceID resourceID = new ResourceID("resource");
slotPoolGateway.registerTaskManager(resourceID);
CompletableFuture<SimpleSlot> future1 = slotPoolGateway.allocateSlot(new SlotPoolGateway.SlotRequestID(), mock(ScheduledUnit.class), DEFAULT_TESTING_PROFILE, null, timeout);
ArgumentCaptor<SlotRequest> slotRequestArgumentCaptor = ArgumentCaptor.forClass(SlotRequest.class);
verify(resourceManagerGateway, Mockito.timeout(timeout.toMilliseconds())).requestSlot(any(JobMasterId.class), slotRequestArgumentCaptor.capture(), any(Time.class));
final SlotRequest slotRequest = slotRequestArgumentCaptor.getValue();
CompletableFuture<SimpleSlot> future2 = slotPoolGateway.allocateSlot(new SlotPoolGateway.SlotRequestID(), mock(ScheduledUnit.class), DEFAULT_TESTING_PROFILE, null, timeout);
AllocatedSlot allocatedSlot = createAllocatedSlot(resourceID, slotRequest.getAllocationId(), jobId, DEFAULT_TESTING_PROFILE);
assertTrue(slotPoolGateway.offerSlot(allocatedSlot).get());
SimpleSlot slot1 = future1.get(1, TimeUnit.SECONDS);
assertTrue(future1.isDone());
assertFalse(future2.isDone());
slotPoolGateway.releaseTaskManager(resourceID);
// wait until the slot has been returned
slotReturnFuture.get();
assertTrue(slot1.isReleased());
// slot released and not usable, second allocation still not fulfilled
Thread.sleep(10);
assertFalse(future2.isDone());
} finally {
slotPool.shutDown();
}
}
/**
* Tests that a slot request is cancelled if it failed with an exception (e.g. TimeoutException).
*
* <p>See FLINK-7870
*/
@Test
public void testSlotRequestCancellationUponFailingRequest() throws Exception {
final SlotPool slotPool = new SlotPool(rpcService, jobId);
final CompletableFuture<Acknowledge> requestSlotFuture = new CompletableFuture<>();
final CompletableFuture<AllocationID> cancelSlotFuture = new CompletableFuture<>();
final CompletableFuture<AllocationID> requestSlotFutureAllocationId = new CompletableFuture<>();
final TestingResourceManagerGateway resourceManagerGateway = new TestingResourceManagerGateway();
resourceManagerGateway.setRequestSlotFuture(requestSlotFuture);
resourceManagerGateway.setRequestSlotConsumer(slotRequest -> requestSlotFutureAllocationId.complete(slotRequest.getAllocationId()));
resourceManagerGateway.setCancelSlotConsumer(allocationID -> cancelSlotFuture.complete(allocationID));
final ScheduledUnit scheduledUnit = new ScheduledUnit(mock(Execution.class));
try {
slotPool.start(JobMasterId.generate(), "localhost");
final SlotPoolGateway slotPoolGateway = slotPool.getSelfGateway(SlotPoolGateway.class);
slotPoolGateway.connectToResourceManager(resourceManagerGateway);
CompletableFuture<SimpleSlot> slotFuture = slotPoolGateway.allocateSlot(
new SlotPoolGateway.SlotRequestID(),
scheduledUnit,
ResourceProfile.UNKNOWN,
Collections.emptyList(),
timeout);
requestSlotFuture.completeExceptionally(new FlinkException("Testing exception."));
try {
slotFuture.get();
fail("The slot future should not have been completed properly.");
} catch (Exception ignored) {
// expected
}
// check that a failure triggered the slot request cancellation
// with the correct allocation id
assertEquals(requestSlotFutureAllocationId.get(), cancelSlotFuture.get());
} finally {
try {
RpcUtils.terminateRpcEndpoint(slotPool, timeout);
} catch (Exception e) {
LOG.warn("Could not properly terminate the SlotPool.", e);
}
}
}
private static ResourceManagerGateway createResourceManagerGatewayMock() {
ResourceManagerGateway resourceManagerGateway = mock(ResourceManagerGateway.class);
when(resourceManagerGateway
.requestSlot(any(JobMasterId.class), any(SlotRequest.class), any(Time.class)))
.thenReturn(mock(CompletableFuture.class, RETURNS_MOCKS));
return resourceManagerGateway;
}
private static SlotPoolGateway setupSlotPool(
SlotPool slotPool,
ResourceManagerGateway resourceManagerGateway) throws Exception {
final String jobManagerAddress = "foobar";
slotPool.start(JobMasterId.generate(), jobManagerAddress);
slotPool.connectToResourceManager(resourceManagerGateway);
return slotPool.getSelfGateway(SlotPoolGateway.class);
}
static AllocatedSlot createAllocatedSlot(
final ResourceID resourceId,
final AllocationID allocationId,
final JobID jobId,
final ResourceProfile resourceProfile) {
TaskManagerLocation mockTaskManagerLocation = mock(TaskManagerLocation.class);
when(mockTaskManagerLocation.getResourceID()).thenReturn(resourceId);
TaskManagerGateway mockTaskManagerGateway = mock(TaskManagerGateway.class);
return new AllocatedSlot(
allocationId,
jobId,
mockTaskManagerLocation,
0,
resourceProfile,
mockTaskManagerGateway);
}
}
|
|
/*
* 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.zeppelin.interpreter;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.zeppelin.dep.Dependency;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.internal.StringMap;
import static org.apache.zeppelin.notebook.utility.IdHashes.generateId;
/**
* Interpreter settings
*/
public class InterpreterSetting {
private static final Logger logger = LoggerFactory.getLogger(InterpreterSetting.class);
private static final String SHARED_PROCESS = "shared_process";
private String id;
private String name;
// always be null in case of InterpreterSettingRef
private String group;
private transient Map<String, String> infos;
// Map of the note and paragraphs which has runtime infos generated by this interpreter setting.
// This map is used to clear the infos in paragraph when the interpretersetting is restarted
private transient Map<String, Set<String>> runtimeInfosToBeCleared;
/**
* properties can be either Map<String, DefaultInterpreterProperty> or
* Map<String, InterpreterProperty>
* properties should be:
* - Map<String, InterpreterProperty> when Interpreter instances are saved to
* `conf/interpreter.json` file
* - Map<String, DefaultInterpreterProperty> when Interpreters are registered
* : this is needed after https://github.com/apache/zeppelin/pull/1145
* which changed the way of getting default interpreter setting AKA interpreterSettingsRef
*/
private Object properties;
private Status status;
private String errorReason;
@SerializedName("interpreterGroup")
private List<InterpreterInfo> interpreterInfos;
private final transient Map<String, InterpreterGroup> interpreterGroupRef = new HashMap<>();
private List<Dependency> dependencies = new LinkedList<>();
private InterpreterOption option;
private transient String path;
@SerializedName("runner")
private InterpreterRunner interpreterRunner;
@Deprecated
private transient InterpreterGroupFactory interpreterGroupFactory;
private final transient ReentrantReadWriteLock.ReadLock interpreterGroupReadLock;
private final transient ReentrantReadWriteLock.WriteLock interpreterGroupWriteLock;
public InterpreterSetting() {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
interpreterGroupReadLock = lock.readLock();
interpreterGroupWriteLock = lock.writeLock();
}
public InterpreterSetting(String id, String name, String group,
List<InterpreterInfo> interpreterInfos, Object properties, List<Dependency> dependencies,
InterpreterOption option, String path, InterpreterRunner runner) {
this();
this.id = id;
this.name = name;
this.group = group;
this.interpreterInfos = interpreterInfos;
this.properties = properties;
this.dependencies = dependencies;
this.option = option;
this.path = path;
this.status = Status.READY;
this.interpreterRunner = runner;
}
public InterpreterSetting(String name, String group, List<InterpreterInfo> interpreterInfos,
Object properties, List<Dependency> dependencies, InterpreterOption option, String path,
InterpreterRunner runner) {
this(generateId(), name, group, interpreterInfos, properties, dependencies, option, path,
runner);
}
/**
* Create interpreter from interpreterSettingRef
*
* @param o interpreterSetting from interpreterSettingRef
*/
public InterpreterSetting(InterpreterSetting o) {
this(generateId(), o.getName(), o.getGroup(), o.getInterpreterInfos(), o.getProperties(),
o.getDependencies(), o.getOption(), o.getPath(), o.getInterpreterRunner());
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getGroup() {
return group;
}
private String getInterpreterProcessKey(String user, String noteId) {
InterpreterOption option = getOption();
String key;
if (getOption().isExistingProcess) {
key = Constants.EXISTING_PROCESS;
} else if (getOption().isProcess()) {
key = (option.perUserIsolated() ? user : "") + ":" + (option.perNoteIsolated() ? noteId : "");
} else {
key = SHARED_PROCESS;
}
//logger.debug("getInterpreterProcessKey: {} for InterpreterSetting Id: {}, Name: {}",
// key, getId(), getName());
return key;
}
private boolean isEqualInterpreterKeyProcessKey(String refKey, String processKey) {
InterpreterOption option = getOption();
int validCount = 0;
if (getOption().isProcess()
&& !(option.perUserIsolated() == true && option.perNoteIsolated() == true)) {
List<String> processList = Arrays.asList(processKey.split(":"));
List<String> refList = Arrays.asList(refKey.split(":"));
if (refList.size() <= 1 || processList.size() <= 1) {
return refKey.equals(processKey);
}
if (processList.get(0).equals("") || processList.get(0).equals(refList.get(0))) {
validCount = validCount + 1;
}
if (processList.get(1).equals("") || processList.get(1).equals(refList.get(1))) {
validCount = validCount + 1;
}
return (validCount >= 2);
} else {
return refKey.equals(processKey);
}
}
String getInterpreterSessionKey(String user, String noteId) {
InterpreterOption option = getOption();
String key;
if (option.isExistingProcess()) {
key = Constants.EXISTING_PROCESS;
} else if (option.perNoteScoped() && option.perUserScoped()) {
key = user + ":" + noteId;
} else if (option.perUserScoped()) {
key = user;
} else if (option.perNoteScoped()) {
key = noteId;
} else {
key = "shared_session";
}
logger.debug("Interpreter session key: {}, for note: {}, user: {}, InterpreterSetting Name: " +
"{}", key, noteId, user, getName());
return key;
}
public InterpreterGroup getInterpreterGroup(String user, String noteId) {
String key = getInterpreterProcessKey(user, noteId);
if (!interpreterGroupRef.containsKey(key)) {
String interpreterGroupId = getId() + ":" + key;
InterpreterGroup intpGroup =
interpreterGroupFactory.createInterpreterGroup(interpreterGroupId, getOption());
interpreterGroupWriteLock.lock();
logger.debug("create interpreter group with groupId:" + interpreterGroupId);
interpreterGroupRef.put(key, intpGroup);
interpreterGroupWriteLock.unlock();
}
try {
interpreterGroupReadLock.lock();
return interpreterGroupRef.get(key);
} finally {
interpreterGroupReadLock.unlock();
}
}
public Collection<InterpreterGroup> getAllInterpreterGroups() {
try {
interpreterGroupReadLock.lock();
return new LinkedList<>(interpreterGroupRef.values());
} finally {
interpreterGroupReadLock.unlock();
}
}
void closeAndRemoveInterpreterGroup(String noteId, String user) {
if (user.equals("anonymous")) {
user = "";
}
String processKey = getInterpreterProcessKey(user, noteId);
String sessionKey = getInterpreterSessionKey(user, noteId);
List<InterpreterGroup> groupToRemove = new LinkedList<>();
InterpreterGroup groupItem;
for (String intpKey : new HashSet<>(interpreterGroupRef.keySet())) {
if (isEqualInterpreterKeyProcessKey(intpKey, processKey)) {
interpreterGroupWriteLock.lock();
// TODO(jl): interpreterGroup has two or more sessionKeys inside it. thus we should not
// remove interpreterGroup if it has two or more values.
groupItem = interpreterGroupRef.get(intpKey);
interpreterGroupWriteLock.unlock();
groupToRemove.add(groupItem);
}
for (InterpreterGroup groupToClose : groupToRemove) {
// TODO(jl): Fix the logic removing session. Now, it's handled into groupToClose.clsose()
groupToClose.close(interpreterGroupRef, intpKey, sessionKey);
}
groupToRemove.clear();
}
//Remove session because all interpreters in this session are closed
//TODO(jl): Change all code to handle interpreter one by one or all at once
}
void closeAndRemoveAllInterpreterGroups() {
for (String processKey : new HashSet<>(interpreterGroupRef.keySet())) {
InterpreterGroup interpreterGroup = interpreterGroupRef.get(processKey);
for (String sessionKey : new HashSet<>(interpreterGroup.keySet())) {
interpreterGroup.close(interpreterGroupRef, processKey, sessionKey);
}
}
}
void shutdownAndRemoveAllInterpreterGroups() {
for (InterpreterGroup interpreterGroup : interpreterGroupRef.values()) {
interpreterGroup.shutdown();
}
}
public Object getProperties() {
return properties;
}
public Properties getFlatProperties() {
Properties p = new Properties();
if (properties != null) {
Map<String, InterpreterProperty> propertyMap = (Map<String, InterpreterProperty>) properties;
for (String key : propertyMap.keySet()) {
InterpreterProperty tmp = propertyMap.get(key);
p.put(tmp.getName() != null ? tmp.getName() : key,
tmp.getValue() != null ? tmp.getValue().toString() : null);
}
}
return p;
}
public List<Dependency> getDependencies() {
if (dependencies == null) {
return new LinkedList<>();
}
return dependencies;
}
public void setDependencies(List<Dependency> dependencies) {
this.dependencies = dependencies;
}
public InterpreterOption getOption() {
if (option == null) {
option = new InterpreterOption();
}
return option;
}
public void setOption(InterpreterOption option) {
this.option = option;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<InterpreterInfo> getInterpreterInfos() {
return interpreterInfos;
}
void setInterpreterGroupFactory(InterpreterGroupFactory interpreterGroupFactory) {
this.interpreterGroupFactory = interpreterGroupFactory;
}
void appendDependencies(List<Dependency> dependencies) {
for (Dependency dependency : dependencies) {
if (!this.dependencies.contains(dependency)) {
this.dependencies.add(dependency);
}
}
}
void setInterpreterOption(InterpreterOption interpreterOption) {
this.option = interpreterOption;
}
public void setProperties(Map<String, InterpreterProperty> p) {
this.properties = p;
}
void setGroup(String group) {
this.group = group;
}
void setName(String name) {
this.name = name;
}
/***
* Interpreter status
*/
public enum Status {
DOWNLOADING_DEPENDENCIES,
ERROR,
READY
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getErrorReason() {
return errorReason;
}
public void setErrorReason(String errorReason) {
this.errorReason = errorReason;
}
public void setInfos(Map<String, String> infos) {
this.infos = infos;
}
public Map<String, String> getInfos() {
return infos;
}
public InterpreterRunner getInterpreterRunner() {
return interpreterRunner;
}
public void setInterpreterRunner(InterpreterRunner interpreterRunner) {
this.interpreterRunner = interpreterRunner;
}
public void addNoteToPara(String noteId, String paraId) {
if (runtimeInfosToBeCleared == null) {
runtimeInfosToBeCleared = new HashMap<>();
}
Set<String> paraIdSet = runtimeInfosToBeCleared.get(noteId);
if (paraIdSet == null) {
paraIdSet = new HashSet<>();
runtimeInfosToBeCleared.put(noteId, paraIdSet);
}
paraIdSet.add(paraId);
}
public Map<String, Set<String>> getNoteIdAndParaMap() {
return runtimeInfosToBeCleared;
}
public void clearNoteIdAndParaMap() {
runtimeInfosToBeCleared = null;
}
// For backward compatibility of interpreter.json format after ZEPPELIN-2654
public void convertPermissionsFromUsersToOwners(JsonObject jsonObject) {
if (jsonObject != null) {
JsonObject option = jsonObject.getAsJsonObject("option");
if (option != null) {
JsonArray users = option.getAsJsonArray("users");
if (users != null) {
if (this.option.getOwners() == null) {
this.option.owners = new LinkedList<>();
}
for (JsonElement user : users) {
this.option.getOwners().add(user.getAsString());
}
}
}
}
}
// For backward compatibility of interpreter.json format after ZEPPELIN-2403
public void convertFlatPropertiesToPropertiesWithWidgets() {
StringMap newProperties = new StringMap();
if (properties != null && properties instanceof StringMap) {
StringMap p = (StringMap) properties;
for (Object o : p.entrySet()) {
Map.Entry entry = (Map.Entry) o;
if (!(entry.getValue() instanceof StringMap)) {
StringMap newProperty = new StringMap();
newProperty.put("name", entry.getKey());
newProperty.put("value", entry.getValue());
newProperty.put("type", InterpreterPropertyType.TEXTAREA.getValue());
newProperties.put(entry.getKey().toString(), newProperty);
} else {
// already converted
return;
}
}
this.properties = newProperties;
}
}
}
|
|
/*
* Copyright 2002-2019 Drew Noakes and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
package com.drew.metadata.exif.makernotes;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
import com.drew.metadata.TagDescriptor;
import static com.drew.metadata.exif.makernotes.SamsungType2MakernoteDirectory.*;
/**
* Provides human-readable string representations of tag values stored in a {@link SamsungType2MakernoteDirectory}.
* <p>
* Tag reference from: http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Samsung.html
*
* @author Kevin Mott https://github.com/kwhopper
* @author Drew Noakes https://drewnoakes.com
*/
@SuppressWarnings("WeakerAccess")
public class SamsungType2MakernoteDescriptor extends TagDescriptor<SamsungType2MakernoteDirectory>
{
public SamsungType2MakernoteDescriptor(@NotNull SamsungType2MakernoteDirectory directory)
{
super(directory);
}
@Override
@Nullable
public String getDescription(int tagType)
{
switch (tagType) {
case TagMakerNoteVersion:
return getMakernoteVersionDescription();
case TagDeviceType:
return getDeviceTypeDescription();
case TagSamsungModelId:
return getSamsungModelIdDescription();
case TagRawDataByteOrder:
return getRawDataByteOrderDescription();
case TagWhiteBalanceSetup:
return getWhiteBalanceSetupDescription();
case TagCameraTemperature:
return getCameraTemperatureDescription();
case TagRawDataCFAPattern:
return getRawDataCFAPatternDescription();
case TagFaceDetect:
return getFaceDetectDescription();
case TagFaceRecognition:
return getFaceRecognitionDescription();
case TagLensType:
return getLensTypeDescription();
case TagColorSpace:
return getColorSpaceDescription();
case TagSmartRange:
return getSmartRangeDescription();
default:
return super.getDescription(tagType);
}
}
@Nullable
public String getMakernoteVersionDescription()
{
return getVersionBytesDescription(TagMakerNoteVersion, 2);
}
@Nullable
public String getDeviceTypeDescription()
{
Integer value = _directory.getInteger(TagDeviceType);
if (value == null)
return null;
switch (value)
{
case 0x1000:
return "Compact Digital Camera";
case 0x2000:
return "High-end NX Camera";
case 0x3000:
return "HXM Video Camera";
case 0x12000:
return "Cell Phone";
case 0x300000:
return "SMX Video Camera";
default:
return String.format("Unknown (%d)", value);
}
}
@Nullable
public String getSamsungModelIdDescription()
{
Integer value = _directory.getInteger(TagSamsungModelId);
if (value == null)
return null;
switch (value)
{
case 0x100101c:
return "NX10";
/*case 0x1001226:
return "HMX-S10BP";*/
case 0x1001226:
return "HMX-S15BP";
case 0x1001233:
return "HMX-Q10";
/*case 0x1001234:
return "HMX-H300";*/
case 0x1001234:
return "HMX-H304";
case 0x100130c:
return "NX100";
case 0x1001327:
return "NX11";
case 0x170104e:
return "ES70, ES71 / VLUU ES70, ES71 / SL600";
case 0x1701052:
return "ES73 / VLUU ES73 / SL605";
case 0x1701300:
return "ES28 / VLUU ES28";
case 0x1701303:
return "ES74,ES75,ES78 / VLUU ES75,ES78";
case 0x2001046:
return "PL150 / VLUU PL150 / TL210 / PL151";
case 0x2001311:
return "PL120,PL121 / VLUU PL120,PL121";
case 0x2001315:
return "PL170,PL171 / VLUUPL170,PL171";
case 0x200131e:
return "PL210, PL211 / VLUU PL210, PL211";
case 0x2701317:
return "PL20,PL21 / VLUU PL20,PL21";
case 0x2a0001b:
return "WP10 / VLUU WP10 / AQ100";
case 0x3000000:
return "Various Models (0x3000000)";
case 0x3a00018:
return "Various Models (0x3a00018)";
case 0x400101f:
return "ST1000 / ST1100 / VLUU ST1000 / CL65";
case 0x4001022:
return "ST550 / VLUU ST550 / TL225";
case 0x4001025:
return "Various Models (0x4001025)";
case 0x400103e:
return "VLUU ST5500, ST5500, CL80";
case 0x4001041:
return "VLUU ST5000, ST5000, TL240";
case 0x4001043:
return "ST70 / VLUU ST70 / ST71";
case 0x400130a:
return "Various Models (0x400130a)";
case 0x400130e:
return "ST90,ST91 / VLUU ST90,ST91";
case 0x4001313:
return "VLUU ST95, ST95";
case 0x4a00015:
return "VLUU ST60";
case 0x4a0135b:
return "ST30, ST65 / VLUU ST65 / ST67";
case 0x5000000:
return "Various Models (0x5000000)";
case 0x5001038:
return "Various Models (0x5001038)";
case 0x500103a:
return "WB650 / VLUU WB650 / WB660";
case 0x500103c:
return "WB600 / VLUU WB600 / WB610";
case 0x500133e:
return "WB150 / WB150F / WB152 / WB152F / WB151";
case 0x5a0000f:
return "WB5000 / HZ25W";
case 0x6001036:
return "EX1";
case 0x700131c:
return "VLUU SH100, SH100";
case 0x27127002:
return "SMX - C20N";
default:
return String.format("Unknown (%d)", value);
}
}
@Nullable
public String getRawDataByteOrderDescription()
{
return getIndexedDescription(TagRawDataByteOrder,
"Little-endian (Intel)", "Big-endian (Motorola)");
}
@Nullable
public String getWhiteBalanceSetupDescription()
{
return getIndexedDescription(TagWhiteBalanceSetup,
"Auto", "Manual");
}
@Nullable
public String getCameraTemperatureDescription()
{
return getFormattedInt(TagCameraTemperature, "%d C");
}
@Nullable
public String getRawDataCFAPatternDescription()
{
Integer value = _directory.getInteger(TagRawDataCFAPattern);
if (value == null)
return null;
switch (value) {
case 0: return "Unchanged";
case 1: return "Swap";
case 65535: return "Roll";
default: return String.format("Unknown (%d)", value);
}
}
@Nullable
public String getFaceDetectDescription()
{
return getIndexedDescription(TagFaceDetect,
"Off", "On");
}
@Nullable
public String getFaceRecognitionDescription()
{
return getIndexedDescription(TagFaceRecognition,
"Off", "On");
}
@Nullable
public String getLensTypeDescription()
{
return getIndexedDescription(TagLensType,
"Built-in or Manual Lens",
"Samsung NX 30mm F2 Pancake",
"Samsung NX 18-55mm F3.5-5.6 OIS",
"Samsung NX 50-200mm F4-5.6 ED OIS",
"Samsung NX 20-50mm F3.5-5.6 ED",
"Samsung NX 20mm F2.8 Pancake",
"Samsung NX 18-200mm F3.5-6.3 ED OIS",
"Samsung NX 60mm F2.8 Macro ED OIS SSA",
"Samsung NX 16mm F2.4 Pancake",
"Samsung NX 85mm F1.4 ED SSA",
"Samsung NX 45mm F1.8",
"Samsung NX 45mm F1.8 2D/3D",
"Samsung NX 12-24mm F4-5.6 ED",
"Samsung NX 16-50mm F2-2.8 S ED OIS",
"Samsung NX 10mm F3.5 Fisheye",
"Samsung NX 16-50mm F3.5-5.6 Power Zoom ED OIS",
null,
null,
null,
null,
"Samsung NX 50-150mm F2.8 S ED OIS",
"Samsung NX 300mm F2.8 ED OIS");
}
@Nullable
public String getColorSpaceDescription()
{
return getIndexedDescription(TagColorSpace,
"sRGB", "Adobe RGB");
}
@Nullable
public String getSmartRangeDescription()
{
return getIndexedDescription(TagSmartRange,
"Off", "On");
}
}
|
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yunos.alicontacts.appwidget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.IBinder;
import android.provider.CallLog.Calls;
import android.telephony.PhoneNumberUtils;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.yunos.alicontacts.ContactsApplication;
import com.yunos.alicontacts.ContactsUtils;
import com.yunos.alicontacts.R;
import com.yunos.alicontacts.database.CallLogManager;
import com.yunos.alicontacts.dialpad.calllog.AliCallLogExtensionHelper;
import com.yunos.alicontacts.dialpad.calllog.CallLogQueryHandler;
import com.yunos.alicontacts.dialpad.calllog.CallLogReceiver;
import com.yunos.alicontacts.dialpad.calllog.CallerViewQuery;
import com.yunos.alicontacts.dialpad.calllog.ContactInfo;
import com.yunos.alicontacts.dialpad.calllog.ContactInfoHelper;
import com.yunos.alicontacts.sim.SimUtil;
import com.yunos.alicontacts.util.AliTextUtils;
import com.yunos.alicontacts.util.FeatureOptionAssistant;
import java.util.ArrayList;
public class GadgetCallLogService extends RemoteViewsService {
private static final String TAG = "GadgetCallLogService";
private static final boolean DEBUG = true;
private static final long ONE_MINUTE = 60 * 1000;
public static final String TAG_DIVIDER = " | ";
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
if (DEBUG) Log.d(TAG, "service in onGetViewFactory");
return new ListRemoteViewsFactory(getApplicationContext(), intent);
}
@Override
public void onCreate() {
if (DEBUG) Log.d(TAG, "service in onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
if (DEBUG) Log.d(TAG, "service in onDestory");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
if (DEBUG) Log.d(TAG, "service in onBind");
return super.onBind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
if (DEBUG) Log.d(TAG, "service in onUnbind");
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
if (DEBUG) Log.d(TAG, "service in onRebind");
super.onRebind(intent);
}
@Override
public int onStartCommand(Intent intent, int flags,int startId) {
if (DEBUG) Log.d(TAG, "service in onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
public static class ListRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory, CallLogQueryHandler.Listener {
private Context mContext;
private Intent mIntent;
private CallLogManager mCallLogManager;
private AliCallLogChangeListener mCallLogListener;
private CallLogQueryHandler mCallLogQueryHandler;
private ArrayList<CallLogInfo> mCallLogCache = new ArrayList<CallLogInfo>();
private final ContactInfoHelper mContactInfoHelper;
private String mRingTimeFormat;
private String mCallLogTimeJustnow;
private int mRedToWhiteColor;
private int mBlackToWhiteColor;
private int mGreyToWhiteColor;
StringBuilder mStringBuilderTmp = new StringBuilder(128);
/**
* Instantiated by RemoteViewsService.onGetViewFactory
*/
protected ListRemoteViewsFactory(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "Factory ListRemoteViewsFactory() : " + intent);
mContext = context;
mContactInfoHelper = ContactInfoHelper.getInstance(mContext);
mIntent = intent;
}
private class AliCallLogChangeListener implements CallLogManager.CallLogChangeListener {
@Override
public void onCallLogChange(int changedPart) {
Log.d(TAG, "Factory AliCallLogChangeListener onCallLogChange");
startCallsQuery(mContext);
}
}
@Override
public void onCreate() {
Log.d(TAG, "Factory onCreate()");
mCallLogManager = CallLogManager.getInstance(mContext);
mCallLogManager.requestSyncCalllogsByInit();
mCallLogListener = new AliCallLogChangeListener();
mCallLogManager.registCallsTableChangeListener(mCallLogListener);
mCallLogQueryHandler = new CallLogQueryHandler(ListRemoteViewsFactory.this);
int listType = mIntent == null ?
-1 : mIntent.getIntExtra(GadgetProvider.EXTRA_LIST_TYPE, -1);
boolean showMissed = (listType == GadgetProvider.EXTRA_LIST_TYPE_MISSED);
startCallsQuery(showMissed);
Resources resources = mContext.getResources();
initFormatString(resources);
initFontColor(resources);
}
@Override
public void onDataSetChanged() {
if (DEBUG) Log.d(TAG, "Factory onDataSetChanged()");
}
@Override
public void onDestroy() {
if (DEBUG) Log.d(TAG, "Factory onDestroy()");
mCallLogManager.unRegistCallsTableChangeListener(mCallLogListener);
synchronized (mCallLogCache) {
mCallLogCache.clear();
}
final Intent intentClear = new Intent(CallLogReceiver.ACTION_CLEAR_ALL_MISSED_CALLS);
intentClear.setClass(mContext, CallLogReceiver.class);
mContext.sendBroadcast(intentClear);
}
@Override
public RemoteViews getLoadingView() {
if (DEBUG) Log.d(TAG, "Factory getLoadingView()");
RemoteViews views = new RemoteViews(mContext.getPackageName(),
R.layout.gadget_loading);
ContactsApplication.overlayDyncColorResIfSupport(views);
return views;
}
@Override
public RemoteViews getViewAt(int position) {
if (DEBUG) Log.d(TAG, "Factory getViewAt() " + position);
CallLogInfo callLoginfo;
synchronized (mCallLogCache) {
if (mCallLogCache.size() == 0) {
Log.e(TAG, "Factory getViewAt() NO Data");
return null;
}
if (position < 0 || position >= getCount()) {
Log.e(TAG, "Factory getViewAt() invalid position:" + position);
return null;
}
callLoginfo = mCallLogCache.get(position);
}
String pkgName = mContext.getPackageName();
RemoteViews views = new RemoteViews(pkgName, R.layout.gadget_calllog_item_view);
ContactsApplication.overlayDyncColorResIfSupport(views);
if (position == 0) {
views.setViewVisibility(R.id.top_divider, View.INVISIBLE);
} else {
views.setViewVisibility(R.id.top_divider, View.VISIBLE);
}
int simId = -1;
if (SimUtil.MULTISIM_ENABLE) {
int subId = callLoginfo.subId;
simId = SimUtil.getSlotId(subId);
}
String number = callLoginfo.number;
final int type = callLoginfo.type;
final int features = callLoginfo.features;
long date = callLoginfo.date;
String countryIso = callLoginfo.countryIso;
/**
* Bug:5322921. APR Null Exception. Avoid exception when number is null
* in very special case.
*/
if (number == null) {
number = "";
Log.w(TAG, "getViewAt: ## call number from callog is null!!! CallID = " + callLoginfo.callId);
}
final String formatNumber = ContactsUtils.formatPhoneNumberWithCurrentCountryIso(number, mContext);
final ContactInfo localCallsContactInfo = getContactInfoFromCallLog(callLoginfo);
final ContactInfo cachedContactInfo = mContactInfoHelper.getAndCacheContactInfo(
number, countryIso, localCallsContactInfo);
boolean isStrange = false;
String labelAndNumberString = "";
String nameStr = "";
String contactName = cachedContactInfo.name;
String ypName = callLoginfo.ypName;
String province = callLoginfo.province;
String area = callLoginfo.area;
String location = AliTextUtils.makeLocation(province, area);
boolean isYP = !TextUtils.isEmpty(ypName);
if (TextUtils.isEmpty(contactName)) {
if (isYP) {
nameStr = ypName;
if (TextUtils.isEmpty(location)) {
labelAndNumberString = formatNumber;
} else {
mStringBuilderTmp.setLength(0);
if (!FeatureOptionAssistant.isInternationalSupportted()) {
mStringBuilderTmp.append(formatNumber).append(' ').append(location);
} else {
mStringBuilderTmp.append(formatNumber);
}
labelAndNumberString = mStringBuilderTmp.toString();
}
} else {
nameStr = formatNumber;
if (!FeatureOptionAssistant.isInternationalSupportted()) {
labelAndNumberString = location;
}
}
isStrange = true;
} else {
nameStr = contactName;
if (TextUtils.isEmpty(location)) {
labelAndNumberString = formatNumber;
} else {
mStringBuilderTmp.setLength(0);
if (!FeatureOptionAssistant.isInternationalSupportted()) {
mStringBuilderTmp.append(formatNumber).append(' ').append(location);
} else {
mStringBuilderTmp.append(formatNumber);
}
labelAndNumberString = mStringBuilderTmp.toString();
}
isStrange = false;
}
mStringBuilderTmp.setLength(0);
mStringBuilderTmp.append(nameStr);
long ringTime = callLoginfo.ringTime;
long duration = callLoginfo.duration;
if (callLoginfo.groupItemCount > 1) {
mStringBuilderTmp.append(" (").append(callLoginfo.groupItemCount).append(')');
}
setNameViewStyle(views, type, ringTime, mStringBuilderTmp.toString());
bindCallTypeAndFreaturesView(views, callLoginfo, duration, type, features,
simId, isStrange, labelAndNumberString);
// for unknown number;private number; payed number
setSpecialNumberLabel(number, views);
String dateString;
long currentTime = System.currentTimeMillis();
if (currentTime - date < ONE_MINUTE) {
dateString = mCallLogTimeJustnow;
} else {
dateString = DateUtils.getRelativeTimeSpanString(date, currentTime,
DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_NUMERIC_DATE).toString();
dateString = dateString.replaceAll("/", "-");
}
views.setTextViewText(R.id.date, dateString);
final Intent fillInIntent = GadgetProvider.getCallDirectly(mContext, number);
views.setOnClickFillInIntent(R.id.numInfo, fillInIntent);
return views;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public int getCount() {
return mCallLogCache.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return false;
}
public void startCallsQuery(final Context context) {
new AsyncTask<Void, Void, Integer>() {
@Override
protected Integer doInBackground(Void... params) {
return GadgetProvider.getCalllogUnreadCount(context);
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
Intent updateIntent =
new Intent(GadgetProvider.ACTION_CONTACTS_APPWIDGET_UPDATE);
updateIntent.putExtra(GadgetProvider.EXTRA_UNREAD_COUNT, result);
updateIntent.setClass(context, GadgetProvider.class);
context.sendBroadcast(updateIntent);
startCallsQuery(result > 0);
}
}.execute();
}
public void startCallsQuery(boolean showMissed) {
if (mCallLogQueryHandler == null) return;
if (DEBUG) Log.d(TAG, "startCallsQuery : " + showMissed);
mCallLogQueryHandler.queryCalls(showMissed ?
CallLogQueryHandler.QUERY_CALLS_NEW_MISSED : CallLogQueryHandler.QUERY_CALLS_ALL);
}
private void setNameViewStyle(RemoteViews views,
int type, long ringTime, String nameStr) {
if (type == Calls.MISSED_TYPE) {
if (ringTime != 0) {
String ringStr = AliCallLogExtensionHelper.formatCallTypeLabel(mContext,
mRingTimeFormat, -1, ringTime);
StringBuilder bdStr = new StringBuilder();
bdStr.append('(').append(ringStr).append(')');
SpannableString ss = new SpannableString(nameStr + bdStr);
int len = nameStr.length() + bdStr.length();
ss.setSpan(new ForegroundColorSpan(mRedToWhiteColor), 0, nameStr.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// float textSize = viewHolder.labelAndNumber.getTextSize();
// ss.setSpan(new AbsoluteSizeSpan((int) textSize), nameStr.length(), len,
// Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new ForegroundColorSpan(mGreyToWhiteColor), nameStr.length(), len,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
views.setTextViewText(R.id.name, ss);
} else {
views.setTextColor(R.id.name, mRedToWhiteColor);
views.setTextViewText(R.id.name, nameStr);
}
} else {
views.setTextColor(R.id.name, mBlackToWhiteColor);
views.setTextViewText(R.id.name, nameStr);
}
}
private void bindCallTypeAndFreaturesView(RemoteViews views, CallLogInfo callLogInfo,
long duration, int type, int features,
int simId, boolean isStrange, String labelAndNumberString) {
int resId = 0;
if (type == Calls.MISSED_TYPE) {
if (simId == SimUtil.SLOT_ID_1) {
resId = R.drawable.ic_dial_doublecard_miss1;
} else if (simId == SimUtil.SLOT_ID_2) {
resId = R.drawable.ic_dial_doublecard_miss2;
} else {
resId = R.drawable.ic_dial_miss;
}
} else if (type == Calls.INCOMING_TYPE) {
if (simId == SimUtil.SLOT_ID_1) {
resId = duration == 0 ? R.drawable.ic_dial_doublecard_stop1
: R.drawable.ic_dial_doublecard_received1;
} else if (simId == SimUtil.SLOT_ID_2) {
resId = duration == 0 ? R.drawable.ic_dial_doublecard_stop2
: R.drawable.ic_dial_doublecard_received2;
} else {
resId = duration == 0 ? R.drawable.ic_dial_stop : R.drawable.ic_dial_received;
}
} else if (type == Calls.OUTGOING_TYPE) {
if (simId == SimUtil.SLOT_ID_1) {
resId = R.drawable.ic_dial_doublecard_called1;
} else if (simId == SimUtil.SLOT_ID_2) {
resId = R.drawable.ic_dial_doublecard_called2;
} else {
resId = R.drawable.ic_dial_called;
}
}
views.setImageViewResource(R.id.call_type_indicator, resId);
if ((features & CallerViewQuery.CALL_FEATURES_BIT_VIDEO) != 0) {
views.setImageViewResource(R.id.call_features_indicator,
R.drawable.ic_callhistory_facetime_normal);
views.setViewVisibility(R.id.call_features_indicator, View.VISIBLE);
} else if ((features & CallerViewQuery.CALL_FEATURES_BIT_HD) != 0) {
views.setImageViewResource(R.id.call_features_indicator,
R.drawable.ic_callhistory_hd_normal);
views.setViewVisibility(R.id.call_features_indicator, View.VISIBLE);
} else {
views.setViewVisibility(R.id.call_features_indicator, View.GONE);
}
// Bind tag type if any tag type marked.
bindTagTypeView(callLogInfo, views, isStrange, labelAndNumberString);
}
private void bindTagTypeView(CallLogInfo callLogInfo, RemoteViews views, boolean isStrange,
String labelAndNumberString) {
mStringBuilderTmp.setLength(0);
mStringBuilderTmp.append(labelAndNumberString);
String tagName = callLogInfo.tagName;
int markedCount = callLogInfo.markedCount;
if (isStrange) {
if (!TextUtils.isEmpty(tagName)) {
if (!TextUtils.isEmpty(labelAndNumberString)) {
mStringBuilderTmp.append(TAG_DIVIDER);
}
if (markedCount > 0) {
tagName = ((markedCount == 1) ? mContext.getString(
R.string.system_tag_type_parameter_for_one, tagName) : mContext
.getString(R.string.system_tag_type_parameter, markedCount, tagName));
}
mStringBuilderTmp.append(tagName);
}
}
views.setTextViewText(R.id.labelAndNumber, mStringBuilderTmp.toString());
}
private void setSpecialNumberLabel(String number, RemoteViews views) {
int resId = AliCallLogExtensionHelper.getSpecialNumber(number);
if (resId > 0) {
views.setTextViewText(R.id.name, mContext.getString(resId));
}
}
/** Returns the contact information as stored in the call log. */
private ContactInfo getContactInfoFromCallLog(CallLogInfo callLogInfo) {
// Fill the same content as ContactInfo.fromLocalCallsCursor(Cursor);
ContactInfo info = new ContactInfo();
info.lookupUri = callLogInfo.lookupUri;
info.name = callLogInfo.name;
info.type = callLogInfo.numberType;
info.label = callLogInfo.label;
info.number = callLogInfo.matchedNumber;
info.normalizedNumber = callLogInfo.normalizedNumber;
info.photoId = callLogInfo.photoId;
info.photoUri = callLogInfo.photoUri;
info.formattedNumber = callLogInfo.formattedNumber;
return info;
}
private void initFormatString(Resources res) {
mRingTimeFormat = res.getString(R.string.ringing_time);
mCallLogTimeJustnow = res.getString(R.string.calllog_time_just_now);
}
private void initFontColor(Resources res) {
mRedToWhiteColor = res.getColor(R.drawable.aui_ic_color_red_to_white);
mBlackToWhiteColor = res.getColor(R.drawable.aui_ic_color_black_to_white);
mGreyToWhiteColor = res.getColor(R.drawable.aui_ic_color_grey_to_white);
}
@Override
public boolean onCallsFetched(Cursor cursor) {
int count = cursor == null ? -1 : cursor.getCount();
Log.i(TAG, "onCallsFetched: count="+count);
if (count <= 0) {
synchronized (mCallLogCache) {
mCallLogCache.clear();
}
// Refresh list view now
notifyRefresh();
return false;
}
if (count == 1) {
cursor.moveToFirst();
CallLogInfo info = getValueFromCursor(cursor);
info.groupItemCount = 1;
synchronized (mCallLogCache) {
mCallLogCache.clear();
mCallLogCache.add(info);
}
// Refresh list view now
notifyRefresh();
return false;
}
ArrayList<CallLogInfo> tmpCache = new ArrayList<CallLogInfo>(count);
cursor.moveToFirst();
String latestNumber = cursor.getString(CallerViewQuery.NUMBER);
int groupItemCount = 1;
CallLogInfo info = getValueFromCursor(cursor);
while (cursor.moveToNext()) {
final String currentNumber = cursor.getString(CallerViewQuery.NUMBER);
final boolean sameNumber = equalNumbers(latestNumber, currentNumber);
if (sameNumber) {
groupItemCount++;
continue;
}
info.groupItemCount = groupItemCount;
tmpCache.add(info);
groupItemCount = 1;
latestNumber = currentNumber;
info = getValueFromCursor(cursor);
if (cursor.isLast()) {
info.groupItemCount = groupItemCount;
tmpCache.add(info);
}
}
if (groupItemCount > 1) {
info.groupItemCount = groupItemCount;
tmpCache.add(info);
}
synchronized (mCallLogCache) {
mCallLogCache.clear();
mCallLogCache.addAll(tmpCache);
Log.d(TAG, "onCallsFetched X: " + mCallLogCache.size());
}
// Refresh list view now
notifyRefresh();
return false;
}
private void notifyRefresh() {
// Refresh list view now
AppWidgetManager widgetMgr = AppWidgetManager.getInstance(mContext);
int[] ids = widgetMgr.getAppWidgetIds(GadgetProvider.getComponentName(mContext));
widgetMgr.notifyAppWidgetViewDataChanged(ids, R.id.call_log_list);
return;
}
private static CallLogInfo getValueFromCursor(final Cursor cursor) {
CallLogInfo info = new CallLogInfo();
info.subId = cursor.getInt(CallerViewQuery.SIMID);
info.callId = cursor.getLong(CallerViewQuery.ID);
info.number = cursor.getString(CallerViewQuery.NUMBER);
info.type = cursor.getInt(CallerViewQuery.TYPE);
info.features = cursor.getInt(CallerViewQuery.FEATURES);
info.date = cursor.getLong(CallerViewQuery.DATE);
info.countryIso = cursor.getString(CallerViewQuery.COUNTRY_ISO);
info.ypName = cursor.getString(CallerViewQuery.SHOP_NAME);
info.province = cursor.getString(CallerViewQuery.LOC_PROVINCE);
info.area = cursor.getString(CallerViewQuery.LOC_AREA);
info.tagName = cursor.getString(CallerViewQuery.TAG_NAME);
info.markedCount = cursor.getInt(CallerViewQuery.MARKED_COUNT);
info.ringTime = cursor.getLong(CallerViewQuery.RING_TIME);
info.duration = cursor.getLong(CallerViewQuery.DURATION);
info.lookupUri = cursor.getString(CallerViewQuery.LOOKUP_URI);
info.name = cursor.getString(CallerViewQuery.NAME);
info.numberType = cursor.getInt(CallerViewQuery.NUMBER_TYPE);
info.label = cursor.getString(CallerViewQuery.NUMBER_LABEL);
info.matchedNumber = cursor.getString(CallerViewQuery.MATCHED_NUM);
info.normalizedNumber = cursor.getString(CallerViewQuery.NORMALIZED_NUM);
info.photoId = cursor.getLong(CallerViewQuery.PHOTO_ID);
info.photoUri = cursor.getString(CallerViewQuery.PHOTO_URI);
info.formattedNumber = cursor.getString(CallerViewQuery.FORMATTED_NUM);
return info;
}
private static boolean equalNumbers(final String number1, final String number2) {
return PhoneNumberUtils.compare(number1, number2);
}
private static class CallLogInfo {
int subId;
long callId;
String number;
int type;
int features;
long date;
String countryIso;
String ypName;
String province;
String area;
String tagName;
int markedCount;
long ringTime;
long duration;
String lookupUri;
String name;
int numberType;
String label;
String matchedNumber;
String normalizedNumber;
long photoId;
String photoUri;
String formattedNumber;
int groupItemCount;
public CallLogInfo() {
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CallLogInfo [subId=").append(subId);
builder.append(", callId=").append(callId);
builder.append(", number=").append(number);
builder.append(", type=").append(type);
builder.append(", features=").append(features);
builder.append(", date=").append(date);
builder.append(", countryIso=").append(countryIso);
builder.append(", ypName=").append(ypName);
builder.append(", province=").append(province);
builder.append(", area=").append(area);
builder.append(", tagName=").append(tagName);
builder.append(", markedCount=").append(markedCount);
builder.append(", ringTime=").append(ringTime);
builder.append(", duration=").append(duration);
builder.append(", groupItemCount=").append(groupItemCount);
builder.append(", lookupUri=").append(lookupUri);
builder.append(", name=").append(name);
builder.append(", numberType=").append(numberType);
builder.append(", label=").append(label);
builder.append(", matchedNumber=").append(matchedNumber);
builder.append(", normalizedNumber=").append(normalizedNumber);
builder.append(", photoId=").append(photoId);
builder.append(", photoUri=").append(photoUri);
builder.append(", formattedNumber=").append(formattedNumber);
builder.append("]");
return builder.toString();
}
}
}
}
|
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ui.UIUtil;
import junit.framework.Assert;
import org.junit.Test;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: Irina.Chernushina
* Date: 11/12/12
* Time: 10:24 AM
*/
public class SvnExternalTest extends Svn17TestCase {
private ChangeListManagerImpl clManager;
private SvnVcs myVcs;
private String myMainUrl;
private String myExternalURL;
@Override
public void setUp() throws Exception {
super.setUp();
clManager = (ChangeListManagerImpl) ChangeListManager.getInstance(myProject);
enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD);
enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE);
myVcs = SvnVcs.getInstance(myProject);
myMainUrl = myRepoUrl + "/root/source";
myExternalURL = myRepoUrl + "/root/target";
}
@Test
public void testExternalCopyIsDetected() throws Exception {
prepareExternal();
externalCopyIsDetectedImpl();
}
@Test
public void testExternalCopyIsDetectedAnotherRepo() throws Exception {
prepareExternal(true, true, true);
externalCopyIsDetectedImpl();
}
private void externalCopyIsDetectedImpl() {
final SvnFileUrlMapping workingCopies = myVcs.getSvnFileUrlMapping();
final List<RootUrlInfo> infos = workingCopies.getAllWcInfos();
Assert.assertEquals(2, infos.size());
final Set<String> expectedUrls = new HashSet<>();
if (myAnotherRepoUrl != null) {
expectedUrls.add(StringUtil.toLowerCase(myAnotherRepoUrl + "/root/target"));
} else {
expectedUrls.add(StringUtil.toLowerCase(myExternalURL));
}
expectedUrls.add(StringUtil.toLowerCase(myMainUrl));
for (RootUrlInfo info : infos) {
expectedUrls.remove(StringUtil.toLowerCase(info.getAbsoluteUrl()));
}
Assert.assertTrue(expectedUrls.isEmpty());
}
protected void prepareInnerCopy() throws Exception {
prepareInnerCopy(false);
}
@Test
public void testInnerCopyDetected() throws Exception {
prepareInnerCopy();
final SvnFileUrlMapping workingCopies = myVcs.getSvnFileUrlMapping();
final List<RootUrlInfo> infos = workingCopies.getAllWcInfos();
Assert.assertEquals(2, infos.size());
final Set<String> expectedUrls = new HashSet<>();
expectedUrls.add(StringUtil.toLowerCase(myExternalURL));
expectedUrls.add(StringUtil.toLowerCase(myMainUrl));
boolean sawInner = false;
for (RootUrlInfo info : infos) {
expectedUrls.remove(StringUtil.toLowerCase(info.getAbsoluteUrl()));
sawInner |= NestedCopyType.inner.equals(info.getType());
}
Assert.assertTrue(expectedUrls.isEmpty());
Assert.assertTrue(sawInner);
}
@Test
public void testSimpleExternalsStatus() throws Exception {
prepareExternal();
simpleExternalStatusImpl();
}
@Test
public void testSimpleExternalsAnotherStatus() throws Exception {
prepareExternal(true, true, true);
simpleExternalStatusImpl();
}
private void simpleExternalStatusImpl() {
final File sourceFile = new File(myWorkingCopyDir.getPath(), "source" + File.separator + "s1.txt");
final File externalFile = new File(myWorkingCopyDir.getPath(), "source" + File.separator + "external" + File.separator + "t12.txt");
final LocalFileSystem lfs = LocalFileSystem.getInstance();
final VirtualFile vf1 = lfs.refreshAndFindFileByIoFile(sourceFile);
final VirtualFile vf2 = lfs.refreshAndFindFileByIoFile(externalFile);
Assert.assertNotNull(vf1);
Assert.assertNotNull(vf2);
VcsTestUtil.editFileInCommand(myProject, vf1, "test externals 123" + System.currentTimeMillis());
VcsTestUtil.editFileInCommand(myProject, vf2, "test externals 123" + System.currentTimeMillis());
VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
clManager.ensureUpToDate(false);
final Change change1 = clManager.getChange(vf1);
final Change change2 = clManager.getChange(vf2);
Assert.assertNotNull(change1);
Assert.assertNotNull(change2);
Assert.assertNotNull(change1.getBeforeRevision());
Assert.assertNotNull(change2.getBeforeRevision());
Assert.assertNotNull(change1.getAfterRevision());
Assert.assertNotNull(change2.getAfterRevision());
}
@Test
public void testUpdatedCreatedExternalFromIDEA() throws Exception {
prepareExternal(false, false, false);
updatedCreatedExternalFromIDEAImpl();
}
@Test
public void testUpdatedCreatedExternalFromIDEAAnother() throws Exception {
prepareExternal(false, false, true);
updatedCreatedExternalFromIDEAImpl();
}
private void updatedCreatedExternalFromIDEAImpl() {
final File sourceDir = new File(myWorkingCopyDir.getPath(), "source");
setNewDirectoryMappings(sourceDir);
imitUpdate(myProject);
final File externalFile = new File(sourceDir, "external/t11.txt");
final VirtualFile externalVf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(externalFile);
Assert.assertNotNull(externalVf);
}
private void setNewDirectoryMappings(final File sourceDir) {
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@Override
public void run() {
ProjectLevelVcsManager.getInstance(myProject).setDirectoryMappings(
Arrays.asList(new VcsDirectoryMapping(FileUtil.toSystemIndependentName(sourceDir.getPath()), myVcs.getName())));
}
});
}
@Test
public void testUncommittedExternalStatus() throws Exception {
prepareExternal(false, true, false);
uncommittedExternalStatusImpl();
}
@Test
public void testUncommittedExternalStatusAnother() throws Exception {
prepareExternal(false, true, true);
uncommittedExternalStatusImpl();
}
private void uncommittedExternalStatusImpl() {
final File sourceDir = new File(myWorkingCopyDir.getPath(), "source");
final File externalFile = new File(sourceDir, "external/t11.txt");
final VirtualFile externalVf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(externalFile);
Assert.assertNotNull(externalVf);
editFileInCommand(externalVf, "some new content");
VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
clManager.ensureUpToDate(false);
final Change change = clManager.getChange(externalVf);
Assert.assertNotNull(change);
Assert.assertEquals(FileStatus.MODIFIED, change.getFileStatus());
}
@Test
public void testUncommittedExternalCopyIsDetected() throws Exception {
prepareExternal(false, false, false);
uncommittedExternalCopyIsDetectedImpl();
}
@Test
public void testUncommittedExternalCopyIsDetectedAnother() throws Exception {
prepareExternal(false, false, true);
uncommittedExternalCopyIsDetectedImpl();
}
private void uncommittedExternalCopyIsDetectedImpl() {
final File sourceDir = new File(myWorkingCopyDir.getPath(), "source");
setNewDirectoryMappings(sourceDir);
imitUpdate(myProject);
refreshSvnMappingsSynchronously();
externalCopyIsDetectedImpl();
}
}
|
|
/*
* 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.test.database.auto;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.testng.Assert;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.orientechnologies.orient.core.db.ODatabase.OPERATION_MODE;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OPartitionedDatabasePool;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.iterator.ORecordIteratorCluster;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecordAbstract;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentInternal;
import com.orientechnologies.orient.core.serialization.OBase64Utils;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerSchemaAware2CSV;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.core.version.OVersionFactory;
@Test(groups = { "crud", "record-vobject" }, sequential = true)
public class CRUDDocumentPhysicalTest extends DocumentDBBaseTest {
protected static final int TOT_RECORDS = 100;
protected static final int TOT_RECORDS_COMPANY = 10;
protected long startRecordNumber;
String base64;
private ODocument record;
@Parameters(value = "url")
public CRUDDocumentPhysicalTest(@Optional String url) {
super(url);
}
@Test
public void testPool() throws IOException {
OPartitionedDatabasePool pool = new OPartitionedDatabasePool(url, "admin", "admin");
final ODatabaseDocumentTx[] dbs = new ODatabaseDocumentTx[pool.getMaxSize()];
for (int i = 0; i < 10; ++i) {
for (int db = 0; db < dbs.length; ++db)
dbs[db] = pool.acquire();
for (int db = 0; db < dbs.length; ++db)
dbs[db].close();
}
pool.close();
}
@Test
public void cleanAll() {
record = database.newInstance();
if (!database.existsCluster("Account"))
database.addCluster("Account");
startRecordNumber = database.countClusterElements("Account");
// DELETE ALL THE RECORDS IN THE CLUSTER
while (database.countClusterElements("Account") > 0)
for (ODocument rec : database.browseCluster("Account"))
if (rec != null)
rec.delete();
Assert.assertEquals(database.countClusterElements("Account"), 0);
if (!database.existsCluster("Company"))
database.addCluster("Company");
}
@Test(dependsOnMethods = "cleanAll")
public void create() {
startRecordNumber = database.countClusterElements("Account");
byte[] binary = new byte[100];
for (int b = 0; b < binary.length; ++b)
binary[b] = (byte) b;
base64 = OBase64Utils.encodeBytes(binary);
final int accountClusterId = database.getClusterIdByName("Account");
for (long i = startRecordNumber; i < startRecordNumber + TOT_RECORDS; ++i) {
record.reset();
record.setClassName("Account");
record.field("id", i);
record.field("name", "Gipsy");
record.field("location", "Italy");
record.field("salary", (i + 300f));
record.field("binary", binary);
record.field("nonSchemaBinary", binary);
record.field("testLong", 10000000000L); // TEST LONG
record.field("extra", "This is an extra field not included in the schema");
record.field("value", (byte) 10);
record.save();
Assert.assertEquals(record.getIdentity().getClusterId(), accountClusterId);
}
long startRecordNumberL = database.countClusterElements("Company");
final ODocument doc = new ODocument();
for (long i = startRecordNumberL; i < startRecordNumberL + TOT_RECORDS_COMPANY; ++i) {
doc.setClassName("Company");
doc.field("id", i);
doc.field("name", "Microsoft" + i);
doc.field("employees", (int) (100000 + i));
database.save(doc);
doc.reset();
}
}
@Test(dependsOnMethods = "create")
public void testCreate() {
Assert.assertEquals(database.countClusterElements("Account") - startRecordNumber, TOT_RECORDS);
}
@Test(dependsOnMethods = "testCreate")
public void readAndBrowseDescendingAndCheckHoleUtilization() {
// BROWSE IN THE OPPOSITE ORDER
byte[] binary;
Set<Integer> ids = new HashSet<Integer>();
for (int i = 0; i < TOT_RECORDS; i++)
ids.add(i);
ORecordIteratorCluster<ODocument> it = database.browseCluster("Account");
for (it.last(); it.hasPrevious();) {
ODocument rec = it.previous();
if (rec != null) {
int id = ((Number) rec.field("id")).intValue();
Assert.assertTrue(ids.remove(id));
Assert.assertEquals(rec.field("name"), "Gipsy");
Assert.assertEquals(rec.field("location"), "Italy");
Assert.assertEquals(((Number) rec.field("testLong")).longValue(), 10000000000L);
Assert.assertEquals(((Number) rec.field("salary")).intValue(), id + 300);
Assert.assertNotNull(rec.field("extra"));
Assert.assertEquals(((Byte) rec.field("value", Byte.class)).byteValue(), (byte) 10);
binary = rec.field("binary", OType.BINARY);
for (int b = 0; b < binary.length; ++b)
Assert.assertEquals(binary[b], (byte) b);
}
}
Assert.assertTrue(ids.isEmpty());
}
@Test(dependsOnMethods = "readAndBrowseDescendingAndCheckHoleUtilization")
public void update() {
int i = 0;
for (ODocument rec : database.browseCluster("Account")) {
if (i % 2 == 0)
rec.field("location", "Spain");
rec.field("price", i + 100);
rec.save();
i++;
}
}
@Test(dependsOnMethods = "update")
public void testUpdate() {
for (ODocument rec : database.browseCluster("Account")) {
int price = ((Number) rec.field("price")).intValue();
Assert.assertTrue(price - 100 >= 0);
if ((price - 100) % 2 == 0)
Assert.assertEquals(rec.field("location"), "Spain");
else
Assert.assertEquals(rec.field("location"), "Italy");
}
}
@Test(dependsOnMethods = "testUpdate")
public void testDoubleChanges() {
ODocument vDoc = database.newInstance();
vDoc.setClassName("Profile");
vDoc.field("nick", "JayM1").field("name", "Jay").field("surname", "Miner");
vDoc.save();
Assert.assertEquals(vDoc.getIdentity().getClusterId(), vDoc.getSchemaClass().getDefaultClusterId());
vDoc = database.load(vDoc.getIdentity());
vDoc.field("nick", "JayM2");
vDoc.field("nick", "JayM3");
vDoc.save();
Set<OIndex<?>> indexes = database.getMetadata().getSchema().getClass("Profile").getProperty("nick").getIndexes();
Assert.assertEquals(indexes.size(), 1);
OIndex indexDefinition = indexes.iterator().next();
OIdentifiable vOldName = (OIdentifiable) indexDefinition.get("JayM1");
Assert.assertNull(vOldName);
OIdentifiable vIntermediateName = (OIdentifiable) indexDefinition.get("JayM2");
Assert.assertNull(vIntermediateName);
OIdentifiable vNewName = (OIdentifiable) indexDefinition.get("JayM3");
Assert.assertNotNull(vNewName);
}
@Test(dependsOnMethods = "testDoubleChanges")
public void testMultiValues() {
ODocument vDoc = database.newInstance();
vDoc.setClassName("Profile");
vDoc.field("nick", "Jacky").field("name", "Jack").field("surname", "Tramiel");
vDoc.save();
// add a new record with the same name "nameA".
vDoc = database.newInstance();
vDoc.setClassName("Profile");
vDoc.field("nick", "Jack").field("name", "Jack").field("surname", "Bauer");
vDoc.save();
Collection<OIndex<?>> indexes = database.getMetadata().getSchema().getClass("Profile").getProperty("name").getIndexes();
Assert.assertEquals(indexes.size(), 1);
OIndex<?> indexName = indexes.iterator().next();
// We must get 2 records for "nameA".
Collection<OIdentifiable> vName1 = (Collection<OIdentifiable>) indexName.get("Jack");
Assert.assertEquals(vName1.size(), 2);
// Remove this last record.
database.delete(vDoc);
// We must get 1 record for "nameA".
vName1 = (Collection<OIdentifiable>) indexName.get("Jack");
Assert.assertEquals(vName1.size(), 1);
}
@Test(dependsOnMethods = "testMultiValues")
public void testUnderscoreField() {
ODocument vDoc = database.newInstance();
vDoc.setClassName("Profile");
vDoc.field("nick", "MostFamousJack").field("name", "Kiefer").field("surname", "Sutherland")
.field("tag_list", new String[] { "actor", "myth" });
vDoc.save();
List<ODocument> result = database.command(
new OSQLSynchQuery<ODocument>("select from Profile where name = 'Kiefer' and tag_list.size() > 0 ")).execute();
Assert.assertEquals(result.size(), 1);
}
public void testLazyLoadingByLink() {
ODocument coreDoc = new ODocument();
ODocument linkDoc = new ODocument();
coreDoc.field("link", linkDoc);
coreDoc.save();
ODocument coreDocCopy = database.load(coreDoc.getIdentity(), "*:-1", true);
Assert.assertNotSame(coreDocCopy, coreDoc);
coreDocCopy.setLazyLoad(false);
Assert.assertTrue(coreDocCopy.field("link") instanceof ORecordId);
coreDocCopy.setLazyLoad(true);
Assert.assertTrue(coreDocCopy.field("link") instanceof ODocument);
}
@SuppressWarnings("unchecked")
@Test
public void testDbCacheUpdated() {
ODocument vDoc = database.newInstance();
vDoc.setClassName("Profile");
Set<String> tags = new HashSet<String>();
tags.add("test");
tags.add("yeah");
vDoc.field("nick", "Dexter").field("name", "Michael").field("surname", "Hall").field("tag_list", tags);
vDoc.save();
List<ODocument> result = database.command(new OSQLSynchQuery<ODocument>("select from Profile where name = 'Michael'"))
.execute();
Assert.assertEquals(result.size(), 1);
ODocument dexter = result.get(0);
((Collection<String>) dexter.field("tag_list")).add("actor");
dexter.setDirty();
dexter.save();
result = database.command(
new OSQLSynchQuery<ODocument>("select from Profile where tag_list contains 'actor' and tag_list contains 'test'"))
.execute();
Assert.assertEquals(result.size(), 1);
}
@Test(dependsOnMethods = "testUnderscoreField")
public void testUpdateLazyDirtyPropagation() {
for (ODocument rec : database.browseCluster("Profile")) {
Assert.assertFalse(rec.isDirty());
Collection<?> followers = rec.field("followers");
if (followers != null && followers.size() > 0) {
followers.remove(followers.iterator().next());
Assert.assertTrue(rec.isDirty());
break;
}
}
}
@SuppressWarnings("unchecked")
@Test
public void testNestedEmbeddedMap() {
ODocument newDoc = new ODocument();
final Map<String, HashMap<?, ?>> map1 = new HashMap<String, HashMap<?, ?>>();
newDoc.field("map1", map1, OType.EMBEDDEDMAP);
final Map<String, HashMap<?, ?>> map2 = new HashMap<String, HashMap<?, ?>>();
map1.put("map2", (HashMap<?, ?>) map2);
final Map<String, HashMap<?, ?>> map3 = new HashMap<String, HashMap<?, ?>>();
map2.put("map3", (HashMap<?, ?>) map3);
final ORecordId rid = (ORecordId) newDoc.save().getIdentity();
final ODocument loadedDoc = database.load(rid);
Assert.assertTrue(newDoc.hasSameContentOf(loadedDoc));
Assert.assertTrue(loadedDoc.containsField("map1"));
Assert.assertTrue(loadedDoc.field("map1") instanceof Map<?, ?>);
final Map<String, ODocument> loadedMap1 = loadedDoc.field("map1");
Assert.assertEquals(loadedMap1.size(), 1);
Assert.assertTrue(loadedMap1.containsKey("map2"));
Assert.assertTrue(loadedMap1.get("map2") instanceof Map<?, ?>);
final Map<String, ODocument> loadedMap2 = (Map<String, ODocument>) loadedMap1.get("map2");
Assert.assertEquals(loadedMap2.size(), 1);
Assert.assertTrue(loadedMap2.containsKey("map3"));
Assert.assertTrue(loadedMap2.get("map3") instanceof Map<?, ?>);
final Map<String, ODocument> loadedMap3 = (Map<String, ODocument>) loadedMap2.get("map3");
Assert.assertEquals(loadedMap3.size(), 0);
}
@Test
public void commandWithPositionalParameters() {
final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>("select from Profile where name = ? and surname = ?");
List<ODocument> result = database.command(query).execute("Barack", "Obama");
Assert.assertTrue(result.size() != 0);
}
@Test
public void queryWithPositionalParameters() {
final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>("select from Profile where name = ? and surname = ?");
List<ODocument> result = database.query(query, "Barack", "Obama");
Assert.assertTrue(result.size() != 0);
}
@Test
public void commandWithNamedParameters() {
final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(
"select from Profile where name = :name and surname = :surname");
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "Barack");
params.put("surname", "Obama");
List<ODocument> result = database.command(query).execute(params);
Assert.assertTrue(result.size() != 0);
}
@Test
public void commandWrongParameterNames() {
ODocument doc = database.newInstance();
try {
doc.field("a:b", 10);
Assert.assertFalse(true);
} catch (IllegalArgumentException e) {
Assert.assertTrue(true);
}
try {
doc.field("a,b", 10);
Assert.assertFalse(true);
} catch (IllegalArgumentException e) {
Assert.assertTrue(true);
}
}
@Test
public void queryWithNamedParameters() {
final OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(
"select from Profile where name = :name and surname = :surname");
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "Barack");
params.put("surname", "Obama");
List<ODocument> result = database.query(query, params);
Assert.assertTrue(result.size() != 0);
}
public void testJSONLinkd() {
ODocument jaimeDoc = new ODocument("PersonTest");
jaimeDoc.field("name", "jaime");
jaimeDoc.save();
ODocument cerseiDoc = new ODocument("PersonTest");
cerseiDoc.fromJSON("{\"@type\":\"d\",\"name\":\"cersei\",\"valonqar\":" + jaimeDoc.toJSON() + "}");
cerseiDoc.save();
// The link between jamie and tyrion is not saved properly
ODocument tyrionDoc = new ODocument("PersonTest");
tyrionDoc.fromJSON("{\"@type\":\"d\",\"name\":\"tyrion\",\"emergency_contact\":{\"relationship\":\"brother\",\"contact\":"
+ jaimeDoc.toJSON() + "}}");
tyrionDoc.save();
// System.out.println("The saved documents are:");
for (ODocument o : database.browseClass("PersonTest")) {
// System.out.println("my id is " + o.getIdentity().toString());
// System.out.println("my name is: " + o.field("name"));
// System.out.println("my ODocument representation is " + o);
// System.out.println("my JSON representation is " + o.toJSON());
// System.out.println("my traversable links are: ");
for (OIdentifiable id : new OSQLSynchQuery<ODocument>("traverse * from " + o.getIdentity().toString())) {
database.load(id.getIdentity()).toJSON();
}
}
}
@Test
public void testDirtyChild() {
ODocument parent = new ODocument();
ODocument child1 = new ODocument();
ODocumentInternal.addOwner(child1, parent);
parent.field("child1", child1);
Assert.assertTrue(child1.hasOwners());
ODocument child2 = new ODocument();
ODocumentInternal.addOwner(child2, child1);
child1.field("child2", child2);
Assert.assertTrue(child2.hasOwners());
// BEFORE FIRST TOSTREAM
Assert.assertTrue(parent.isDirty());
parent.toStream();
// AFTER TOSTREAM
Assert.assertTrue(parent.isDirty());
// CHANGE FIELDS VALUE (Automaticaly set dirty this child)
child1.field("child2", new ODocument());
Assert.assertTrue(parent.isDirty());
}
@Test
public void testInvalidFetchplanLoad() {
ODocument doc = database.newInstance();
doc.field("test", "test");
doc.save();
ORID docRid = doc.getIdentity().copy();
try {
// RELOAD THE DOCUMENT, THIS WILL PUT IT IN L1 CACHE
doc = database.load(docRid, "*:-1");
doc = testInvalidFetchPlanInvalidateL1Cache(doc, docRid);
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(1, 0));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(1, 1));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(1, 2));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(2, 0));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(2, 1));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(2, 2));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(3, 0));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(3, 1));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(3, 2));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(4, 0));
doc = testInvalidFetchPlanInvalidateL1Cache(doc, new ORecordId(4, 1));
// CLOSE DB AND RE-TEST THE LOAD TO MAKE SURE
} finally {
database.close();
}
database.open("admin", "admin");
doc = testInvalidFetchPlanClearL1Cache(doc, docRid);
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(1, 0));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(1, 1));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(1, 2));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(2, 0));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(2, 1));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(2, 2));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(3, 0));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(3, 1));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(3, 2));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(4, 0));
doc = testInvalidFetchPlanClearL1Cache(doc, new ORecordId(4, 1));
doc = database.load(docRid);
doc.delete();
}
public void testEncoding() {
String s = " \r\n\t:;,.|+*/\\=!?[]()'\"";
ODocument doc = new ODocument();
doc.field("test", s);
doc.save();
doc.reload(null, true);
Assert.assertEquals(doc.field("test"), s);
}
@Test
public void polymorphicQuery() {
final ORecordAbstract newAccount = new ODocument("Account").field("name", "testInheritanceName").save();
List<ODocument> superClassResult = database.query(new OSQLSynchQuery<ODocument>("select from Account"));
List<ODocument> subClassResult = database.query(new OSQLSynchQuery<ODocument>("select from Company"));
Assert.assertTrue(superClassResult.size() != 0);
Assert.assertTrue(subClassResult.size() != 0);
Assert.assertTrue(superClassResult.size() >= subClassResult.size());
// VERIFY ALL THE SUBCLASS RESULT ARE ALSO CONTAINED IN SUPERCLASS
// RESULT
for (ODocument d : subClassResult) {
Assert.assertTrue(superClassResult.contains(d));
}
HashSet<ODocument> browsed = new HashSet<ODocument>();
for (ODocument d : database.browseClass("Account")) {
Assert.assertFalse(browsed.contains(d));
browsed.add(d);
}
newAccount.delete();
}
@Test(dependsOnMethods = "testCreate")
public void testBrowseClassHasNextTwice() {
ODocument doc1 = null;
for (Iterator<ODocument> itDoc = database.browseClass("Account"); itDoc.hasNext();) {
doc1 = itDoc.next();
break;
}
ODocument doc2 = null;
for (Iterator<ODocument> itDoc = database.browseClass("Account"); itDoc.hasNext();) {
itDoc.hasNext();
doc2 = itDoc.next();
break;
}
Assert.assertEquals(doc1, doc2);
}
@Test(dependsOnMethods = "testCreate")
public void nonPolymorphicQuery() {
final ORecordAbstract newAccount = new ODocument("Account").field("name", "testInheritanceName").save();
List<ODocument> allResult = database.query(new OSQLSynchQuery<ODocument>("select from Account"));
List<ODocument> superClassResult = database
.query(new OSQLSynchQuery<ODocument>("select from Account where @class = 'Account'"));
List<ODocument> subClassResult = database.query(new OSQLSynchQuery<ODocument>("select from Company where @class = 'Company'"));
Assert.assertTrue(allResult.size() != 0);
Assert.assertTrue(superClassResult.size() != 0);
Assert.assertTrue(subClassResult.size() != 0);
// VERIFY ALL THE SUBCLASS RESULT ARE NOT CONTAINED IN SUPERCLASS RESULT
for (ODocument d : subClassResult) {
Assert.assertFalse(superClassResult.contains(d));
}
HashSet<ODocument> browsed = new HashSet<ODocument>();
for (ODocument d : database.browseClass("Account")) {
Assert.assertFalse(browsed.contains(d));
browsed.add(d);
}
newAccount.delete();
}
@Test(dependsOnMethods = "cleanAll")
public void asynchInsertion() {
startRecordNumber = database.countClusterElements("Account");
final AtomicInteger callBackCalled = new AtomicInteger();
final long total = startRecordNumber + TOT_RECORDS;
for (long i = startRecordNumber; i < total; ++i) {
record.reset();
record.setClassName("Account");
record.field("id", i);
record.field("name", "Asynch insertion test");
record.field("location", "Italy");
record.field("salary", (i + 300));
database.save(record, OPERATION_MODE.ASYNCHRONOUS, false, new ORecordCallback<Long>() {
@Override
public void call(ORecordId iRID, Long iParameter) {
callBackCalled.incrementAndGet();
}
}, null);
}
while (callBackCalled.intValue() < total) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
Assert.assertEquals(callBackCalled.intValue(), total);
// WAIT UNTIL ALL RECORD ARE INSERTED. USE A NEW DATABASE CONNECTION
// TO AVOID TO ENQUEUE THE COUNT ITSELF
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
final ODatabaseDocumentTx db = new ODatabaseDocumentTx(url).open("admin", "admin");
long tot;
while ((tot = db.countClusterElements("Account")) < startRecordNumber + TOT_RECORDS) {
// System.out.println("Asynchronous insertion: found " + tot + " records but waiting till " + (startRecordNumber +
// TOT_RECORDS)
// + " is reached");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
db.close();
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
}
if (database.countClusterElements("Account") > 0)
for (ODocument d : database.browseClass("Account")) {
if (d.field("name").equals("Asynch insertion test"))
d.delete();
}
}
@Test(dependsOnMethods = "cleanAll")
public void testEmbeddeDocumentInTx() {
ODocument bank = database.newInstance("Account");
database.begin();
bank.field("Name", "MyBank");
ODocument bank2 = database.newInstance("Account");
bank.field("embedded", bank2, OType.EMBEDDED);
bank.save();
database.commit();
database.close();
database.open("admin", "admin");
bank.reload();
Assert.assertTrue(((ODocument) bank.field("embedded")).isEmbedded());
Assert.assertFalse(((ODocument) bank.field("embedded")).getIdentity().isPersistent());
bank.delete();
}
@Test(dependsOnMethods = "cleanAll")
public void testUpdateInChain() {
ODocument bank = database.newInstance("Account");
bank.field("name", "MyBankChained");
// EMBEDDED
ODocument embedded = database.newInstance("Account").field("name", "embedded1");
bank.field("embedded", embedded, OType.EMBEDDED);
ODocument[] embeddeds = new ODocument[] { database.newInstance("Account").field("name", "embedded2"),
database.newInstance("Account").field("name", "embedded3") };
bank.field("embeddeds", embeddeds, OType.EMBEDDEDLIST);
// LINKED
ODocument linked = database.newInstance("Account").field("name", "linked1");
bank.field("linked", linked);
ODocument[] linkeds = new ODocument[] { database.newInstance("Account").field("name", "linked2"),
database.newInstance("Account").field("name", "linked3") };
bank.field("linkeds", linkeds, OType.LINKLIST);
bank.save();
database.close();
database.open("admin", "admin");
bank.reload();
ODocument changedDoc1 = bank.field("embedded.total", 100);
// MUST CHANGE THE PARENT DOC BECAUSE IT'S EMBEDDED
Assert.assertEquals(changedDoc1.field("name"), "MyBankChained");
Assert.assertEquals(changedDoc1.field("embedded.total"), 100);
ODocument changedDoc2 = bank.field("embeddeds.total", 200);
// MUST CHANGE THE PARENT DOC BECAUSE IT'S EMBEDDED
Assert.assertEquals(changedDoc2.field("name"), "MyBankChained");
Collection<Integer> intEmbeddeds = changedDoc2.field("embeddeds.total");
for (Integer e : intEmbeddeds)
Assert.assertEquals(e.intValue(), 200);
ODocument changedDoc3 = bank.field("linked.total", 300);
// MUST CHANGE THE LINKED DOCUMENT
Assert.assertEquals(changedDoc3.field("name"), "linked1");
Assert.assertEquals(changedDoc3.field("total"), 300);
try {
bank.field("linkeds.total", 400);
Assert.assertTrue(false);
} catch (IllegalArgumentException e) {
// MUST THROW AN EXCEPTION
Assert.assertTrue(true);
}
((ODocument) bank.field("linked")).delete();
for (ODocument l : (Collection<ODocument>) bank.field("linkeds"))
l.delete();
bank.delete();
}
public void testSerialization() {
ORecordSerializer current = ODatabaseDocumentTx.getDefaultSerializer();
ODatabaseDocumentTx.setDefaultSerializer(ORecordSerializerSchemaAware2CSV.INSTANCE);
ODatabaseDocumentInternal oldDb = ODatabaseRecordThreadLocal.INSTANCE.get();
ORecordSerializer dbser = oldDb.getSerializer();
((ODatabaseDocumentTx) oldDb).setSerializer(ORecordSerializerSchemaAware2CSV.INSTANCE);
final byte[] streamOrigin = "Account@html:{\"path\":\"html/layout\"},config:{\"title\":\"Github Admin\",\"modules\":(githubDisplay:\"github_display\")},complex:(simple1:\"string1\",one_level1:(simple2:\"string2\"),two_levels:(simple3:\"string3\",one_level2:(simple4:\"string4\")))"
.getBytes();
ODocument doc = (ODocument) ORecordSerializerSchemaAware2CSV.INSTANCE.fromStream(streamOrigin, new ODocument(), null);
doc.field("out");
final byte[] streamDest = ORecordSerializerSchemaAware2CSV.INSTANCE.toStream(doc, false);
Assert.assertEquals(streamOrigin, streamDest);
ODatabaseDocumentTx.setDefaultSerializer(current);
((ODatabaseDocumentTx) oldDb).setSerializer(dbser);
}
public void testUpdateNoVersionCheck() {
List<ODocument> result = database.query(new OSQLSynchQuery<ODocument>("select from Account"));
ODocument doc = result.get(0);
doc.field("name", "modified");
int oldVersion = doc.getVersion();
ORecordVersion recordVersion = OVersionFactory.instance().createVersion();
recordVersion.setCounter(-2);
doc.getRecordVersion().copyFrom(recordVersion);
doc.save();
doc.reload();
Assert.assertEquals(doc.getVersion(), oldVersion);
Assert.assertEquals(doc.field("name"), "modified");
}
public void testCreateEmbddedClassDocument() {
final OSchema schema = database.getMetadata().getSchema();
final String SUFFIX = "TESTCLUSTER1";
OClass testClass1 = schema.createClass("testCreateEmbddedClass1");
OClass testClass2 = schema.createClass("testCreateEmbddedClass2");
testClass2.createProperty("testClass1Property", OType.EMBEDDED, testClass1);
int clusterId = database.addCluster("testCreateEmbddedClass2" + SUFFIX);
schema.getClass("testCreateEmbddedClass2").addClusterId(clusterId);
testClass1 = schema.getClass("testCreateEmbddedClass1");
testClass2 = schema.getClass("testCreateEmbddedClass2");
ODocument testClass2Document = new ODocument(testClass2);
testClass2Document.field("testClass1Property", new ODocument(testClass1));
testClass2Document.save("testCreateEmbddedClass2" + SUFFIX);
testClass2Document = database.load(testClass2Document.getIdentity(), "*:-1", true);
Assert.assertNotNull(testClass2Document);
Assert.assertEquals(testClass2Document.getSchemaClass(), testClass2);
ODocument embeddedDoc = testClass2Document.field("testClass1Property");
Assert.assertEquals(embeddedDoc.getSchemaClass(), testClass1);
}
public void testRemoveAllLinkList() {
final ODocument doc = new ODocument();
final List<ODocument> allDocs = new ArrayList<ODocument>();
for (int i = 0; i < 10; i++) {
final ODocument linkDoc = new ODocument();
linkDoc.save();
allDocs.add(linkDoc);
}
doc.field("linkList", allDocs);
doc.save();
doc.reload();
final List<ODocument> docsToRemove = new ArrayList<ODocument>(allDocs.size() / 2);
for (int i = 0; i < 5; i++)
docsToRemove.add(allDocs.get(i));
List<OIdentifiable> linkList = doc.field("linkList");
linkList.removeAll(docsToRemove);
Assert.assertEquals(linkList.size(), 5);
for (int i = 5; i < 10; i++)
Assert.assertEquals(linkList.get(i - 5), allDocs.get(i));
doc.save();
doc.reload();
linkList = doc.field("linkList");
Assert.assertEquals(linkList.size(), 5);
for (int i = 5; i < 10; i++)
Assert.assertEquals(linkList.get(i - 5), allDocs.get(i));
}
public void testRemoveAndReload() {
ODocument doc1;
database.begin();
{
doc1 = new ODocument();
doc1.save();
}
database.commit();
database.begin();
{
database.delete(doc1);
}
database.commit();
database.begin();
{
ODocument deletedDoc = database.load(doc1.getIdentity());
Assert.assertNull(deletedDoc); // OK!
}
database.commit();
database.begin();
try {
doc1.reload();
Assert.fail(); // <=================== AssertionError
} catch (ORecordNotFoundException e) {
// OK
// The JavaDoc of #reload() is documented : "If the record does not exist a ORecordNotFoundException exception is thrown.".
}
database.commit();
}
private ODocument testInvalidFetchPlanInvalidateL1Cache(ODocument doc, ORID docRid) {
try {
// LOAD DOCUMENT, CHECK BEFORE GETTING IT FROM L1 CACHE
doc = database.load(docRid, "invalid");
Assert.fail("Should throw IllegalArgumentException");
} catch (Exception e) {
}
// INVALIDATE L1 CACHE TO CHECK THE L2 CACHE
database.getLocalCache().invalidate();
try {
// LOAD DOCUMENT, CHECK BEFORE GETTING IT FROM L2 CACHE
doc = database.load(docRid, "invalid");
Assert.fail("Should throw IllegalArgumentException");
} catch (Exception e) {
}
// CLEAR THE L2 CACHE TO CHECK THE RAW READ
try {
// LOAD DOCUMENT NOT IN ANY CACHE
doc = database.load(docRid, "invalid");
Assert.fail("Should throw IllegalArgumentException");
} catch (Exception e) {
}
return doc;
}
private ODocument testInvalidFetchPlanClearL1Cache(ODocument doc, ORID docRid) {
try {
// LOAD DOCUMENT NOT IN ANY CACHE
doc = database.load(docRid, "invalid");
Assert.fail("Should throw IllegalArgumentException");
} catch (Exception e) {
}
// LOAD DOCUMENT, THIS WILL PUT IT IN L1 CACHE
try {
database.load(docRid);
} catch (Exception e) {
}
try {
// LOAD DOCUMENT, CHECK BEFORE GETTING IT FROM L1 CACHE
doc = database.load(docRid, "invalid");
Assert.fail("Should throw IllegalArgumentException");
} catch (Exception e) {
}
// CLEAR L1 CACHE, THIS WILL PUT IT IN L2 CACHE
database.getLocalCache().clear();
try {
// LOAD DOCUMENT, CHECK BEFORE GETTING IT FROM L2 CACHE
doc = database.load(docRid, "invalid");
Assert.fail("Should throw IllegalArgumentException");
} catch (Exception e) {
}
try {
// LOAD DOCUMENT NOT IN ANY CACHE
doc = database.load(docRid, "invalid");
Assert.fail("Should throw IllegalArgumentException");
} catch (Exception e) {
}
return doc;
}
}
|
|
/*
* Parallelising JVM Compiler
*
* Copyright 2010 Peter Calvert, University of Cambridge
*
* 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 graph;
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2007 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Class to represent Java types. This class is derived from the
* org.objectweb.asm.Type class distributed as part of ASM 3.2, but includes
* modifications so that types can be unified. This is useful as part of array
* type reconstruction.
*
* @author Eric Bruneton
* @author Chris Nokleberg
* @author Peter Calvert
*/
public class Type {
/**
* Enumeration of basic primitive Java types.
*/
public enum Sort {
BOOL, BYTE, CHAR, SHORT, INT, FLOAT, REF, ADDR, LONG, DOUBLE;
}
/**
* The <tt>void</tt> type.
*/
public static final Type VOID = new Type((Sort) null);
/**
* The <tt>boolean</tt> type.
*/
public static final Type BOOL = new Type(Sort.BOOL);
/**
* The <tt>char</tt> type.
*/
public static final Type CHAR = new Type(Sort.CHAR);
/**
* The <tt>byte</tt> type.
*/
public static final Type BYTE = new Type(Sort.BYTE);
/**
* The <tt>short</tt> type.
*/
public static final Type SHORT = new Type(Sort.SHORT);
/**
* The <tt>int</tt> type.
*/
public static final Type INT = new Type(Sort.INT);
/**
* The <tt>float</tt> type.
*/
public static final Type FLOAT = new Type(Sort.FLOAT);
/**
* The <tt>long</tt> type.
*/
public static final Type LONG = new Type(Sort.LONG);
/**
* The <tt>double</tt> type.
*/
public static final Type DOUBLE = new Type(Sort.DOUBLE);
/**
* Reference types.
*/
public static final Type REF = getFreshRef();
/**
* Sort of the type.
*/
private final Sort sort;
/**
* Constructs a primitive type.
*
* @param Sort the primitive type to be constructed.
*/
private Type(final Sort sort) {
this.sort = sort;
}
//////////////////////////////////////////////////////////////////////////////
/**
* A buffer containing the internal name of this Java type.
*/
private char[] buf = null;
/**
* The offset of the internal name of this Java type in {@link #buf buf}.
*/
private int off = 0;
/**
* The length of the internal name of this Java type.
*/
private int len = 0;
/**
* Constructs a reference type.
*
* @param buf Buffer containing the descriptor of the object type.
* @param off Offset of this descriptor in the buffer.
* @param len Length of this descriptor.
*/
private Type(final char[] buf, final int off,final int len) {
this.sort = Sort.REF;
this.buf = buf;
this.off = off;
this.len = len;
}
/**
* Returns the internal name of the class corresponding to this object type.
* The internal name of a class is its fully qualified name (as returned by
* Class.getName(), where '.' are replaced by '/'.
*
* @return Internal name of the class corresponding to this object type.
*/
public String getInternalName() {
// Objects
if(buf != null) {
return new String(buf, off, len);
// Array
} else if(element != null) {
return getDescriptor();
// Other
} else {
throw new RuntimeException("Primitive Types don't have internal name");
}
}
/**
* Returns the name of the class corresponding to this object type.
*
* @return Fully qualified name of the class corresponding to this type.
*/
public String getClassName() {
return new String(buf, off, len).replace('/', '.');
}
/**
* Returns the ClassNode corresponding to this type.
*
* @return ClassNode object.
*/
public ClassNode getClassNode() {
if(isArray() || (sort != Sort.REF)) {
return null;
} else {
return ClassNode.getClass(getInternalName());
}
}
////////////////////////////////////////////////////////////////////////////////
/**
* Type of elements within the array.
*/
private Type element;
/**
* Constructs an array type.
*
* @param et Element type.
*/
private Type(final Type et) {
this.sort = Sort.REF;
this.element = et;
}
/**
* Returns the number of dimensions of this type. This is defined as 0 for
* non-array types, and is defined recursively for arrays.
*
* @return Number of dimensions of this array type.
*/
public int getDimensions() {
if(element != null) {
return 1 + element.getDimensions();
} else {
return 0;
}
}
/**
* Returns the type of the elements of this array type.
*
* @return Type of the elements of this array type.
*/
public Type getElementType() {
return element;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Determines whether the type is represented by an integer on the operand
* stack.
*
* @return <code>true</code> if represented as an integer,
* <code>false</code> otherwise.
*/
public boolean isIntBased() {
return equals(CHAR) || equals(BYTE) || equals(SHORT) || equals(INT)
|| equals(BOOL);
}
/**
* Determines whether the array is an array type.
*
* @return <code>true</code> if an array, <code>false</code> otherwise.
*/
public boolean isArray() {
return (element != null);
}
/**
* Returns <code>true</code> if the type is a supertype of that given.
*
* @param type Type to compare to.
* @return <code>true</code> if the type is a supertype,
* <code>false</code> otherwise.
*/
public boolean isSuperType(Type type) {
// Equal.
if(equals(type)) {
return true;
}
// Only possible for reference types.
if((sort != Sort.REF) || (type.sort != Sort.REF)) {
return false;
}
// java.lang.Object is a supertype of everything
if(equals(REF)) {
return true;
// If both arrays, recurse
} else if(isArray() && type.isArray()) {
return element.isSuperType(type.element);
// If both objects, check superclass sets.
} else if(!isArray() && !type.isArray()) {
return getClassNode().isSuperClass(type.getClassNode());
}
return false;
}
public void unify(Type type) {
unify(type, true);
}
/**
* Unifies the type with the given type. This is the sole way of altering a
* type object. A parameter specifies whether the given type can also be
* modified. If so, this function ensures that the two types are
* interchangable, if not, then it ensures that the type can be used as if it
* were of the argument type (i.e. that the argument type is a super type of
* it).
*
* @param type Type to unify with.
* @param modify Whether to allow modification of type argument.
*/
public void unify(Type type, boolean modify) {
// Already equal.
if(equals(type)) {
return;
}
// Both integer based, so can be used interchangibly.
if(isIntBased() && type.isIntBased()) {
return;
}
// Only possible for reference types.
if((sort != Sort.REF) || (type.sort != Sort.REF)) {
throw new RuntimeException("Can only unify reference types");
}
// Perform unification in correct direction.
if(isSuperType(type)) {
// Don't modify REF
if(this == REF) {
throw new RuntimeException("Can't modify REF, use getFreshRef()");
}
this.buf = type.buf;
this.off = type.off;
this.len = type.len;
this.element = type.element;
} else if(type.isSuperType(this)) {
if(modify) {
// Don't modify REF
if(type == REF) {
throw new RuntimeException("Can't modify REF, use getFreshRef()");
}
type.buf = this.buf;
type.off = this.off;
type.len = this.len;
type.element = this.element;
}
} else {
throw new RuntimeException("Unification failed (" + this + " with " + type + ")");
}
}
/**
* Returns the sort of this Java type.
*
* @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN},
* {@link #CHAR CHAR}, {@link #BYTE BYTE}, {@link #SHORT SHORT},
* {@link #INT INT}, {@link #FLOAT FLOAT}, {@link #LONG LONG},
* {@link #DOUBLE DOUBLE}, {@link #ARRAY ARRAY} or
* {@link #OBJECT OBJECT}.
*/
public Sort getSort() {
return sort;
}
/**
* Returns the size of values of this type.
*
* @return Size of values of this type (i.e., 2 for <tt>long</tt> and
* <tt>double</tt>), and 1 otherwise.
*/
public int getSize() {
if((sort == Sort.LONG) || (sort == Sort.DOUBLE)) {
return 2;
} else {
return 1;
}
}
/**
* Returns the descriptor corresponding to this Java type.
*
* @return the descriptor corresponding to this Java type.
*/
public String getDescriptor() {
StringBuffer sbuf = new StringBuffer();
getDescriptor(sbuf);
return sbuf.toString();
}
/**
* Appends the descriptor corresponding to this Java type to the given
* string buffer.
*
* @param buf String buffer to which the descriptor must be appended.
*/
protected void getDescriptor(final StringBuffer sbuf) {
if(sort == null) {
sbuf.append('V');
} else {
switch(sort) {
// Primitive Types
case BOOL: sbuf.append('Z'); return;
case CHAR: sbuf.append('C'); return;
case BYTE: sbuf.append('B'); return;
case SHORT: sbuf.append('S'); return;
case INT: sbuf.append('I'); return;
case FLOAT: sbuf.append('F'); return;
case LONG: sbuf.append('J'); return;
case DOUBLE:sbuf.append('D'); return;
// Reference Types
case REF:
// Object
if(element == null) {
sbuf.append('L');
sbuf.append(buf, off, len);
sbuf.append(';');
// Array
} else {
sbuf.append('[');
element.getDescriptor(sbuf);
}
}
}
}
/**
* Returns a 'fresh' reference type. This is identical to Type.REF, except
* that it can be modified using unify().
*
* @return Fresh reference type.
*/
public static Type getFreshRef() {
return getType("Ljava/lang/Object;");
}
/**
* Returns the Java type corresponding to the given type descriptor.
*
* @param descriptor Type descriptor.
* @return Corresponding type.
*/
public static Type getType(final String descriptor) {
return getType(descriptor.toCharArray(), 0);
}
/**
* Returns the Java type corresponding to the given type descriptor.
*
* @param buf Buffer containing a type descriptor.
* @param off Offset of this descriptor in the buffer.
* @return Type corresponding to the given type descriptor.
*/
private static Type getType(final char[] buf, final int off) {
switch(buf[off]) {
// Primitive Types
case 'V': return VOID;
case 'Z': return BOOL;
case 'C': return CHAR;
case 'B': return BYTE;
case 'S': return SHORT;
case 'I': return INT;
case 'F': return FLOAT;
case 'J': return LONG;
case 'D': return DOUBLE;
// Array Types
case '[': return new Type(getType(buf, off + 1));
// Object Types
case 'L':
default:
int len = 1;
while(buf[off + len] != ';') {
++len;
}
return new Type(buf, off + 1, len - 1);
}
}
/**
* Returns the Java type corresponding to the given internal name.
*
* @param internalName an internal name.
* @return the Java type corresponding to the given internal name.
*/
public static Type getObjectType(final String internalName) {
char[] buf = internalName.toCharArray();
// Arrays
if(buf[0] == '[') {
return getType(internalName);
// Objects
} else {
return new Type(buf, 0, buf.length);
}
}
/**
* Returns the array type where each element is of the given type.
*
* @param type Element type.
* @return Array type.
*/
public static Type getArrayOf(Type type) {
return new Type(type);
}
/**
* Returns the Java types corresponding to the parameter types of the given
* method descriptor.
*
* @param desc Method descriptor.
* @return Types corresponding to the parameter types of the given
* method descriptor.
*/
public static Type[] getParameterTypes(final String desc) {
char[] buf = desc.toCharArray();
int off = 1;
int size = 0;
while (true) {
char car = buf[off++];
if (car == ')') {
break;
} else if (car == 'L') {
while(buf[off++] != ';') {}
++size;
} else if (car != '[') {
++size;
}
}
Type[] args = new Type[size];
off = 1;
size = 0;
while (buf[off] != ')') {
args[size] = getType(buf, off);
off += args[size].getDescriptor().length();
size += 1;
}
return args;
}
/**
* Returns the Java type corresponding to the return type of the given
* method descriptor.
*
* @param desc Method descriptor.
* @return Type corresponding to the return type of the given method
* descriptor.
*/
public static Type getReturnType(final String desc) {
char[] buf = desc.toCharArray();
return getType(buf, desc.indexOf(')') + 1);
}
/**
* Returns the descriptor corresponding to the given argument and return
* types.
*
* @param args Argument types of the method.
* @param ret Return type of the method.
* @return Descriptor corresponding to the given argument and return
* types.
*/
public static String getMethodDescriptor(final Type[] args, final Type ret) {
StringBuffer buf = new StringBuffer();
buf.append('(');
for(final Type arg : args) {
arg.getDescriptor(buf);
}
buf.append(')');
ret.getDescriptor(buf);
return buf.toString();
}
/**
* Tests if the given object is equal to this type.
*
* @param o Object to be compared to this type.
* @return <tt>true</tt> if the given object is equal to this type.
*/
@Override
public boolean equals(final Object o) {
if(o instanceof Type) {
return getDescriptor().equals(((Type) o).getDescriptor());
} else {
return false;
}
}
/**
* Returns a hash code value for this type.
*
* @return Hash code value for this type.
*/
@Override
public int hashCode() {
return getDescriptor().hashCode();
}
/**
* Returns the textual descriptor of the type, as its standard string
* representation.
*
* @return Type descriptor.
*/
@Override
public String toString() {
return getDescriptor();
}
}
|
|
package com.liuguangqiang.recyclerview;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* A RecyclerView.Adapter that allows for headers and footers as well.
* <p>
* This class wraps a base adapter that's passed into the constructor. It works by creating extra view items types
* that are returned in {@link #getItemViewType(int)}, and mapping these to the header and footer views provided via
* {@link #addHeader(View)} and {@link #addFooter(View)}.
* <p>
* There are two restrictions when using this class:
* <p>
* 1) The base adapter can't use negative view types, since this class uses negative view types to keep track
* of header and footer views.
* <p>
* 2) You can't add more than 1000 headers or footers.
* <p>
*/
public class Bookends<T extends RecyclerView.Adapter> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final T mBase;
/**
* Defines available view type integers for headers and footers.
* <p>
* How this works:
* - Regular views use view types starting from 0, counting upwards
* - Header views use view types starting from -1000, counting upwards
* - Footer views use view types starting from -2000, counting upwards
* <p>
* This means that you're safe as long as the base adapter doesn't use negative view types,
* and as long as you have fewer than 1000 headers and footers
*/
private static final int HEADER_VIEW_TYPE = -1000;
private static final int FOOTER_VIEW_TYPE = -2000;
private final List<View> mHeaders = new ArrayList<>();
private final List<View> mFooters = new ArrayList<>();
/**
* Constructor.
*
* @param base the adapter to wrap
*/
public Bookends(T base) {
super();
mBase = base;
}
/**
* Gets the base adapter that this is wrapping.
*/
public T getWrappedAdapter() {
return mBase;
}
/**
* Adds a header view.
*/
public void addHeader(@NonNull View view) {
if (view == null) {
throw new IllegalArgumentException("You can't have a null header!");
}
mHeaders.add(view);
}
/**
* Adds a footer view.
*/
public void addFooter(@NonNull View view) {
if (view == null) {
throw new IllegalArgumentException("You can't have a null footer!");
}
mFooters.add(view);
}
public void removeHeader(@NonNull View view) {
if (view == null) {
throw new IllegalArgumentException("You can't remove a null header!");
}
mHeaders.remove(view);
}
public void removeFooter(@NonNull View view) {
if (view == null) {
throw new IllegalArgumentException("You can't remove a null footer!");
}
mFooters.remove(view);
}
/**
* Toggles the visibility of the header views.
*/
public void setHeaderVisibility(boolean shouldShow) {
for (View header : mHeaders) {
header.setVisibility(shouldShow ? View.VISIBLE : View.GONE);
}
}
public void setHeaderVisibility(View view, boolean shouldShow) {
for (View header : mHeaders) {
if (header == view) {
header.setVisibility(shouldShow ? View.VISIBLE : View.GONE);
}
}
}
/**
* Toggles the visibility of the footer views.
*/
public void setFooterVisibility(boolean shouldShow) {
for (View footer : mFooters) {
footer.setVisibility(shouldShow ? View.VISIBLE : View.GONE);
}
}
public void setFooterVisibility(View view, boolean shouldShow) {
for (View footer : mFooters) {
if (footer == view) {
footer.setVisibility(shouldShow ? View.VISIBLE : View.GONE);
}
}
}
/**
* @return the number of headers.
*/
public int getHeaderCount() {
return mHeaders.size();
}
/**
* @return the number of footers.
*/
public int getFooterCount() {
return mFooters.size();
}
/**
* Gets the indicated header, or null if it doesn't exist.
*/
public View getHeader(int i) {
return i < mHeaders.size() ? mHeaders.get(i) : null;
}
/**
* Gets the indicated footer, or null if it doesn't exist.
*/
public View getFooter(int i) {
return i < mFooters.size() ? mFooters.get(i) : null;
}
private boolean isHeader(int viewType) {
return viewType >= HEADER_VIEW_TYPE && viewType < (HEADER_VIEW_TYPE + mHeaders.size());
}
private boolean isFooter(int viewType) {
return viewType >= FOOTER_VIEW_TYPE && viewType < (FOOTER_VIEW_TYPE + mFooters.size());
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (isHeader(viewType)) {
int whichHeader = Math.abs(viewType - HEADER_VIEW_TYPE);
View headerView = mHeaders.get(whichHeader);
return new RecyclerView.ViewHolder(headerView) {
};
} else if (isFooter(viewType)) {
int whichFooter = Math.abs(viewType - FOOTER_VIEW_TYPE);
View footerView = mFooters.get(whichFooter);
return new RecyclerView.ViewHolder(footerView) {
};
} else {
return mBase.onCreateViewHolder(viewGroup, viewType);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
if (position < mHeaders.size()) {
// Headers don't need anything special
} else if (position < mHeaders.size() + mBase.getItemCount()) {
// This is a real position, not a header or footer. Bind it.
mBase.onBindViewHolder(viewHolder, position - mHeaders.size());
} else {
// Footers don't need anything special
}
}
@Override
public int getItemCount() {
return mHeaders.size() + mBase.getItemCount() + mFooters.size();
}
@Override
public int getItemViewType(int position) {
if (position < mHeaders.size()) {
return HEADER_VIEW_TYPE + position;
} else if (position < (mHeaders.size() + mBase.getItemCount())) {
return mBase.getItemViewType(position - mHeaders.size());
} else {
return FOOTER_VIEW_TYPE + position - mHeaders.size() - mBase.getItemCount();
}
}
}
|
|
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import javax.sql.DataSource;
import junit.framework.AssertionFailedError;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.util.Assert;
/**
* <p>
* Java 5 specific subclass of
* {@link AbstractTransactionalDataSourceSpringContextTests}, exposing a
* {@link SimpleJdbcTemplate} and obeying annotations for transaction control.
* </p>
* <p>
* For example, test methods can be annotated with the regular Spring
* {@link org.springframework.transaction.annotation.Transactional @Transactional}
* annotation (e.g., to force execution in a read-only transaction) or with the
* {@link NotTransactional @NotTransactional} annotation to prevent any
* transaction being created at all. In addition, individual test methods can be
* annotated with {@link Rollback @Rollback} to override the
* {@link #isDefaultRollback() default rollback} settings.
* </p>
* <p>
* The following list constitutes all annotations currently supported by
* AbstractAnnotationAwareTransactionalTests:
* </p>
* <ul>
* <li>{@link DirtiesContext @DirtiesContext}</li>
* <li>{@link ProfileValueSourceConfiguration @ProfileValueSourceConfiguration}</li>
* <li>{@link IfProfileValue @IfProfileValue}</li>
* <li>{@link ExpectedException @ExpectedException}</li>
* <li>{@link Timed @Timed}</li>
* <li>{@link Repeat @Repeat}</li>
* <li>{@link org.springframework.transaction.annotation.Transactional @Transactional}</li>
* <li>{@link NotTransactional @NotTransactional}</li>
* <li>{@link Rollback @Rollback}</li>
* </ul>
*
* @author Rod Johnson
* @author Sam Brannen
* @author Juergen Hoeller
* @since 2.0
*/
public abstract class AbstractAnnotationAwareTransactionalTests extends
AbstractTransactionalDataSourceSpringContextTests {
protected SimpleJdbcTemplate simpleJdbcTemplate;
private final TransactionAttributeSource transactionAttributeSource = new AnnotationTransactionAttributeSource();
/**
* {@link ProfileValueSource} available to subclasses but primarily intended
* for use in {@link #isDisabledInThisEnvironment(Method)}.
* <p>Set to {@link SystemProfileValueSource} by default for backwards
* compatibility; however, the value may be changed in the
* {@link #AbstractAnnotationAwareTransactionalTests(String)} constructor.
*/
protected ProfileValueSource profileValueSource = SystemProfileValueSource.getInstance();
/**
* Default constructor for AbstractAnnotationAwareTransactionalTests, which
* delegates to {@link #AbstractAnnotationAwareTransactionalTests(String)}.
*/
public AbstractAnnotationAwareTransactionalTests() {
this(null);
}
/**
* Constructs a new AbstractAnnotationAwareTransactionalTests instance with
* the specified JUnit <code>name</code> and retrieves the configured (or
* default) {@link ProfileValueSource}.
* @param name the name of the current test
* @see ProfileValueUtils#retrieveProfileValueSource(Class)
*/
public AbstractAnnotationAwareTransactionalTests(String name) {
super(name);
this.profileValueSource = ProfileValueUtils.retrieveProfileValueSource(getClass());
}
@Override
public void setDataSource(DataSource dataSource) {
super.setDataSource(dataSource);
// JdbcTemplate will be identically configured
this.simpleJdbcTemplate = new SimpleJdbcTemplate(this.jdbcTemplate);
}
/**
* Search for a unique {@link ProfileValueSource} in the supplied
* {@link ApplicationContext}. If found, the
* <code>profileValueSource</code> for this test will be set to the unique
* {@link ProfileValueSource}.
* @param applicationContext the ApplicationContext in which to search for
* the ProfileValueSource; may not be <code>null</code>
* @deprecated Use {@link ProfileValueSourceConfiguration @ProfileValueSourceConfiguration} instead.
*/
@Deprecated
protected void findUniqueProfileValueSourceFromContext(ApplicationContext applicationContext) {
Assert.notNull(applicationContext, "Can not search for a ProfileValueSource in a null ApplicationContext.");
ProfileValueSource uniqueProfileValueSource = null;
Map<?, ?> beans = applicationContext.getBeansOfType(ProfileValueSource.class);
if (beans.size() == 1) {
uniqueProfileValueSource = (ProfileValueSource) beans.values().iterator().next();
}
if (uniqueProfileValueSource != null) {
this.profileValueSource = uniqueProfileValueSource;
}
}
/**
* Overridden to populate transaction definition from annotations.
*/
@Override
public void runBare() throws Throwable {
// getName will return the name of the method being run.
if (isDisabledInThisEnvironment(getName())) {
// Let superclass log that we didn't run the test.
super.runBare();
return;
}
final Method testMethod = getTestMethod();
if (isDisabledInThisEnvironment(testMethod)) {
recordDisabled();
this.logger.info("**** " + getClass().getName() + "." + getName() + " disabled in this environment: "
+ "Total disabled tests=" + getDisabledTestCount());
return;
}
TransactionDefinition explicitTransactionDefinition =
this.transactionAttributeSource.getTransactionAttribute(testMethod, getClass());
if (explicitTransactionDefinition != null) {
this.logger.info("Custom transaction definition [" + explicitTransactionDefinition + "] for test method ["
+ getName() + "].");
setTransactionDefinition(explicitTransactionDefinition);
}
else if (testMethod.isAnnotationPresent(NotTransactional.class)) {
// Don't have any transaction...
preventTransaction();
}
// Let JUnit handle execution. We're just changing the state of the test class first.
runTestTimed(new TestExecutionCallback() {
public void run() throws Throwable {
try {
AbstractAnnotationAwareTransactionalTests.super.runBare();
}
finally {
// Mark the context to be blown away if the test was
// annotated to result in setDirty being invoked
// automatically.
if (testMethod.isAnnotationPresent(DirtiesContext.class)) {
AbstractAnnotationAwareTransactionalTests.this.setDirty();
}
}
}
}, testMethod);
}
/**
* Determine if the test for the supplied <code>testMethod</code> should
* run in the current environment.
* <p>The default implementation is based on
* {@link IfProfileValue @IfProfileValue} semantics.
* @param testMethod the test method
* @return <code>true</code> if the test is <em>disabled</em> in the current environment
* @see ProfileValueUtils#isTestEnabledInThisEnvironment
*/
protected boolean isDisabledInThisEnvironment(Method testMethod) {
return !ProfileValueUtils.isTestEnabledInThisEnvironment(this.profileValueSource, testMethod, getClass());
}
/**
* Get the current test method.
*/
protected Method getTestMethod() {
assertNotNull("TestCase.getName() cannot be null", getName());
Method testMethod = null;
try {
// Use same algorithm as JUnit itself to retrieve the test method
// about to be executed (the method name is returned by getName). It
// has to be public so we can retrieve it.
testMethod = getClass().getMethod(getName(), (Class[]) null);
}
catch (NoSuchMethodException ex) {
fail("Method '" + getName() + "' not found");
}
if (!Modifier.isPublic(testMethod.getModifiers())) {
fail("Method '" + getName() + "' should be public");
}
return testMethod;
}
/**
* Determine whether or not to rollback transactions for the current test
* by taking into consideration the
* {@link #isDefaultRollback() default rollback} flag and a possible
* method-level override via the {@link Rollback @Rollback} annotation.
* @return the <em>rollback</em> flag for the current test
*/
@Override
protected boolean isRollback() {
boolean rollback = isDefaultRollback();
Rollback rollbackAnnotation = getTestMethod().getAnnotation(Rollback.class);
if (rollbackAnnotation != null) {
boolean rollbackOverride = rollbackAnnotation.value();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Method-level @Rollback(" + rollbackOverride + ") overrides default rollback ["
+ rollback + "] for test [" + getName() + "].");
}
rollback = rollbackOverride;
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("No method-level @Rollback override: using default rollback [" + rollback
+ "] for test [" + getName() + "].");
}
}
return rollback;
}
private void runTestTimed(TestExecutionCallback tec, Method testMethod) throws Throwable {
Timed timed = testMethod.getAnnotation(Timed.class);
if (timed == null) {
runTest(tec, testMethod);
}
else {
long startTime = System.currentTimeMillis();
try {
runTest(tec, testMethod);
}
finally {
long elapsed = System.currentTimeMillis() - startTime;
if (elapsed > timed.millis()) {
fail("Took " + elapsed + " ms; limit was " + timed.millis());
}
}
}
}
private void runTest(TestExecutionCallback tec, Method testMethod) throws Throwable {
ExpectedException expectedExceptionAnnotation = testMethod.getAnnotation(ExpectedException.class);
boolean exceptionIsExpected = (expectedExceptionAnnotation != null && expectedExceptionAnnotation.value() != null);
Class<? extends Throwable> expectedException = (exceptionIsExpected ? expectedExceptionAnnotation.value() : null);
Repeat repeat = testMethod.getAnnotation(Repeat.class);
int runs = ((repeat != null) && (repeat.value() > 1)) ? repeat.value() : 1;
for (int i = 0; i < runs; i++) {
try {
if (runs > 1 && this.logger != null && this.logger.isInfoEnabled()) {
this.logger.info("Repetition " + (i + 1) + " of test " + testMethod.getName());
}
tec.run();
if (exceptionIsExpected) {
fail("Expected exception: " + expectedException.getName());
}
}
catch (Throwable t) {
if (!exceptionIsExpected) {
throw t;
}
if (!expectedException.isAssignableFrom(t.getClass())) {
// Wrap the unexpected throwable with an explicit message.
AssertionFailedError assertionError = new AssertionFailedError("Unexpected exception, expected<" +
expectedException.getName() + "> but was<" + t.getClass().getName() + ">");
assertionError.initCause(t);
throw assertionError;
}
}
}
}
private static interface TestExecutionCallback {
void run() throws Throwable;
}
}
|
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: mike
* Date: Aug 19, 2002
* Time: 8:21:52 PM
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij.openapi.application.ex;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.module.impl.ModuleManagerImpl;
import com.intellij.openapi.module.impl.ModulePath;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.Parameterized;
import com.intellij.testFramework.TestRunnerUtil;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import junit.framework.TestCase;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.serialization.JDomSerializationUtil;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName;
import static java.util.Arrays.asList;
public class PathManagerEx {
/**
* All IDEA project files may be logically divided by the following criteria:
* <ul>
* <li>files that are contained at <code>'community'</code> directory;</li>
* <li>all other files;</li>
* </ul>
* <p/>
* File location types implied by criteria mentioned above are enumerated here.
*/
private enum FileSystemLocation {
ULTIMATE, COMMUNITY
}
/**
* Caches test data lookup strategy by class.
*/
private static final ConcurrentMap<Class, TestDataLookupStrategy> CLASS_STRATEGY_CACHE = ContainerUtil.newConcurrentMap();
private static final ConcurrentMap<String, Class> CLASS_CACHE = ContainerUtil.newConcurrentMap();
private static Set<String> ourCommunityModules;
private PathManagerEx() { }
/**
* Enumerates possible strategies of test data lookup.
* <p/>
* Check member-level javadoc for more details.
*/
public enum TestDataLookupStrategy {
/**
* Stands for algorithm that retrieves <code>'test data'</code> stored at the <code>'ultimate'</code> project level assuming
* that it's used from the test running in context of <code>'ultimate'</code> project as well.
* <p/>
* Is assumed to be default strategy for all <code>'ultimate'</code> tests.
*/
ULTIMATE,
/**
* Stands for algorithm that retrieves <code>'test data'</code> stored at the <code>'community'</code> project level assuming
* that it's used from the test running in context of <code>'community'</code> project as well.
* <p/>
* Is assumed to be default strategy for all <code>'community'</code> tests.
*/
COMMUNITY,
/**
* Stands for algorithm that retrieves <code>'test data'</code> stored at the <code>'community'</code> project level assuming
* that it's used from the test running in context of <code>'ultimate'</code> project.
*/
COMMUNITY_FROM_ULTIMATE
}
/**
* It's assumed that test data location for both <code>community</code> and <code>ultimate</code> tests follows the same template:
* <code>'<IDEA_HOME>/<RELATIVE_PATH>'</code>.
* <p/>
* <code>'IDEA_HOME'</code> here stands for path to IDEA installation; <code>'RELATIVE_PATH'</code> defines a path to
* test data relative to IDEA installation path. That relative path may be different for <code>community</code>
* and <code>ultimate</code> tests.
* <p/>
* This collection contains mappings from test group type to relative paths to use, i.e. it's possible to define more than one
* relative path for the single test group. It's assumed that path definition algorithm iterates them and checks if
* resulting absolute path points to existing directory. The one is returned in case of success; last path is returned otherwise.
* <p/>
* Hence, the order of relative paths for the single test group matters.
*/
private static final Map<TestDataLookupStrategy, List<String>> TEST_DATA_RELATIVE_PATHS
= new EnumMap<>(TestDataLookupStrategy.class);
static {
TEST_DATA_RELATIVE_PATHS.put(TestDataLookupStrategy.ULTIMATE, Collections.singletonList(toSystemDependentName("testData")));
TEST_DATA_RELATIVE_PATHS.put(
TestDataLookupStrategy.COMMUNITY,
Collections.singletonList(toSystemDependentName("java/java-tests/testData"))
);
TEST_DATA_RELATIVE_PATHS.put(
TestDataLookupStrategy.COMMUNITY_FROM_ULTIMATE,
Collections.singletonList(toSystemDependentName("community/java/java-tests/testData"))
);
}
/**
* Shorthand for calling {@link #getTestDataPath(TestDataLookupStrategy)} with
* {@link #guessTestDataLookupStrategy() guessed} lookup strategy.
*
* @return test data path with {@link #guessTestDataLookupStrategy() guessed} lookup strategy
* @throws IllegalStateException as defined by {@link #getTestDataPath(TestDataLookupStrategy)}
*/
@NonNls
public static String getTestDataPath() throws IllegalStateException {
TestDataLookupStrategy strategy = guessTestDataLookupStrategy();
return getTestDataPath(strategy);
}
public static String getTestDataPath(String path) throws IllegalStateException {
return getTestDataPath() + path.replace('/', File.separatorChar);
}
/**
* Shorthand for calling {@link #getTestDataPath(TestDataLookupStrategy)} with strategy obtained via call to
* {@link #determineLookupStrategy(Class)} with the given class.
* <p/>
* <b>Note:</b> this method receives explicit class argument in order to solve the following limitation - we analyze calling
* stack trace in order to guess test data lookup strategy ({@link #guessTestDataLookupStrategyOnClassLocation()}). However,
* there is a possible case that super-class method is called on sub-class object. Stack trace shows super-class then.
* There is a possible situation that actual test is <code>'ultimate'</code> but its abstract super-class is
* <code>'community'</code>, hence, test data lookup is performed incorrectly. So, this method should be called from abstract
* base test class if its concrete sub-classes doesn't explicitly occur at stack trace.
*
*
* @param testClass target test class for which test data should be obtained
* @return base test data directory to use for the given test class
* @throws IllegalStateException as defined by {@link #getTestDataPath(TestDataLookupStrategy)}
*/
public static String getTestDataPath(Class<?> testClass) throws IllegalStateException {
TestDataLookupStrategy strategy = isLocatedInCommunity() ? TestDataLookupStrategy.COMMUNITY : determineLookupStrategy(testClass);
return getTestDataPath(strategy);
}
/**
* @return path to 'community' project home irrespective of current project
*/
@NotNull
public static String getCommunityHomePath() {
String path = PathManager.getHomePath();
return isLocatedInCommunity() ? path : path + File.separator + "community";
}
/**
* @return path to 'community' project home if {@code testClass} is located in the community project and path to 'ultimate' project otherwise
*/
public static String getHomePath(Class<?> testClass) {
TestDataLookupStrategy strategy = isLocatedInCommunity() ? TestDataLookupStrategy.COMMUNITY : determineLookupStrategy(testClass);
return strategy == TestDataLookupStrategy.COMMUNITY_FROM_ULTIMATE ? getCommunityHomePath() : PathManager.getHomePath();
}
/**
* Find file by its path relative to 'community' directory irrespective of current project
* @param relativePath path to file relative to 'community' directory
* @return file under the home directory of 'community' project
*/
public static File findFileUnderCommunityHome(String relativePath) {
File file = new File(getCommunityHomePath(), toSystemDependentName(relativePath));
if (!file.exists()) {
throw new IllegalArgumentException("Cannot find file '" + relativePath + "' under '" + getCommunityHomePath() + "' directory");
}
return file;
}
/**
* Find file by its path relative to project home directory (the 'community' project if {@code testClass} is located
* in the community project, and the 'ultimate' project otherwise)
*/
public static File findFileUnderProjectHome(String relativePath, Class<? extends TestCase> testClass) {
String homePath = getHomePath(testClass);
File file = new File(homePath, toSystemDependentName(relativePath));
if (!file.exists()) {
throw new IllegalArgumentException("Cannot find file '" + relativePath + "' under '" + homePath + "' directory");
}
return file;
}
private static boolean isLocatedInCommunity() {
FileSystemLocation projectLocation = parseProjectLocation();
return projectLocation == FileSystemLocation.COMMUNITY;
// There is no other options then.
}
/**
* Tries to return test data path for the given lookup strategy.
*
* @param strategy lookup strategy to use
* @return test data path for the given strategy
* @throws IllegalStateException if it's not possible to find valid test data path for the given strategy
*/
@NonNls
public static String getTestDataPath(TestDataLookupStrategy strategy) throws IllegalStateException {
String homePath = PathManager.getHomePath();
List<String> relativePaths = TEST_DATA_RELATIVE_PATHS.get(strategy);
if (relativePaths.isEmpty()) {
throw new IllegalStateException(
String.format("Can't determine test data path. Reason: no predefined relative paths are configured for test data "
+ "lookup strategy %s. Configured mappings: %s", strategy, TEST_DATA_RELATIVE_PATHS)
);
}
File candidate = null;
for (String relativePath : relativePaths) {
candidate = new File(homePath, relativePath);
if (candidate.isDirectory()) {
return candidate.getPath();
}
}
if (candidate == null) {
throw new IllegalStateException("Can't determine test data path. Looks like programming error - reached 'if' block that was "
+ "never expected to be executed");
}
return candidate.getPath();
}
/**
* Tries to guess test data lookup strategy for the current execution.
*
* @return guessed lookup strategy for the current execution; defaults to {@link TestDataLookupStrategy#ULTIMATE}
*/
public static TestDataLookupStrategy guessTestDataLookupStrategy() {
TestDataLookupStrategy result = guessTestDataLookupStrategyOnClassLocation();
if (result == null) {
result = guessTestDataLookupStrategyOnDirectoryAvailability();
}
return result;
}
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
@Nullable
private static TestDataLookupStrategy guessTestDataLookupStrategyOnClassLocation() {
if (isLocatedInCommunity()) return TestDataLookupStrategy.COMMUNITY;
// The general idea here is to find test class at the bottom of hierarchy and try to resolve test data lookup strategy
// against it. Rationale is that there is a possible case that, say, 'ultimate' test class extends basic test class
// that remains at 'community'. We want to perform the processing against 'ultimate' test class then.
// About special abstract classes processing - there is a possible case that target test class extends abstract base
// test class and call to this method is rooted from that parent. We need to resolve test data lookup against super
// class then, hence, we keep track of found abstract test class as well and fallback to it if no non-abstract class is found.
Class<?> testClass = null;
Class<?> abstractTestClass = null;
StackTraceElement[] stackTrace = new Exception().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
String className = stackTraceElement.getClassName();
Class<?> clazz = loadClass(className);
if (clazz == null || TestCase.class == clazz || !isJUnitClass(clazz)) {
continue;
}
if (determineLookupStrategy(clazz) == TestDataLookupStrategy.ULTIMATE) return TestDataLookupStrategy.ULTIMATE;
if ((clazz.getModifiers() & Modifier.ABSTRACT) == 0) {
testClass = clazz;
}
else {
abstractTestClass = clazz;
}
}
Class<?> classToUse = testClass == null ? abstractTestClass : testClass;
return classToUse == null ? null : determineLookupStrategy(classToUse);
}
@Nullable
private static Class<?> loadClass(String className) {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Class<?> clazz = CLASS_CACHE.get(className);
if (clazz != null) {
return clazz;
}
ClassLoader definingClassLoader = PathManagerEx.class.getClassLoader();
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
for (ClassLoader classLoader : asList(contextClassLoader, definingClassLoader, systemClassLoader)) {
clazz = loadClass(className, classLoader);
if (clazz != null) {
CLASS_CACHE.put(className, clazz);
return clazz;
}
}
CLASS_CACHE.put(className, TestCase.class); //dummy
return null;
}
@Nullable
private static Class<?> loadClass(String className, ClassLoader classLoader) {
try {
return Class.forName(className, true, classLoader);
}
catch (NoClassDefFoundError | ClassNotFoundException e) {
return null;
}
}
@SuppressWarnings("TestOnlyProblems")
private static boolean isJUnitClass(Class<?> clazz) {
return TestCase.class.isAssignableFrom(clazz) || TestRunnerUtil.isJUnit4TestClass(clazz) || Parameterized.class.isAssignableFrom(clazz);
}
@Nullable
private static TestDataLookupStrategy determineLookupStrategy(Class<?> clazz) {
// Check if resulting strategy is already cached for the target class.
TestDataLookupStrategy result = CLASS_STRATEGY_CACHE.get(clazz);
if (result != null) {
return result;
}
FileSystemLocation classFileLocation = computeClassLocation(clazz);
// We know that project location is ULTIMATE if control flow reaches this place.
result = classFileLocation == FileSystemLocation.COMMUNITY ? TestDataLookupStrategy.COMMUNITY_FROM_ULTIMATE
: TestDataLookupStrategy.ULTIMATE;
CLASS_STRATEGY_CACHE.put(clazz, result);
return result;
}
public static void replaceLookupStrategy(Class<?> substitutor, Class<?>... initial) {
CLASS_STRATEGY_CACHE.clear();
for (Class<?> aClass : initial) {
CLASS_STRATEGY_CACHE.put(aClass, determineLookupStrategy(substitutor));
}
}
private static FileSystemLocation computeClassLocation(Class<?> clazz) {
String classRootPath = PathManager.getJarPathForClass(clazz);
if (classRootPath == null) {
throw new IllegalStateException("Cannot find root directory for " + clazz);
}
File root = new File(classRootPath);
if (!root.exists()) {
throw new IllegalStateException("Classes root " + root + " doesn't exist");
}
if (!root.isDirectory()) {
//this means that clazz is located in a library, perhaps we should throw exception here
return FileSystemLocation.ULTIMATE;
}
String moduleName = root.getName();
String chunkPrefix = "ModuleChunk(";
if (moduleName.startsWith(chunkPrefix)) {
//todo[nik] this is temporary workaround to fix tests on TeamCity which compiles the whole modules cycle to a single output directory
moduleName = StringUtil.trimStart(moduleName, chunkPrefix);
moduleName = moduleName.substring(0, moduleName.indexOf(','));
}
return getCommunityModules().contains(moduleName) ? FileSystemLocation.COMMUNITY : FileSystemLocation.ULTIMATE;
}
private synchronized static Set<String> getCommunityModules() {
if (ourCommunityModules != null) {
return ourCommunityModules;
}
ourCommunityModules = new THashSet<>();
File modulesXml = findFileUnderCommunityHome(Project.DIRECTORY_STORE_FOLDER + "/modules.xml");
if (!modulesXml.exists()) {
throw new IllegalStateException("Cannot obtain test data path: " + modulesXml.getAbsolutePath() + " not found");
}
try {
Element element = JDomSerializationUtil.findComponent(JDOMUtil.load(modulesXml), ModuleManagerImpl.COMPONENT_NAME);
assert element != null;
for (ModulePath file : ModuleManagerImpl.getPathsToModuleFiles(element)) {
ourCommunityModules.add(file.getModuleName());
}
return ourCommunityModules;
}
catch (JDOMException | IOException e) {
throw new RuntimeException("Cannot read modules from " + modulesXml.getAbsolutePath(), e);
}
}
/**
* Allows to determine project type by its file system location.
*
* @return project type implied by its file system location
*/
private static FileSystemLocation parseProjectLocation() {
return new File(PathManager.getHomePath(), "community/.idea").isDirectory() ? FileSystemLocation.ULTIMATE : FileSystemLocation.COMMUNITY;
}
/**
* Tries to check test data lookup strategy by target test data directories availability.
* <p/>
* Such an approach has a drawback that it doesn't work correctly at number of scenarios, e.g. when
* <code>'community'</code> test is executed under <code>'ultimate'</code> project.
*
* @return test data lookup strategy based on target test data directories availability
*/
private static TestDataLookupStrategy guessTestDataLookupStrategyOnDirectoryAvailability() {
String homePath = PathManager.getHomePath();
for (Map.Entry<TestDataLookupStrategy, List<String>> entry : TEST_DATA_RELATIVE_PATHS.entrySet()) {
for (String relativePath : entry.getValue()) {
if (new File(homePath, relativePath).isDirectory()) {
return entry.getKey();
}
}
}
return TestDataLookupStrategy.ULTIMATE;
}
}
|
|
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.io.File;
import java.io.FilenameFilter;
import java.io.Reader;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import net.sourceforge.pmd.AbstractConfiguration;
import net.sourceforge.pmd.util.FileFinder;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.Parameter;
/**
*
* @author Brian Remedios
* @author Romain Pelisse - <[email protected]>
*/
public class CPDConfiguration extends AbstractConfiguration {
public final static String DEFAULT_LANGUAGE = "java";
public final static String DEFAULT_RENDERER = "text";
@Parameter(names = "--language", description = "Sources code language. Default value is "
+ DEFAULT_LANGUAGE, required = false, converter = LanguageConverter.class)
private Language language;
@Parameter(names = "--minimum-tokens", description = "The minimum token length which should be reported as a duplicate.", required = true)
private int minimumTileSize;
@Parameter(names = "--skip-duplicate-files", description = "Ignore multiple copies of files of the same name and length in comparison", required = false)
private boolean skipDuplicates;
@Parameter(names = "--format", description = "Report format. Default value is "
+ DEFAULT_RENDERER, required = false)
private String rendererName;
/**
* The actual renderer. constructed by using the {@link #rendererName}.
* This property is only valid after {@link #postContruct()} has been called!
*/
private Renderer renderer;
private String encoding;
@Parameter(names = "--ignore-literals", description = "Ignore number values and string contents when comparing text", required = false)
private boolean ignoreLiterals;
@Parameter(names = "--ignore-identifiers", description = "Ignore constant and variable names when comparing text", required = false)
private boolean ignoreIdentifiers;
@Parameter(names = "--ignore-annotations", description = "Ignore language annotations when comparing text", required = false)
private boolean ignoreAnnotations;
@Parameter(names = "--skip-lexical-errors", description = "Skip files which can't be tokenized due to invalid characters instead of aborting CPD", required = false)
private boolean skipLexicalErrors = false;
@Parameter(names = "--no-skip-blocks", description = "Do not skip code blocks marked with --skip-blocks-pattern (e.g. #if 0 until #endif)", required = false)
private boolean noSkipBlocks = false;
@Parameter(names = "--skip-blocks-pattern", description = "Pattern to find the blocks to skip. Start and End pattern separated by |. "
+ "Default is \"" + Tokenizer.DEFAULT_SKIP_BLOCKS_PATTERN + "\".", required = false)
private String skipBlocksPattern = Tokenizer.DEFAULT_SKIP_BLOCKS_PATTERN;
@Parameter(names = "--files", variableArity = true, description = "List of files and directories to process", required = false)
private List<String> files;
@Parameter(names = "--exclude", variableArity = true, description = "Files to be excluded from CPD check", required = false)
private List<String> excludes;
@Parameter(names = "--non-recursive", description = "Don't scan subdirectiories", required = false)
private boolean nonRecursive;
@Parameter(names = "--uri", description = "URI to process", required = false)
private String uri;
@Parameter(names = { "--help", "-h" }, description = "Print help text", required = false, help = true)
private boolean help;
// this has to be a public static class, so that JCommander can use it!
public static class LanguageConverter implements IStringConverter<Language> {
public Language convert(String languageString) {
if (languageString == null || "".equals(languageString)) {
languageString = DEFAULT_LANGUAGE;
}
return LanguageFactory.createLanguage(languageString);
}
}
public CPDConfiguration()
{
}
@Deprecated
public CPDConfiguration(int minimumTileSize, Language language, String encoding)
{
setMinimumTileSize(minimumTileSize);
setLanguage(language);
setEncoding(encoding);
}
@Parameter(names = "--encoding", description = "Character encoding to use when processing files", required = false)
public void setEncoding(String encoding) {
this.encoding = encoding;
setSourceEncoding(encoding);
}
public SourceCode sourceCodeFor(File file) {
return new SourceCode(new SourceCode.FileCodeLoader(file,
getSourceEncoding()));
}
public SourceCode sourceCodeFor(Reader reader, String sourceCodeName ) {
return new SourceCode(new SourceCode.ReaderCodeLoader(reader, sourceCodeName ));
}
public void postContruct() {
if ( this.getLanguage() == null ) {
this.setLanguage(CPDConfiguration.getLanguageFromString(DEFAULT_LANGUAGE));
}
if (this.getRendererName() == null ) {
this.setRendererName(DEFAULT_RENDERER);
}
if ( this.getRenderer() == null ) {
this.setRenderer(getRendererFromString(getRendererName(), this.getEncoding()));
}
}
/**
* Gets a renderer with the platform's default encoding.
* @param name renderer name
* @return a fresh renderer instance
* @deprecated use {@link #getRendererFromString(String, String)} instead
*/
@Deprecated
public static Renderer getRendererFromString(String name) {
return getRendererFromString(name, System.getProperty("file.encoding"));
}
public static Renderer getRendererFromString(String name, String encoding) {
if (name.equalsIgnoreCase(DEFAULT_RENDERER) || name.equals("")) {
return new SimpleRenderer();
} else if ("xml".equals(name)) {
return new XMLRenderer(encoding);
} else if ("csv".equals(name)) {
return new CSVRenderer();
} else if ("vs".equals(name)) {
return new VSRenderer();
}
try {
return (Renderer) Class.forName(name).newInstance();
} catch (Exception e) {
System.out.println("Can't find class '" + name
+ "', defaulting to SimpleRenderer.");
}
return new SimpleRenderer();
}
public static Language getLanguageFromString(String languageString) {
return LanguageFactory.createLanguage(languageString);
}
public static void setSystemProperties(CPDConfiguration configuration) {
Properties properties = new Properties();
if (configuration.isIgnoreLiterals()) {
properties.setProperty(Tokenizer.IGNORE_LITERALS, "true");
} else {
properties.remove(Tokenizer.IGNORE_LITERALS);
}
if (configuration.isIgnoreIdentifiers()) {
properties.setProperty(Tokenizer.IGNORE_IDENTIFIERS, "true");
} else {
properties.remove(Tokenizer.IGNORE_IDENTIFIERS);
}
if (configuration.isIgnoreAnnotations()) {
properties.setProperty(Tokenizer.IGNORE_ANNOTATIONS, "true");
} else {
properties.remove(Tokenizer.IGNORE_ANNOTATIONS);
}
properties.setProperty(Tokenizer.OPTION_SKIP_BLOCKS, Boolean.toString(!configuration.isNoSkipBlocks()));
properties.setProperty(Tokenizer.OPTION_SKIP_BLOCKS_PATTERN, configuration.getSkipBlocksPattern());
configuration.getLanguage().setProperties(properties);
}
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
public int getMinimumTileSize() {
return minimumTileSize;
}
public void setMinimumTileSize(int minimumTileSize) {
this.minimumTileSize = minimumTileSize;
}
public boolean isSkipDuplicates() {
return skipDuplicates;
}
public void setSkipDuplicates(boolean skipDuplicates) {
this.skipDuplicates = skipDuplicates;
}
public String getRendererName() {
return rendererName;
}
public void setRendererName(String rendererName) {
this.rendererName = rendererName;
}
public Renderer getRenderer() {
return renderer;
}
public Tokenizer tokenizer() {
if ( language == null ) {
throw new IllegalStateException("Language is null.");
}
return language.getTokenizer();
}
public FilenameFilter filenameFilter() {
if (language == null) {
throw new IllegalStateException("Language is null.");
}
final FilenameFilter languageFilter = language.getFileFilter();
final Set<String> exclusions = new HashSet<String>();
if (excludes != null) {
FileFinder finder = new FileFinder();
for (String excludedFile : excludes) {
File exFile = new File(excludedFile);
if (exFile.isDirectory()) {
List<File> files = finder.findFilesFrom(excludedFile, languageFilter, true);
for (File f : files) {
exclusions.add(f.getAbsolutePath());
}
} else {
exclusions.add(exFile.getAbsolutePath());
}
}
}
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
File f = new File(dir, name);
if (exclusions.contains(f.getAbsolutePath())) {
System.err.println("Excluding " + f.getAbsolutePath());
return false;
}
return languageFilter.accept(dir, name);
}
};
return filter;
}
public void setRenderer(Renderer renderer) {
this.renderer = renderer;
}
public boolean isIgnoreLiterals() {
return ignoreLiterals;
}
public void setIgnoreLiterals(boolean ignoreLiterals) {
this.ignoreLiterals = ignoreLiterals;
}
public boolean isIgnoreIdentifiers() {
return ignoreIdentifiers;
}
public void setIgnoreIdentifiers(boolean ignoreIdentifiers) {
this.ignoreIdentifiers = ignoreIdentifiers;
}
public boolean isIgnoreAnnotations() {
return ignoreAnnotations;
}
public void setIgnoreAnnotations(boolean ignoreAnnotations) {
this.ignoreAnnotations = ignoreAnnotations;
}
public boolean isSkipLexicalErrors() {
return skipLexicalErrors;
}
public void setSkipLexicalErrors(boolean skipLexicalErrors) {
this.skipLexicalErrors = skipLexicalErrors;
}
public List<String> getFiles() {
return files;
}
public void setFiles(List<String> files) {
this.files = files;
}
public String getURI() {
return uri;
}
public void setURI(String uri) {
this.uri = uri;
}
public List<String> getExcludes() {
return excludes;
}
public void setExcludes(List<String> excludes) {
this.excludes = excludes;
}
public boolean isNonRecursive() {
return nonRecursive;
}
public void setNonRecursive(boolean nonRecursive) {
this.nonRecursive = nonRecursive;
}
public boolean isHelp() {
return help;
}
public void setHelp(boolean help) {
this.help = help;
}
public String getEncoding() {
return encoding;
}
public boolean isNoSkipBlocks() {
return noSkipBlocks;
}
public void setNoSkipBlocks(boolean noSkipBlocks) {
this.noSkipBlocks = noSkipBlocks;
}
public String getSkipBlocksPattern() {
return skipBlocksPattern;
}
public void setSkipBlocksPattern(String skipBlocksPattern) {
this.skipBlocksPattern = skipBlocksPattern;
}
}
|
|
/**********************************************************************
Copyright (c) 2006 Erik Bengtson and others. 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.
Contributors:
...
**********************************************************************/
package org.datanucleus.tests;
import java.util.List;
import java.util.Properties;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.PersistenceUnitUtil;
import jakarta.persistence.TypedQuery;
import org.datanucleus.api.jakarta.JakartaEntityManagerFactory;
import org.datanucleus.samples.annotations.models.company.Person;
import org.datanucleus.samples.annotations.versioned.VersionedEmployee;
/**
* Tests for EntityManagerFactory (and PersistenceProvider).
*/
public class EntityManagerFactoryTest extends JakartaPersistenceTestCase
{
public EntityManagerFactoryTest(String name)
{
super(name);
}
/**
* Test for the creation of EntityManagerFactory with unspecified persistence provider
*/
public void testCreateEntityManagerFactoryWithNoProvider()
{
// We need to get the datastore props direct like this since the persistence.xml doesnt have them
Properties datastoreProps = TestHelper.getPropertiesForDatastore(1);
assertNotNull(jakarta.persistence.Persistence.createEntityManagerFactory("TEST", datastoreProps));
}
/**
* Test for the creation of EntityManagerFactory using single arg method via Persistence.
*/
public void testCreateEntityManagerFactoryWithoutOverridingProps()
{
try
{
EntityManagerFactory emf = jakarta.persistence.Persistence.createEntityManagerFactory("TEST2");
if (emf == null)
{
fail("Failed to find EMF with name");
}
}
catch (Exception e)
{
LOG.info("Exception thrown creating EMF", e);
fail("Exception thrown while creating EMF using Persistence.createEntityManagerFactory(String) : " + e.getMessage());
}
}
/**
* Test for the creation of EntityManagerFactory with specified invalid persistence provider
*/
public void testCreateEntityManagerFactoryWithInvalidProvider()
{
try
{
EntityManagerFactory emf = jakarta.persistence.Persistence.createEntityManagerFactory("Invalid Provider");
if (emf != null)
{
fail("Managed to create an EntityManagerFactory yet the provider should have resulted in none valid");
}
}
catch (PersistenceException pe)
{
// Expected since we dont have the required provider
}
}
public void testSerialize()
{
try
{
EntityManager em = getEM();
EntityTransaction tx = em.getTransaction();
try
{
tx.begin();
Person p = new Person(101, "Fred", "Flintstone", "[email protected]");
p.setGlobalNum("First");
em.persist(p);
tx.commit();
}
catch (Exception e)
{
LOG.error(">> Exception on persist before serialisation", e);
fail("Exception on persist : " + e.getMessage());
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
em.close();
}
// Serialize the current EMF
byte[] bytes = null;
try
{
bytes = TestHelper.serializeObject(emf);
}
catch (RuntimeException re)
{
LOG.error("Error serializing EMF", re);
fail("Error in serialization : " + re.getMessage());
}
// Deserialise the EMF
EntityManagerFactory emf = null;
try
{
emf = (JakartaEntityManagerFactory)TestHelper.deserializeObject(bytes);
}
catch (RuntimeException re)
{
LOG.error("Error deserializing EMF", re);
fail("Error in deserialization : " + re.getMessage());
}
JakartaEntityManagerFactory jpaEMF = (JakartaEntityManagerFactory)emf;
assertNotNull(jpaEMF);
assertNotNull(jpaEMF.getNucleusContext());
assertNotNull(jpaEMF.getMetamodel());
em = emf.createEntityManager();
tx = em.getTransaction();
try
{
tx.begin();
TypedQuery<Person> q = em.createQuery("SELECT p FROM " + Person.class.getName() + " p", Person.class);
List<Person> results = q.getResultList();
assertEquals(1, results.size());
Person p = results.get(0);
assertEquals("Fred", p.getFirstName());
assertEquals("Flintstone", p.getLastName());
assertEquals("[email protected]", p.getEmailAddress());
tx.commit();
}
catch (Exception e)
{
LOG.error(">> Exception on retrieve after deserialisation", e);
fail("Exception on retrieve after deserialisation : " + e.getMessage());
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
em.close();
}
}
finally
{
clean(Person.class);
}
}
/**
* Test for emf.getPersistenceUnitUtil.getIdentifier() method
*/
public void testPersistenceUnitUtilGetIdentifier()
{
try
{
PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
EntityManager em = getEM();
EntityTransaction tx = em.getTransaction();
try
{
tx.begin();
Person p = new Person(101, "Fred", "Flintstone", "[email protected]");
p.setGlobalNum("First");
em.persist(p);
assertTrue(util.getIdentifier(p) instanceof Person.PK);
VersionedEmployee ve = new VersionedEmployee(1, "First");
em.persist(ve);
Object veId = util.getIdentifier(ve);
assertTrue(veId instanceof Long && ((Long)veId) == 1);
tx.rollback();
}
catch (Exception e)
{
LOG.error(">> Exception on persist before serialisation", e);
fail("Exception on persist : " + e.getMessage());
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
em.close();
}
}
finally
{
// No cleanup needed
}
}
}
|
|
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.exec.planner.sql;
import static org.apache.calcite.sql.SqlUtil.stripAs;
import static org.apache.calcite.util.Static.RESOURCE;
import java.util.ArrayList;
import java.util.List;
import org.apache.calcite.rel.type.DynamicRecordType;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.runtime.CalciteContextException;
import org.apache.calcite.sql.SqlBasicCall;
import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlJdbcFunctionCall;
import org.apache.calcite.sql.SqlJoin;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlLiteral;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.SqlNumericLiteral;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.SqlSelect;
import org.apache.calcite.sql.SqlWindow;
import org.apache.calcite.sql.fun.SqlLeadLagAggFunction;
import org.apache.calcite.sql.fun.SqlNtileAggFunction;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.sql.validate.DremioEmptyScope;
import org.apache.calcite.sql.validate.SqlConformance;
import org.apache.calcite.sql.validate.SqlScopedShuttle;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorCatalogReader;
import org.apache.calcite.sql.validate.SqlValidatorException;
import org.apache.calcite.sql.validate.SqlValidatorScope;
import org.apache.calcite.util.Util;
import org.checkerframework.checker.nullness.qual.Nullable;
class SqlValidatorImpl extends org.apache.calcite.sql.validate.SqlValidatorImpl {
private final FlattenOpCounter flattenCount;
protected SqlValidatorImpl(
FlattenOpCounter flattenCount,
SqlOperatorTable sqlOperatorTable,
SqlValidatorCatalogReader catalogReader,
RelDataTypeFactory typeFactory,
SqlConformance conformance) {
super(sqlOperatorTable, catalogReader, typeFactory, conformance);
this.flattenCount = flattenCount;
}
@Override
public SqlNode validate(SqlNode topNode) {
final SqlValidatorScope scope = DremioEmptyScope.createBaseScope(this);
final SqlNode topNode2 = validateScopedExpression(topNode, scope);
final RelDataType type = getValidatedNodeType(topNode2);
Util.discard(type);
return topNode2;
}
@Override
protected SqlNode performUnconditionalRewrites(SqlNode node, boolean underFrom) {
if(node instanceof SqlBasicCall
&& ((SqlBasicCall)node).getOperator() instanceof SqlJdbcFunctionCall) {
//Check for operator overrides in DremioSqlOperatorTable
SqlBasicCall call = (SqlBasicCall) node;
final SqlJdbcFunctionCall function = (SqlJdbcFunctionCall) call.getOperator();
final List<SqlOperator> overloads = new ArrayList<>();
//The name is in the format {fn operator_name}, so we need to remove the prefix '{fn ' and
//the suffix '}' to get the original operators name.
String functionName = function.getName().substring(4, function.getName().length()-1);
//ROUND and TRUNCATE have been overridden in DremioSqlOperatorTable
if(functionName.equalsIgnoreCase(DremioSqlOperatorTable.ROUND.getName())) {
call.setOperator(DremioSqlOperatorTable.ROUND);
} else if(functionName.equalsIgnoreCase(DremioSqlOperatorTable.TRUNCATE.getName())) {
call.setOperator(DremioSqlOperatorTable.TRUNCATE);
}
}
return super.performUnconditionalRewrites(node, underFrom);
}
@Override
public void validateJoin(SqlJoin join, SqlValidatorScope scope) {
SqlNode condition = join.getCondition();
checkIfFlattenIsPartOfJoinCondition(condition);
super.validateJoin(join, scope);
}
private void checkIfFlattenIsPartOfJoinCondition(SqlNode node) {
if (node instanceof SqlBasicCall) {
SqlBasicCall call = (SqlBasicCall) node;
SqlNode[] conditionOperands = call.getOperands();
for (SqlNode operand : conditionOperands) {
if (operand instanceof SqlBasicCall) {
if (((SqlBasicCall) operand).getOperator().getName().equalsIgnoreCase("flatten")) {
throwException(node.getParserPosition());
}
}
checkIfFlattenIsPartOfJoinCondition(operand);
}
}
}
private void throwException(SqlParserPos parserPos) {
throw new CalciteContextException("Failure parsing the query",
new SqlValidatorException("Flatten is not supported as part of join condition", null),
parserPos.getLineNum(), parserPos.getEndLineNum(),
parserPos.getColumnNum(), parserPos.getEndColumnNum());
}
int nextFlattenIndex(){
return flattenCount.nextFlattenIndex();
}
static class FlattenOpCounter {
private int value;
int nextFlattenIndex(){
return value++;
}
}
@Override
public void validateWindow(
SqlNode windowOrId,
SqlValidatorScope scope,
SqlCall call) {
super.validateWindow(windowOrId, scope, call);
final SqlWindow targetWindow;
switch (windowOrId.getKind()) {
case IDENTIFIER:
targetWindow = getWindowByName((SqlIdentifier) windowOrId, scope);
break;
case WINDOW:
targetWindow = (SqlWindow) windowOrId;
break;
default:
return;
}
SqlNodeList orderList = targetWindow.getOrderList();
SqlOperator operator = call.getOperator();
Exception e = null;
if (operator instanceof SqlLeadLagAggFunction || operator instanceof SqlNtileAggFunction) {
if (orderList.size() == 0) {
e = new SqlValidatorException("LAG, LEAD or NTILE functions require ORDER BY clause in window specification", null);
}
}
if (orderList.getList().stream().anyMatch(f -> f instanceof SqlNumericLiteral)) {
e = new SqlValidatorException("Dremio does not currently support order by with ordinals in over clause", null);
}
if (e != null) {
SqlParserPos pos = targetWindow.getParserPosition();
CalciteContextException ex = RESOURCE.validatorContextPoint(pos.getLineNum(), pos.getColumnNum()).ex(e);
ex.setPosition(pos.getLineNum(), pos.getColumnNum());
throw ex;
}
}
@Override
public void validateAggregateParams(SqlCall aggCall, SqlNode filter, SqlNodeList orderList, SqlValidatorScope scope) {
super.validateAggregateParams(aggCall, filter, orderList, scope);
}
@Override
public SqlNode expand(SqlNode expr, SqlValidatorScope scope) {
Expander expander = new Expander(this, scope);
SqlNode newExpr = (SqlNode)expr.accept(expander);
if (expr != newExpr) {
this.setOriginal(newExpr, expr);
}
return newExpr;
}
/**Overriden to Handle the ITEM operator.*/
@Override
protected @Nullable SqlNode stripDot(@Nullable SqlNode node) {
//Checking for Item operator which is similiar to the dot operator.
if (null == node) {
return null;
} else if (node.getKind() == SqlKind.DOT) {
return stripDot(((SqlCall) node).operand(0));
} else if (node.getKind() == SqlKind.OTHER_FUNCTION
&& SqlStdOperatorTable.ITEM == ((SqlCall) node).getOperator()) {
return stripDot(((SqlCall) node).operand(0));
} else {
return node;
}
}
/**We are seeing nested AS nodes that reference SqlIdentifiers.*/
@Override
protected void checkRollUp(SqlNode grandParent,
SqlNode parent,
SqlNode current,
SqlValidatorScope scope,
String optionalClause) {
current = stripAs(current);
if (current instanceof SqlCall && !(current instanceof SqlSelect)) {
// Validate OVER separately
checkRollUpInWindow(getWindowInOver(current), scope);
current = stripOver(current);
SqlNode stripped = stripAs(stripDot(current));
if (stripped instanceof SqlCall) {
List<SqlNode> children = ((SqlCall) stripped).getOperandList();
for (SqlNode child : children) {
checkRollUp(parent, current, child, scope, optionalClause);
}
} else {
current = stripped;
}
}
if (current instanceof SqlIdentifier) {
SqlIdentifier id = (SqlIdentifier) current;
if (!id.isStar() && isRolledUpColumn(id, scope)) {
if (!isAggregation(parent.getKind())
|| !isRolledUpColumnAllowedInAgg(id, scope, (SqlCall) parent, grandParent)) {
String context = optionalClause != null ? optionalClause : parent.getKind().toString();
throw newValidationError(id,
RESOURCE.rolledUpNotAllowed(deriveAlias(id, 0), context));
}
}
}
}
/**
* Expander
*/
private static class Expander extends SqlScopedShuttle {
protected final org.apache.calcite.sql.validate.SqlValidatorImpl validator;
Expander(org.apache.calcite.sql.validate.SqlValidatorImpl validator, SqlValidatorScope scope) {
super(scope);
this.validator = validator;
}
public SqlNode visit(SqlIdentifier id) {
SqlValidator validator = getScope().getValidator();
final SqlCall call = validator.makeNullaryCall(id);
if (call != null) {
return (SqlNode)call.accept(this);
} else {
SqlIdentifier fqId = null;
try {
fqId = this.getScope().fullyQualify(id).identifier;
} catch (CalciteContextException ex) {
// The failure here may be happening because the path references a field within ANY type column.
// Check if the first derivable type in parents is ANY. If this is the case, fall back to ITEM operator.
// Otherwise, throw the original exception.
if(id.names.size() > 1 && checkAnyType(id)) {
SqlBasicCall itemCall = new SqlBasicCall(
SqlStdOperatorTable.ITEM,
new SqlNode[]{id.getComponent(0, id.names.size()-1), SqlLiteral.createCharString((String) Util.last(id.names), id.getParserPosition())}, id.getParserPosition());
try {
return itemCall.accept(this);
} catch (Exception ignored) {}
}
throw ex;
}
SqlNode expandedExpr = fqId;
if (DynamicRecordType.isDynamicStarColName((String) Util.last(fqId.names)) && !DynamicRecordType.isDynamicStarColName((String) Util.last(id.names))) {
SqlNode[] inputs = new SqlNode[]{fqId, SqlLiteral.createCharString((String) Util.last(id.names), id.getParserPosition())};
SqlBasicCall item_call = new SqlBasicCall(SqlStdOperatorTable.ITEM, inputs, id.getParserPosition());
expandedExpr = item_call;
}
this.validator.setOriginal((SqlNode) expandedExpr, id);
return (SqlNode) expandedExpr;
}
}
@Override
protected SqlNode visitScoped(SqlCall call) {
switch(call.getKind()) {
case WITH:
case SCALAR_QUERY:
case CURRENT_VALUE:
case NEXT_VALUE:
return call;
default:
SqlCall newCall = call;
if (call.getOperator() == SqlStdOperatorTable.DOT) {
try {
validator.deriveType(getScope(), call);
} catch (Exception ex) {
// The failure here may be happening because the dot operator was used within ANY type column.
// Check if the first derivable type in parents is ANY. If this is the case, fall back to ITEM operator.
// Otherwise, throw the original exception.
if (checkAnyType(call)) {
SqlNode left = call.getOperandList().get(0);
SqlNode right = call.getOperandList().get(1);
SqlNode[] inputs = new SqlNode[]{left, SqlLiteral.createCharString(right.toString(), call.getParserPosition())};
newCall = new SqlBasicCall(SqlStdOperatorTable.ITEM, inputs, call.getParserPosition());
} else {
throw ex;
}
}
}
ArgHandler<SqlNode> argHandler = new CallCopyingArgHandler(newCall, false);
newCall.getOperator().acceptCall(this, newCall, true, argHandler);
SqlNode result = (SqlNode)argHandler.result();
this.validator.setOriginal(result, newCall);
return result;
}
}
private boolean checkAnyType(SqlIdentifier identifier) {
List<String> names = identifier.names;
for (int i = names.size(); i > 0; i--) {
try {
final RelDataType type = validator.deriveType(getScope(), new SqlIdentifier(names.subList(0, i), identifier.getParserPosition()));
return SqlTypeName.ANY == type.getSqlTypeName();
} catch (Exception ignored) {
}
}
return false;
}
private boolean checkAnyType(SqlCall call) {
if (call.getOperandList().size() == 0) {
return false;
}
RelDataType type = null;
final SqlNode operand = call.operand(0);
try {
type = validator.deriveType(getScope(), operand);
} catch (Exception ignored) {
}
if(type != null) {
return SqlTypeName.ANY == type.getSqlTypeName();
}
if(operand instanceof SqlCall) {
return checkAnyType((SqlCall) operand);
}
if(operand instanceof SqlIdentifier) {
return checkAnyType((SqlIdentifier) operand);
}
return false;
}
}
}
|
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.Request;
import com.amazonaws.services.ec2.model.transform.ModifyTrafficMirrorSessionRequestMarshaller;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ModifyTrafficMirrorSessionRequest extends AmazonWebServiceRequest implements Serializable, Cloneable,
DryRunSupportedRequest<ModifyTrafficMirrorSessionRequest> {
/**
* <p>
* The ID of the Traffic Mirror session.
* </p>
*/
private String trafficMirrorSessionId;
/**
* <p>
* The Traffic Mirror target. The target must be in the same VPC as the source, or have a VPC peering connection
* with the source.
* </p>
*/
private String trafficMirrorTargetId;
/**
* <p>
* The ID of the Traffic Mirror filter.
* </p>
*/
private String trafficMirrorFilterId;
/**
* <p>
* The number of bytes in each packet to mirror. These are bytes after the VXLAN header. To mirror a subset, set
* this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100 bytes that
* meet the filter criteria are copied to the target. Do not specify this parameter when you want to mirror the
* entire packet.
* </p>
*/
private Integer packetLength;
/**
* <p>
* The session number determines the order in which sessions are evaluated when an interface is used by multiple
* sessions. The first session with a matching filter is the one that mirrors the packets.
* </p>
* <p>
* Valid values are 1-32766.
* </p>
*/
private Integer sessionNumber;
/**
* <p>
* The virtual network ID of the Traffic Mirror session.
* </p>
*/
private Integer virtualNetworkId;
/**
* <p>
* The description to assign to the Traffic Mirror session.
* </p>
*/
private String description;
/**
* <p>
* The properties that you want to remove from the Traffic Mirror session.
* </p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> removeFields;
/**
* <p>
* The ID of the Traffic Mirror session.
* </p>
*
* @param trafficMirrorSessionId
* The ID of the Traffic Mirror session.
*/
public void setTrafficMirrorSessionId(String trafficMirrorSessionId) {
this.trafficMirrorSessionId = trafficMirrorSessionId;
}
/**
* <p>
* The ID of the Traffic Mirror session.
* </p>
*
* @return The ID of the Traffic Mirror session.
*/
public String getTrafficMirrorSessionId() {
return this.trafficMirrorSessionId;
}
/**
* <p>
* The ID of the Traffic Mirror session.
* </p>
*
* @param trafficMirrorSessionId
* The ID of the Traffic Mirror session.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyTrafficMirrorSessionRequest withTrafficMirrorSessionId(String trafficMirrorSessionId) {
setTrafficMirrorSessionId(trafficMirrorSessionId);
return this;
}
/**
* <p>
* The Traffic Mirror target. The target must be in the same VPC as the source, or have a VPC peering connection
* with the source.
* </p>
*
* @param trafficMirrorTargetId
* The Traffic Mirror target. The target must be in the same VPC as the source, or have a VPC peering
* connection with the source.
*/
public void setTrafficMirrorTargetId(String trafficMirrorTargetId) {
this.trafficMirrorTargetId = trafficMirrorTargetId;
}
/**
* <p>
* The Traffic Mirror target. The target must be in the same VPC as the source, or have a VPC peering connection
* with the source.
* </p>
*
* @return The Traffic Mirror target. The target must be in the same VPC as the source, or have a VPC peering
* connection with the source.
*/
public String getTrafficMirrorTargetId() {
return this.trafficMirrorTargetId;
}
/**
* <p>
* The Traffic Mirror target. The target must be in the same VPC as the source, or have a VPC peering connection
* with the source.
* </p>
*
* @param trafficMirrorTargetId
* The Traffic Mirror target. The target must be in the same VPC as the source, or have a VPC peering
* connection with the source.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyTrafficMirrorSessionRequest withTrafficMirrorTargetId(String trafficMirrorTargetId) {
setTrafficMirrorTargetId(trafficMirrorTargetId);
return this;
}
/**
* <p>
* The ID of the Traffic Mirror filter.
* </p>
*
* @param trafficMirrorFilterId
* The ID of the Traffic Mirror filter.
*/
public void setTrafficMirrorFilterId(String trafficMirrorFilterId) {
this.trafficMirrorFilterId = trafficMirrorFilterId;
}
/**
* <p>
* The ID of the Traffic Mirror filter.
* </p>
*
* @return The ID of the Traffic Mirror filter.
*/
public String getTrafficMirrorFilterId() {
return this.trafficMirrorFilterId;
}
/**
* <p>
* The ID of the Traffic Mirror filter.
* </p>
*
* @param trafficMirrorFilterId
* The ID of the Traffic Mirror filter.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyTrafficMirrorSessionRequest withTrafficMirrorFilterId(String trafficMirrorFilterId) {
setTrafficMirrorFilterId(trafficMirrorFilterId);
return this;
}
/**
* <p>
* The number of bytes in each packet to mirror. These are bytes after the VXLAN header. To mirror a subset, set
* this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100 bytes that
* meet the filter criteria are copied to the target. Do not specify this parameter when you want to mirror the
* entire packet.
* </p>
*
* @param packetLength
* The number of bytes in each packet to mirror. These are bytes after the VXLAN header. To mirror a subset,
* set this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100
* bytes that meet the filter criteria are copied to the target. Do not specify this parameter when you want
* to mirror the entire packet.
*/
public void setPacketLength(Integer packetLength) {
this.packetLength = packetLength;
}
/**
* <p>
* The number of bytes in each packet to mirror. These are bytes after the VXLAN header. To mirror a subset, set
* this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100 bytes that
* meet the filter criteria are copied to the target. Do not specify this parameter when you want to mirror the
* entire packet.
* </p>
*
* @return The number of bytes in each packet to mirror. These are bytes after the VXLAN header. To mirror a subset,
* set this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first
* 100 bytes that meet the filter criteria are copied to the target. Do not specify this parameter when you
* want to mirror the entire packet.
*/
public Integer getPacketLength() {
return this.packetLength;
}
/**
* <p>
* The number of bytes in each packet to mirror. These are bytes after the VXLAN header. To mirror a subset, set
* this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100 bytes that
* meet the filter criteria are copied to the target. Do not specify this parameter when you want to mirror the
* entire packet.
* </p>
*
* @param packetLength
* The number of bytes in each packet to mirror. These are bytes after the VXLAN header. To mirror a subset,
* set this to the length (in bytes) to mirror. For example, if you set this value to 100, then the first 100
* bytes that meet the filter criteria are copied to the target. Do not specify this parameter when you want
* to mirror the entire packet.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyTrafficMirrorSessionRequest withPacketLength(Integer packetLength) {
setPacketLength(packetLength);
return this;
}
/**
* <p>
* The session number determines the order in which sessions are evaluated when an interface is used by multiple
* sessions. The first session with a matching filter is the one that mirrors the packets.
* </p>
* <p>
* Valid values are 1-32766.
* </p>
*
* @param sessionNumber
* The session number determines the order in which sessions are evaluated when an interface is used by
* multiple sessions. The first session with a matching filter is the one that mirrors the packets.</p>
* <p>
* Valid values are 1-32766.
*/
public void setSessionNumber(Integer sessionNumber) {
this.sessionNumber = sessionNumber;
}
/**
* <p>
* The session number determines the order in which sessions are evaluated when an interface is used by multiple
* sessions. The first session with a matching filter is the one that mirrors the packets.
* </p>
* <p>
* Valid values are 1-32766.
* </p>
*
* @return The session number determines the order in which sessions are evaluated when an interface is used by
* multiple sessions. The first session with a matching filter is the one that mirrors the packets.</p>
* <p>
* Valid values are 1-32766.
*/
public Integer getSessionNumber() {
return this.sessionNumber;
}
/**
* <p>
* The session number determines the order in which sessions are evaluated when an interface is used by multiple
* sessions. The first session with a matching filter is the one that mirrors the packets.
* </p>
* <p>
* Valid values are 1-32766.
* </p>
*
* @param sessionNumber
* The session number determines the order in which sessions are evaluated when an interface is used by
* multiple sessions. The first session with a matching filter is the one that mirrors the packets.</p>
* <p>
* Valid values are 1-32766.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyTrafficMirrorSessionRequest withSessionNumber(Integer sessionNumber) {
setSessionNumber(sessionNumber);
return this;
}
/**
* <p>
* The virtual network ID of the Traffic Mirror session.
* </p>
*
* @param virtualNetworkId
* The virtual network ID of the Traffic Mirror session.
*/
public void setVirtualNetworkId(Integer virtualNetworkId) {
this.virtualNetworkId = virtualNetworkId;
}
/**
* <p>
* The virtual network ID of the Traffic Mirror session.
* </p>
*
* @return The virtual network ID of the Traffic Mirror session.
*/
public Integer getVirtualNetworkId() {
return this.virtualNetworkId;
}
/**
* <p>
* The virtual network ID of the Traffic Mirror session.
* </p>
*
* @param virtualNetworkId
* The virtual network ID of the Traffic Mirror session.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyTrafficMirrorSessionRequest withVirtualNetworkId(Integer virtualNetworkId) {
setVirtualNetworkId(virtualNetworkId);
return this;
}
/**
* <p>
* The description to assign to the Traffic Mirror session.
* </p>
*
* @param description
* The description to assign to the Traffic Mirror session.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The description to assign to the Traffic Mirror session.
* </p>
*
* @return The description to assign to the Traffic Mirror session.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The description to assign to the Traffic Mirror session.
* </p>
*
* @param description
* The description to assign to the Traffic Mirror session.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ModifyTrafficMirrorSessionRequest withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The properties that you want to remove from the Traffic Mirror session.
* </p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* </p>
*
* @return The properties that you want to remove from the Traffic Mirror session.</p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* @see TrafficMirrorSessionField
*/
public java.util.List<String> getRemoveFields() {
if (removeFields == null) {
removeFields = new com.amazonaws.internal.SdkInternalList<String>();
}
return removeFields;
}
/**
* <p>
* The properties that you want to remove from the Traffic Mirror session.
* </p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* </p>
*
* @param removeFields
* The properties that you want to remove from the Traffic Mirror session.</p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* @see TrafficMirrorSessionField
*/
public void setRemoveFields(java.util.Collection<String> removeFields) {
if (removeFields == null) {
this.removeFields = null;
return;
}
this.removeFields = new com.amazonaws.internal.SdkInternalList<String>(removeFields);
}
/**
* <p>
* The properties that you want to remove from the Traffic Mirror session.
* </p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setRemoveFields(java.util.Collection)} or {@link #withRemoveFields(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param removeFields
* The properties that you want to remove from the Traffic Mirror session.</p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* @return Returns a reference to this object so that method calls can be chained together.
* @see TrafficMirrorSessionField
*/
public ModifyTrafficMirrorSessionRequest withRemoveFields(String... removeFields) {
if (this.removeFields == null) {
setRemoveFields(new com.amazonaws.internal.SdkInternalList<String>(removeFields.length));
}
for (String ele : removeFields) {
this.removeFields.add(ele);
}
return this;
}
/**
* <p>
* The properties that you want to remove from the Traffic Mirror session.
* </p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* </p>
*
* @param removeFields
* The properties that you want to remove from the Traffic Mirror session.</p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* @return Returns a reference to this object so that method calls can be chained together.
* @see TrafficMirrorSessionField
*/
public ModifyTrafficMirrorSessionRequest withRemoveFields(java.util.Collection<String> removeFields) {
setRemoveFields(removeFields);
return this;
}
/**
* <p>
* The properties that you want to remove from the Traffic Mirror session.
* </p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* </p>
*
* @param removeFields
* The properties that you want to remove from the Traffic Mirror session.</p>
* <p>
* When you remove a property from a Traffic Mirror session, the property is set to the default.
* @return Returns a reference to this object so that method calls can be chained together.
* @see TrafficMirrorSessionField
*/
public ModifyTrafficMirrorSessionRequest withRemoveFields(TrafficMirrorSessionField... removeFields) {
com.amazonaws.internal.SdkInternalList<String> removeFieldsCopy = new com.amazonaws.internal.SdkInternalList<String>(removeFields.length);
for (TrafficMirrorSessionField value : removeFields) {
removeFieldsCopy.add(value.toString());
}
if (getRemoveFields() == null) {
setRemoveFields(removeFieldsCopy);
} else {
getRemoveFields().addAll(removeFieldsCopy);
}
return this;
}
/**
* This method is intended for internal use only. Returns the marshaled request configured with additional
* parameters to enable operation dry-run.
*/
@Override
public Request<ModifyTrafficMirrorSessionRequest> getDryRunRequest() {
Request<ModifyTrafficMirrorSessionRequest> request = new ModifyTrafficMirrorSessionRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTrafficMirrorSessionId() != null)
sb.append("TrafficMirrorSessionId: ").append(getTrafficMirrorSessionId()).append(",");
if (getTrafficMirrorTargetId() != null)
sb.append("TrafficMirrorTargetId: ").append(getTrafficMirrorTargetId()).append(",");
if (getTrafficMirrorFilterId() != null)
sb.append("TrafficMirrorFilterId: ").append(getTrafficMirrorFilterId()).append(",");
if (getPacketLength() != null)
sb.append("PacketLength: ").append(getPacketLength()).append(",");
if (getSessionNumber() != null)
sb.append("SessionNumber: ").append(getSessionNumber()).append(",");
if (getVirtualNetworkId() != null)
sb.append("VirtualNetworkId: ").append(getVirtualNetworkId()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getRemoveFields() != null)
sb.append("RemoveFields: ").append(getRemoveFields());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ModifyTrafficMirrorSessionRequest == false)
return false;
ModifyTrafficMirrorSessionRequest other = (ModifyTrafficMirrorSessionRequest) obj;
if (other.getTrafficMirrorSessionId() == null ^ this.getTrafficMirrorSessionId() == null)
return false;
if (other.getTrafficMirrorSessionId() != null && other.getTrafficMirrorSessionId().equals(this.getTrafficMirrorSessionId()) == false)
return false;
if (other.getTrafficMirrorTargetId() == null ^ this.getTrafficMirrorTargetId() == null)
return false;
if (other.getTrafficMirrorTargetId() != null && other.getTrafficMirrorTargetId().equals(this.getTrafficMirrorTargetId()) == false)
return false;
if (other.getTrafficMirrorFilterId() == null ^ this.getTrafficMirrorFilterId() == null)
return false;
if (other.getTrafficMirrorFilterId() != null && other.getTrafficMirrorFilterId().equals(this.getTrafficMirrorFilterId()) == false)
return false;
if (other.getPacketLength() == null ^ this.getPacketLength() == null)
return false;
if (other.getPacketLength() != null && other.getPacketLength().equals(this.getPacketLength()) == false)
return false;
if (other.getSessionNumber() == null ^ this.getSessionNumber() == null)
return false;
if (other.getSessionNumber() != null && other.getSessionNumber().equals(this.getSessionNumber()) == false)
return false;
if (other.getVirtualNetworkId() == null ^ this.getVirtualNetworkId() == null)
return false;
if (other.getVirtualNetworkId() != null && other.getVirtualNetworkId().equals(this.getVirtualNetworkId()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getRemoveFields() == null ^ this.getRemoveFields() == null)
return false;
if (other.getRemoveFields() != null && other.getRemoveFields().equals(this.getRemoveFields()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTrafficMirrorSessionId() == null) ? 0 : getTrafficMirrorSessionId().hashCode());
hashCode = prime * hashCode + ((getTrafficMirrorTargetId() == null) ? 0 : getTrafficMirrorTargetId().hashCode());
hashCode = prime * hashCode + ((getTrafficMirrorFilterId() == null) ? 0 : getTrafficMirrorFilterId().hashCode());
hashCode = prime * hashCode + ((getPacketLength() == null) ? 0 : getPacketLength().hashCode());
hashCode = prime * hashCode + ((getSessionNumber() == null) ? 0 : getSessionNumber().hashCode());
hashCode = prime * hashCode + ((getVirtualNetworkId() == null) ? 0 : getVirtualNetworkId().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getRemoveFields() == null) ? 0 : getRemoveFields().hashCode());
return hashCode;
}
@Override
public ModifyTrafficMirrorSessionRequest clone() {
return (ModifyTrafficMirrorSessionRequest) super.clone();
}
}
|
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.spi;
import com.facebook.presto.spi.security.Privilege;
import io.airlift.slice.Slice;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Set;
import static com.facebook.presto.spi.StandardErrorCode.INTERNAL_ERROR;
import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
@Deprecated
public interface ConnectorMetadata
{
/**
* Returns the schemas provided by this connector.
*/
List<String> listSchemaNames(ConnectorSession session);
/**
* Returns a table handle for the specified table name, or null if the connector does not contain the table.
*/
ConnectorTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName);
/**
* Return a list of table layouts that satisfy the given constraint.
* <p>
* For each layout, connectors must return an "unenforced constraint" representing the part of the constraint summary that isn't guaranteed by the layout.
*/
default List<ConnectorTableLayoutResult> getTableLayouts(
ConnectorSession session,
ConnectorTableHandle table,
Constraint<ColumnHandle> constraint,
Optional<Set<ColumnHandle>> desiredColumns)
{
throw new UnsupportedOperationException("not yet implemented");
}
default ConnectorTableLayout getTableLayout(ConnectorSession session, ConnectorTableLayoutHandle handle)
{
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Return the metadata for the specified table handle.
*
* @throws RuntimeException if table handle is no longer valid
*/
ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle table);
/**
* List table names, possibly filtered by schema. An empty list is returned if none match.
*/
List<SchemaTableName> listTables(ConnectorSession session, String schemaNameOrNull);
/**
* Returns the handle for the sample weight column, or null if the table does not contain sampled data.
*
* @throws RuntimeException if the table handle is no longer valid
*/
default ColumnHandle getSampleWeightColumnHandle(ConnectorSession session, ConnectorTableHandle tableHandle)
{
return null;
}
/**
* Returns true if this catalog supports creation of sampled tables
*/
default boolean canCreateSampledTables(ConnectorSession session)
{
return false;
}
/**
* Gets all of the columns on the specified table, or an empty map if the columns can not be enumerated.
*
* @throws RuntimeException if table handle is no longer valid
*/
Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle);
/**
* Gets the metadata for the specified table column.
*
* @throws RuntimeException if table or column handles are no longer valid
*/
ColumnMetadata getColumnMetadata(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle columnHandle);
/**
* Gets the metadata for all columns that match the specified table prefix.
*/
Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix);
/**
* Creates a table using the specified table metadata.
*/
default void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support creating tables");
}
/**
* Drops the specified table
*
* @throws RuntimeException if the table can not be dropped or table handle is no longer valid
*/
default void dropTable(ConnectorSession session, ConnectorTableHandle tableHandle)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support dropping tables");
}
/**
* Rename the specified table
*/
default void renameTable(ConnectorSession session, ConnectorTableHandle tableHandle, SchemaTableName newTableName)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support renaming tables");
}
/**
* Add the specified column
*/
default void addColumn(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnMetadata column)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support adding columns");
}
/**
* Rename the specified column
*/
default void renameColumn(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle source, String target)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support renaming columns");
}
/**
* Begin the atomic creation of a table with data.
*/
default ConnectorOutputTableHandle beginCreateTable(ConnectorSession session, ConnectorTableMetadata tableMetadata)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support creating tables with data");
}
/**
* Commit a table creation with data after the data is written.
*/
default void commitCreateTable(ConnectorSession session, ConnectorOutputTableHandle tableHandle, Collection<Slice> fragments)
{
throw new PrestoException(INTERNAL_ERROR, "ConnectorMetadata beginCreateTable() is implemented without commitCreateTable()");
}
/**
* Rollback a table creation
*/
default void rollbackCreateTable(ConnectorSession session, ConnectorOutputTableHandle tableHandle) {}
/**
* Begin insert query
*/
default ConnectorInsertTableHandle beginInsert(ConnectorSession session, ConnectorTableHandle tableHandle)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support inserts");
}
/**
* Commit insert query
*/
default void commitInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle, Collection<Slice> fragments)
{
throw new PrestoException(INTERNAL_ERROR, "ConnectorMetadata beginInsert() is implemented without commitInsert()");
}
/**
* Rollback insert query
*/
default void rollbackInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle) {}
/**
* Get the column handle that will generate row IDs for the delete operation.
* These IDs will be passed to the {@code deleteRows()} method of the
* {@link UpdatablePageSource} that created them.
*/
default ColumnHandle getUpdateRowIdColumnHandle(ConnectorSession session, ConnectorTableHandle tableHandle)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support updates or deletes");
}
/**
* Begin delete query
*/
default ConnectorTableHandle beginDelete(ConnectorSession session, ConnectorTableHandle tableHandle)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support deletes");
}
/**
* Commit delete query
*
* @param fragments all fragments returned by {@link com.facebook.presto.spi.UpdatablePageSource#finish()}
*/
default void commitDelete(ConnectorSession session, ConnectorTableHandle tableHandle, Collection<Slice> fragments)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support deletes");
}
/**
* Rollback delete query
*/
default void rollbackDelete(ConnectorSession session, ConnectorTableHandle tableHandle) {}
/**
* Create the specified view. The data for the view is opaque to the connector.
*/
default void createView(ConnectorSession session, SchemaTableName viewName, String viewData, boolean replace)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support creating views");
}
/**
* Drop the specified view.
*/
default void dropView(ConnectorSession session, SchemaTableName viewName)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support dropping views");
}
/**
* List view names, possibly filtered by schema. An empty list is returned if none match.
*/
default List<SchemaTableName> listViews(ConnectorSession session, String schemaNameOrNull)
{
return emptyList();
}
/**
* Gets the view data for views that match the specified table prefix.
*/
default Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix)
{
return emptyMap();
}
/**
* @return whether delete without table scan is supported
*/
default boolean supportsMetadataDelete(ConnectorSession session, ConnectorTableHandle tableHandle, ConnectorTableLayoutHandle tableLayoutHandle)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support deletes");
}
/**
* Delete the provided table layout
*
* @return number of rows deleted, or null for unknown
*/
default OptionalLong metadataDelete(ConnectorSession session, ConnectorTableHandle tableHandle, ConnectorTableLayoutHandle tableLayoutHandle)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support deletes");
}
/**
* Grants the specified privilege to the specified user on the specified table
*/
default void grantTablePrivileges(ConnectorSession session, SchemaTableName tableName, Set<Privilege> privileges, String grantee, boolean grantOption)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support grants");
}
/**
* Revokes the specified privilege on the specified table from the specified user
*/
default void revokeTablePrivileges(ConnectorSession session, SchemaTableName tableName, Set<Privilege> privileges, String grantee, boolean grantOption)
{
throw new PrestoException(NOT_SUPPORTED, "This connector does not support revokes");
}
}
|
|
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.impl.cmmn.behavior;
import org.camunda.bpm.engine.impl.ProcessEngineLogger;
import org.camunda.bpm.engine.impl.cmmn.entity.runtime.CaseExecutionEntity;
import org.camunda.bpm.engine.impl.cmmn.execution.CaseExecutionState;
import org.camunda.bpm.engine.impl.cmmn.execution.CmmnActivityExecution;
import org.camunda.bpm.engine.impl.cmmn.execution.CmmnExecution;
import org.camunda.bpm.engine.impl.cmmn.model.CmmnActivity;
import java.util.List;
import static org.camunda.bpm.engine.impl.cmmn.execution.CaseExecutionState.*;
import static org.camunda.bpm.engine.impl.cmmn.handler.ItemHandler.PROPERTY_AUTO_COMPLETE;
import static org.camunda.bpm.engine.impl.util.ActivityBehaviorUtil.getActivityBehavior;
import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureInstanceOf;
/**
* @author Roman Smirnov
*
*/
public class StageActivityBehavior extends StageOrTaskActivityBehavior implements CmmnCompositeActivityBehavior {
protected static final CmmnBehaviorLogger LOG = ProcessEngineLogger.CMNN_BEHAVIOR_LOGGER;
// start /////////////////////////////////////////////////////////////////////
protected void performStart(CmmnActivityExecution execution) {
CmmnActivity activity = execution.getActivity();
List<CmmnActivity> childActivities = activity.getActivities();
if (childActivities != null && !childActivities.isEmpty()) {
List<CmmnExecution> children = execution.createChildExecutions(childActivities);
execution.createSentryParts();
execution.triggerChildExecutionsLifecycle(children);
if (execution.isActive()) {
execution.fireIfOnlySentryParts();
// if "autoComplete == true" and there are no
// required nor active child activities,
// then the stage will be completed.
if (execution.isActive()) {
checkAndCompleteCaseExecution(execution);
}
}
} else {
execution.complete();
}
}
// re-activation ////////////////////////////////////////////////////////////
public void onReactivation(CmmnActivityExecution execution) {
String id = execution.getId();
if (execution.isActive()) {
throw LOG.alreadyActiveException("reactivate", id);
}
if (execution.isCaseInstanceExecution()) {
if (execution.isClosed()) {
throw LOG.alreadyClosedCaseException("reactivate", id);
}
} else {
ensureTransitionAllowed(execution, FAILED, ACTIVE, "reactivate");
}
}
public void reactivated(CmmnActivityExecution execution) {
if (execution.isCaseInstanceExecution()) {
CaseExecutionState previousState = execution.getPreviousState();
if (SUSPENDED.equals(previousState)) {
resumed(execution);
}
}
// at the moment it is not possible to re-activate a case execution
// because the state "FAILED" is not implemented.
}
// completion //////////////////////////////////////////////////////////////
public void onCompletion(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, ACTIVE, COMPLETED, "complete");
canComplete(execution, true);
completing(execution);
}
public void onManualCompletion(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, ACTIVE, COMPLETED, "complete");
canComplete(execution, true, true);
completing(execution);
}
protected void completing(CmmnActivityExecution execution) {
List<? extends CmmnExecution> children = execution.getCaseExecutions();
for (CmmnExecution child : children) {
if (!child.isDisabled()) {
child.parentComplete();
} else {
child.remove();
}
}
}
protected boolean canComplete(CmmnActivityExecution execution) {
return canComplete(execution, false);
}
protected boolean canComplete(CmmnActivityExecution execution, boolean throwException) {
boolean autoComplete = evaluateAutoComplete(execution);
return canComplete(execution, throwException, autoComplete);
}
protected boolean canComplete(CmmnActivityExecution execution, boolean throwException, boolean autoComplete) {
String id = execution.getId();
List<? extends CmmnExecution> children = execution.getCaseExecutions();
if (children == null || children.isEmpty()) {
// if the stage does not contain any child
// then the stage can complete.
return true;
}
// verify there are no STATE_ACTIVE children
for (CmmnExecution child : children) {
if (child.isActive()) {
if (throwException) {
throw LOG.remainingChildException("complete", id, child.getId(), CaseExecutionState.ACTIVE);
}
return false;
}
}
if (autoComplete) {
// ensure that all required children are DISABLED, STATE_COMPLETED and/or TERMINATED
// available in the case execution tree.
for (CmmnExecution child : children) {
if (child.isRequired() && !child.isDisabled() && !child.isCompleted() && !child.isTerminated()) {
if (throwException) {
throw LOG.remainingChildException("complete", id, child.getId(), child.getCurrentState());
}
return false;
}
}
} else { /* autoComplete == false && manualCompletion == false */
// ensure that ALL children are DISABLED, STATE_COMPLETED and/or TERMINATED
for (CmmnExecution child : children) {
if (!child.isDisabled() && !child.isCompleted() && !child.isTerminated()) {
if (throwException) {
throw LOG.wrongChildStateException("complete", id, child.getId(), "[available|enabled|suspended]");
}
return false;
}
}
// TODO: are there any DiscretionaryItems?
// if yes, then it is not possible to complete
// this stage (NOTE: manualCompletion == false)!
}
return true;
}
protected boolean evaluateAutoComplete(CmmnActivityExecution execution) {
CmmnActivity activity = getActivity(execution);
Object autoCompleteProperty = activity.getProperty(PROPERTY_AUTO_COMPLETE);
if (autoCompleteProperty != null) {
String message = "Property autoComplete expression returns non-Boolean: "+autoCompleteProperty+" ("+autoCompleteProperty.getClass().getName()+")";
ensureInstanceOf(message, "autoComplete", autoCompleteProperty, Boolean.class);
return (Boolean) autoCompleteProperty;
}
return false;
}
// termination //////////////////////////////////////////////////////////////
protected boolean isAbleToTerminate(CmmnActivityExecution execution) {
List<? extends CmmnExecution> children = execution.getCaseExecutions();
if (children != null && !children.isEmpty()) {
for (CmmnExecution child : children) {
// the guard "!child.isCompleted()" is needed,
// when an exitCriteria is triggered on a stage, and
// the referenced sentry contains an onPart to a child
// case execution which has defined as standardEvent "complete".
// In that case the completed child case execution is still
// in the list of child case execution of the parent case execution.
if (!child.isTerminated() && !child.isCompleted()) {
return false;
}
}
}
return true;
}
protected void performTerminate(CmmnActivityExecution execution) {
if (!isAbleToTerminate(execution)) {
terminateChildren(execution);
} else {
super.performTerminate(execution);
}
}
protected void performExit(CmmnActivityExecution execution) {
if (!isAbleToTerminate(execution)) {
terminateChildren(execution);
} else {
super.performExit(execution);
}
}
protected void terminateChildren(CmmnActivityExecution execution) {
List<? extends CmmnExecution> children = execution.getCaseExecutions();
for (CmmnExecution child : children) {
terminateChild(child);
}
}
protected void terminateChild(CmmnExecution child) {
CmmnActivityBehavior behavior = getActivityBehavior(child);
// "child.isTerminated()": during resuming the children, it can
// happen that a sentry will be satisfied, so that a child
// will terminated. these terminated child cannot be resumed,
// so ignore it.
// "child.isCompleted()": in case that an exitCriteria on caseInstance
// (ie. casePlanModel) has been fired, when a child inside has been
// completed, so ignore it.
if (!child.isTerminated() && !child.isCompleted()) {
if (behavior instanceof StageOrTaskActivityBehavior) {
child.exit();
} else { /* behavior instanceof EventListenerOrMilestoneActivityBehavior */
child.parentTerminate();
}
}
}
// suspension /////////////////////////////////////////////////////////////////
protected void performSuspension(CmmnActivityExecution execution) {
if (!isAbleToSuspend(execution)) {
suspendChildren(execution);
} else {
super.performSuspension(execution);
}
}
protected void performParentSuspension(CmmnActivityExecution execution) {
if (!isAbleToSuspend(execution)) {
suspendChildren(execution);
} else {
super.performParentSuspension(execution);
}
}
protected void suspendChildren(CmmnActivityExecution execution) {
List<? extends CmmnExecution> children = execution.getCaseExecutions();
if (children != null && !children.isEmpty()) {
for (CmmnExecution child : children) {
CmmnActivityBehavior behavior = getActivityBehavior(child);
// "child.isTerminated()": during resuming the children, it can
// happen that a sentry will be satisfied, so that a child
// will terminated. these terminated child cannot be resumed,
// so ignore it.
// "child.isSuspended()": maybe the child has been already
// suspended, so ignore it.
if (!child.isTerminated() && !child.isSuspended()) {
if (behavior instanceof StageOrTaskActivityBehavior) {
child.parentSuspend();
} else { /* behavior instanceof EventListenerOrMilestoneActivityBehavior */
child.suspend();
}
}
}
}
}
protected boolean isAbleToSuspend(CmmnActivityExecution execution) {
List<? extends CmmnExecution> children = execution.getCaseExecutions();
if (children != null && !children.isEmpty()) {
for (CmmnExecution child : children) {
if (!child.isSuspended()) {
return false;
}
}
}
return true;
}
// resume /////////////////////////////////////////////////////////////////////////
public void resumed(CmmnActivityExecution execution) {
if (execution.isAvailable()) {
// trigger created() to check whether an exit- or
// entryCriteria has been satisfied in the meantime.
created(execution);
} else if (execution.isActive()) {
// if the given case execution is active after resuming,
// then propagate it to the children.
resumeChildren(execution);
}
}
protected void resumeChildren(CmmnActivityExecution execution) {
List<? extends CmmnExecution> children = execution.getCaseExecutions();
if (children != null && !children.isEmpty()) {
for (CmmnExecution child : children) {
CmmnActivityBehavior behavior = getActivityBehavior(child);
// during resuming the children, it can happen that a sentry
// will be satisfied, so that a child will terminated. these
// terminated child cannot be resumed, so ignore it.
if (!child.isTerminated()) {
if (behavior instanceof StageOrTaskActivityBehavior) {
child.parentResume();
} else { /* behavior instanceof EventListenerOrMilestoneActivityBehavior */
child.resume();
}
}
}
}
}
// sentry ///////////////////////////////////////////////////////////////////////////////
protected boolean isAtLeastOneEntryCriterionSatisfied(CmmnActivityExecution execution) {
if (!execution.isCaseInstanceExecution()) {
return super.isAtLeastOneEntryCriterionSatisfied(execution);
}
return false;
}
public void fireExitCriteria(CmmnActivityExecution execution) {
if (!execution.isCaseInstanceExecution()) {
execution.exit();
} else {
execution.terminate();
}
}
public void fireEntryCriteria(CmmnActivityExecution execution) {
if (!execution.isCaseInstanceExecution()) {
super.fireEntryCriteria(execution);
return;
}
throw LOG.criteriaNotAllowedForCaseInstanceException("entry", execution.getId());
}
// handle child state changes ///////////////////////////////////////////////////////////
public void handleChildCompletion(CmmnActivityExecution execution, CmmnActivityExecution child) {
fireForceUpdate(execution);
if (execution.isActive()) {
checkAndCompleteCaseExecution(execution);
}
}
public void handleChildDisabled(CmmnActivityExecution execution, CmmnActivityExecution child) {
fireForceUpdate(execution);
if (execution.isActive()) {
checkAndCompleteCaseExecution(execution);
}
}
public void handleChildSuspension(CmmnActivityExecution execution, CmmnActivityExecution child) {
// if the given execution is not suspending currently, then ignore this notification.
if (execution.isSuspending() && isAbleToSuspend(execution)) {
String id = execution.getId();
CaseExecutionState currentState = execution.getCurrentState();
if (SUSPENDING_ON_SUSPENSION.equals(currentState)) {
execution.performSuspension();
} else if (SUSPENDING_ON_PARENT_SUSPENSION.equals(currentState)) {
execution.performParentSuspension();
} else {
throw LOG.suspendCaseException(id, currentState);
}
}
}
public void handleChildTermination(CmmnActivityExecution execution, CmmnActivityExecution child) {
fireForceUpdate(execution);
if (execution.isActive()) {
checkAndCompleteCaseExecution(execution);
} else if (execution.isTerminating() && isAbleToTerminate(execution)) {
String id = execution.getId();
CaseExecutionState currentState = execution.getCurrentState();
if (TERMINATING_ON_TERMINATION.equals(currentState)) {
execution.performTerminate();
} else if (TERMINATING_ON_EXIT.equals(currentState)) {
execution.performExit();
} else if (TERMINATING_ON_PARENT_TERMINATION.equals(currentState)) {
throw LOG.illegalStateTransitionException("parentTerminate", id, getTypeName());
} else {
throw LOG.terminateCaseException(id, currentState);
}
}
}
protected void checkAndCompleteCaseExecution(CmmnActivityExecution execution) {
if (canComplete(execution)) {
execution.complete();
}
}
protected void fireForceUpdate(CmmnActivityExecution execution) {
if (execution instanceof CaseExecutionEntity) {
CaseExecutionEntity entity = (CaseExecutionEntity) execution;
entity.forceUpdate();
}
}
protected String getTypeName() {
return "stage";
}
}
|
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.broad.igv.bbfile;
import htsjdk.samtools.seekablestream.SeekableStream;
import org.broad.igv.logging.*;
import org.broad.igv.util.LittleEndianInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: martind
* Date: Dec 17, 2009
* Time: 12:28:30 PM
* To change this template use File | Settings | File Templates.
*/
/*
* B+ Tree class will construct a B+ tree from a binary Bed/Wig BBFile.
* (or by insertion of tree nodes - TBD see insert method)
*
* 1) BPTree will first read in the B+ tree header with BPTreeHeader class.
*
* 2) Starting with the root node, the readBPTreeNode method will read in the
* node format, determine if the node contains child nodes (isLeaf = false)
* or leaf items (isLeaf = true).
*
* 3) If node is a leaf node, all leaf items are read in to the node's leaf array.
*
* 4) If node is a child node, readBPTreeNode will be called recursively,
* until the leaf node is encountered, where step 3 is performed.
*
* 5) The child nodes will be populated with their child node items in reverse order
* of recursion from step 4, until the tree is completely populated
* back up to the root node.
*
* 6) The getChromosomeKey is provided to construct a valid key for B+
* chromosome tree searches, and getChromosomeID returns a chromosome ID for
* searches in the R+ index tree.
*
**/
public class BPTree {
private static Logger log = LogManager.getLogger(BPTree.class);
public static final int BPTREE_NODE_FORMAT_SIZE = 4; // node format size
public static final int BPTREE_NODE_ITEM_SIZE = 8; // Plus keySize to be added
// B+ tree access variables - for reading in B+ tree nodes from a file
private SeekableStream fis; // file handle - BBFile input stream
private long treeOffset; // mChromosome B+ tree file offset
private BPTreeHeader treeHeader; // B+ tree header (Table E for BBFile)
// B+ tree organizational variables - derived from Table E
private int blockSize; // number of children per block
private int keySize; // character size of primary key
private int valueSize; // number of bytes in value being indexed
private long itemCount; // number of contig/mChromosome items in tree
// B+ tree nodal variables
private BPTreeNode rootNode; // B+ tree root node
private long nodeCount; // number of nodes defined in the B+ tree
private long leafCount; // number of leaves in the B+ tree
private Map<Integer, String> idChromMap;
private Map<String, Integer> chromIdMap;
/*
* Constructor for reading in a B+ tree from a BBFile/input stream.
*
* Parameters:
* fis - file input stream handle
* fileOffset - file offset to the B+ tree header
* isLowToHigh - indicates byte order is low to high, else is high to low
* */
public BPTree(SeekableStream fis, long fileOffset, boolean isLowToHigh) {
// Save the seekable file handle and B+ Tree file offset
// Note: the offset is the B+ Tree Header Table E file location
this.fis = fis;
treeOffset = fileOffset;
idChromMap = new HashMap<>();
chromIdMap = new HashMap<>();
// read in B+ tree header - verify the B+ tree info exits
treeHeader = new BPTreeHeader(this.fis, treeOffset, isLowToHigh);
// log error if header not found and throw exception
if (!treeHeader.isHeaderOK()) {
int badMagic = treeHeader.getMagic();
log.error("Error reading B+ tree header: bad magic = " + badMagic);
throw new RuntimeException("Error reading B+ tree header: bad magic = "
+ badMagic);
}
// assign B+ tree specifications from the header
blockSize = treeHeader.getBlockSize();
keySize = treeHeader.getKeySize();
valueSize = treeHeader.getValSize();
itemCount = treeHeader.getItemCount();
// populate the tree - read in the nodes
long nodeOffset = treeOffset + treeHeader.BPTREE_HEADER_SIZE;
BPTreeNode parentNode = null; // parent node of the root is itself, or null
// get the root node - which recursively populates the remaining nodes
rootNode = readBPTreeNode(this.fis, nodeOffset, parentNode, isLowToHigh);
}
/*
* Method returns the file input stream handle
* */
public SeekableStream getFis() {
return fis;
}
/*
* Method returns the chromosome name key size, which is
* the number of valid characters for chromosome name.
* */
public int getKeySize() {
return keySize;
}
/*
* Method returns the number of chromosome/contig names.
*/
public long getItemCount() {
return itemCount;
}
Map<String, String> chromosomeKeyCache = new HashMap();
/*
* Returns a search key for the mChromosome region which can
* be used to search for a corresponding section in the B+ tree.
*
* According the the spec the key is the "first keySize characters of chromosome name"
* */
public String getChromosomeKey(String chromosome) {
String key = chromosomeKeyCache.get(chromosome);
if (key == null) {
key = chromosome.length() <= keySize ? chromosome : chromosome.substring(0, keySize);
chromosomeKeyCache.put(chromosome, key);
}
return key;
}
/*
* Returns a chromosome ID which can be used to search for a
* corresponding data section in the R+ tree for data.
*
Parameters:
* chromKey - chromosome name of valid key size.
*
*
* Note: A chromosomeID of -1 means chromosome name not included in B+ tree.
*
* */
public int getChromosomeID(String chromKey) {
Integer chromId = chromIdMap.get(chromKey);
return chromId == null ? -1 : chromId.intValue();
}
/*
* Returns a chromosome name which is the B+ key for returning the
* chromosome ID for lookup in the R+ tree for data.
*
* Parameters:
* chromID - chromosome ID expected in B+ tree
*
* Returns:
* Chromosome name key; a null string means chromosome ID not found.
*
* */
public String getChromosomeName(int chromID) {
return idChromMap.get(chromID);
}
/*
* Method returns all chromosome key names in B+ tree.
*
* Returns:
* Collection of all (chromosome ID, chromosome name)entries
* */
public ArrayList<String> getChromosomeNames() {
return new ArrayList<>(chromIdMap.keySet());
}
/*
* Method returns all chromosome name, chromosome ID pairs for a given ID range.
*
* Parameters:
* startChromID - starting ID for chromosome range expected in B+ tree
* endChromID - ending ID for chromosome range expected in B+ tree
*
* Returns:
* Collection of (chromosome ID, chromosome name key) hash items;
* where an empty collection means ID range was not found.
*
* */
public Map<Integer, String> getChromosomeIDMap(int startChromID, int endChromID) {
Map<Integer, String> m = new HashMap<>();
for (int i = startChromID; i <= endChromID; i++) {
String c = idChromMap.get(i);
if (c != null) {
m.put(i, c);
}
}
return m;
}
// prints out the B+ Tree nodes and leaves
public void print() {
// check if read in
if (!treeHeader.isHeaderOK()) {
int badMagic = treeHeader.getMagic();
log.error("Error reading B+ tree header: bad magic = " + badMagic);
return;
}
// print B+ tree header
treeHeader.print();
// print B+ tree node and leaf items - recursively
if (rootNode != null)
rootNode.printItems();
}
/*
* Method reads in the B+ tree nodes from the file, recursively.
*
* Parameters:
* fis - file input stream handle
* fileOffset - file offset for B+ tree header
* keySize - chromosome name key size in characters
* parent - parent node
* isLowToHigh - if true, indicates byte order is low to high; else is high to low
*
* Returns:
* Boolean which indicates if the B+ tree header was read correctly, with
* true for success, false for failure to find the header information.
* */
private BPTreeNode readBPTreeNode(SeekableStream fis, long fileOffset,
BPTreeNode parent, boolean isLowToHigh) {
LittleEndianInputStream lbdis = null; // low to high byte reader
DataInputStream bdis = null; // high to low byte reader
// set up for node format
byte[] buffer = new byte[BPTREE_NODE_FORMAT_SIZE];
BPTreeNode thisNode = null;
BPTreeNode childNode = null;
byte type;
byte bval;
int itemCount;
int itemSize;
boolean isLeaf;
try {
// Read node format into a buffer
fis.seek(fileOffset);
fis.readFully(buffer);
if (isLowToHigh)
lbdis = new LittleEndianInputStream(new ByteArrayInputStream(buffer));
else
bdis = new DataInputStream(new ByteArrayInputStream(buffer));
// find node type
if (isLowToHigh)
type = lbdis.readByte();
else
type = bdis.readByte();
// create the B+ tree node
if (type == 1) {
isLeaf = true;
thisNode = new BPTreeLeafNode(++nodeCount);
} else {
isLeaf = false;
thisNode = new BPTreeChildNode(++nodeCount);
}
if (isLowToHigh) {
bval = lbdis.readByte(); // reserved - not currently used
itemCount = lbdis.readUShort();
} else {
bval = bdis.readByte(); // reserved - not currently used
itemCount = bdis.readUnsignedShort();
}
// Note: B+ tree node item size is the same for leaf and child items
itemSize = BPTREE_NODE_ITEM_SIZE + this.keySize;
int totalSize = itemSize * itemCount;
byte[] itemBuffer = new byte[totalSize];
fis.readFully(itemBuffer);
if (isLowToHigh)
lbdis = new LittleEndianInputStream(new ByteArrayInputStream(itemBuffer));
else
bdis = new DataInputStream(new ByteArrayInputStream(itemBuffer));
// get the node items - leaves or child nodes
for (int item = 0; item < itemCount; ++item) {
// always extract the key from the node format
char[] keychars = new char[keySize]; // + 1 for 0 byte
int index;
for (index = 0; index < keySize; ++index) {
if (isLowToHigh)
bval = lbdis.readByte();
else
bval = bdis.readByte();
keychars[index] = (char) bval;
}
String key = new String(keychars).trim();
int chromID;
int chromSize;
long childOffset;
if (isLeaf) {
if (isLowToHigh) {
chromID = lbdis.readInt();
chromSize = lbdis.readInt();
} else {
chromID = bdis.readInt();
chromSize = bdis.readInt();
}
idChromMap.put(chromID, key);
chromIdMap.put(key, chromID);
// insert leaf items
BPTreeLeafNodeItem leafItem = new BPTreeLeafNodeItem(++leafCount, key, chromID, chromSize);
thisNode.insertItem(leafItem);
} else {
// get the child node pointed to in the node item
if (isLowToHigh)
childOffset = lbdis.readLong();
else
childOffset = bdis.readLong();
childNode = readBPTreeNode(this.fis, childOffset, thisNode, isLowToHigh);
// insert child node item
BPTreeChildNodeItem childItem = new BPTreeChildNodeItem(item, key, childNode);
thisNode.insertItem(childItem);
}
fileOffset += itemSize;
}
} catch (IOException ex) {
log.error("Error reading B+ tree node " + ex);
throw new RuntimeException("Error reading B+ tree node \n ", ex);
}
// success: return node
return thisNode;
}
}
|
|
/* Generated By:JJTree: Do not edit this line. SimpleNode.java */
package syntax_analyzer.compiler.model;
import code.*;
import syntax_analyzer.compiler.MiniJavaParser;
import syntax_analyzer.compiler.MiniJavaParserTreeConstants;
import syntax_analyzer.compiler.MiniJavaTypeCheck;
import syntax_analyzer.compiler.visitor.MiniJavaCheckVisitor;
import syntax_analyzer.compiler.visitor.MiniJavaParserVisitor;
public class SimpleNode extends BaseNode implements Node {
protected Node parent;
public Node[] children;
protected int id;
protected MiniJavaParser parser;
public String getName() {
return name;
}
public SimpleNode(int i) {
id = i;
}
public SimpleNode(MiniJavaParser p, int i) {
this(i);
parser = p;
}
public void jjtOpen() {
}
public void jjtClose() {
}
public void jjtSetParent(Node n) {
parent = n;
}
public Node jjtGetParent() {
return parent;
}
public void jjtAddChild(Node n, int i) {
if (children == null) {
children = new Node[i + 1];
} else if (i >= children.length) {
Node c[] = new Node[i + 1];
System.arraycopy(children, 0, c, 0, children.length);
children = c;
}
children[i] = n;
}
public Node jjtGetChild(int i) {
return children[i];
}
public int jjtGetNumChildren() {
return (children == null) ? 0 : children.length;
}
/** Accept the visitor. * */
public Object jjtAccept(MiniJavaParserVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public String acceptTypeCheck(MiniJavaCheckVisitor visitor, Symbol thisClass, int times){
if(children==null){
children=new Node[0];
}
if(this instanceof ASTRoot)
return visitor.visit((ASTRoot)this, thisClass,times);
if(this instanceof ASTMainClass)
return visitor.visit((ASTMainClass)this, thisClass,times);
if(this instanceof ASTMainMethodDeclaration)
return visitor.visit((ASTMainMethodDeclaration)this, thisClass,times);
if(this instanceof ASTClassDeclaration)
return visitor.visit((ASTClassDeclaration)this, thisClass,times);
if(this instanceof ASTClassExtendsDeclaration)
return visitor.visit((ASTClassExtendsDeclaration)this, thisClass,times);
if(this instanceof ASTVariableDeclaration)
return visitor.visit((ASTVariableDeclaration)this, thisClass,times);
if(this instanceof ASTMethodDeclaration)
return visitor.visit((ASTMethodDeclaration)this, thisClass,times);
if(this instanceof ASTFormalParameter)
return visitor.visit((ASTFormalParameter)this, thisClass,times);
if(this instanceof ASTType)
return visitor.visit((ASTType)this, thisClass,times);
if(this instanceof ASTArrayType)
return visitor.visit((ASTArrayType)this, thisClass,times);
if(this instanceof ASTBooleanType)
return visitor.visit((ASTBooleanType)this, thisClass,times);
if(this instanceof ASTIntegerType)
return visitor.visit((ASTIntegerType)this, thisClass,times);
if(this instanceof ASTIdentifier)
return visitor.visit((ASTIdentifier)this, thisClass,times);
if(this instanceof ASTStatement)
return visitor.visit((ASTStatement)this, thisClass,times);
if(this instanceof ASTBlock)
return visitor.visit((ASTBlock)this, thisClass,times);
if(this instanceof ASTAssignmentStatement)
return visitor.visit((ASTAssignmentStatement)this, thisClass,times);
if(this instanceof ASTArrayAssignmentStatement)
return visitor.visit((ASTArrayAssignmentStatement)this, thisClass,times);
if(this instanceof ASTIfStatement)
return visitor.visit((ASTIfStatement)this, thisClass,times);
if(this instanceof ASTWhileStatement)
return visitor.visit((ASTWhileStatement)this, thisClass,times);
if(this instanceof ASTPrintStatement)
return visitor.visit((ASTPrintStatement)this, thisClass,times);
if(this instanceof ASTExpression)
return visitor.visit((ASTExpression)this, thisClass,times);
if(this instanceof ASTAndExpression)
return visitor.visit((ASTAndExpression)this, thisClass,times);
if(this instanceof ASTCompareExpression)
return visitor.visit((ASTCompareExpression)this, thisClass,times);
if(this instanceof ASTPlusExpression)
return visitor.visit((ASTPlusExpression)this, thisClass,times);
if(this instanceof ASTMinusExpression)
return visitor.visit((ASTMinusExpression)this, thisClass,times);
if(this instanceof ASTTimesExpression)
return visitor.visit((ASTTimesExpression)this, thisClass,times);
if(this instanceof ASTArrayLookUp)
return visitor.visit((ASTArrayLookUp)this, thisClass,times);
if(this instanceof ASTArrayLength)
return visitor.visit((ASTArrayLength)this, thisClass,times);
if(this instanceof ASTMessageSend)
return visitor.visit((ASTMessageSend)this, thisClass,times);
if(this instanceof ASTIntegerLiteral)
return visitor.visit((ASTIntegerLiteral)this, thisClass,times);
if(this instanceof ASTTrueLiteral)
return visitor.visit((ASTTrueLiteral)this, thisClass,times);
if(this instanceof ASTFalseLiteral)
return visitor.visit((ASTFalseLiteral)this, thisClass,times);
if(this instanceof ASTNotExpression)
return visitor.visit((ASTNotExpression)this, thisClass,times);
return visitor.visit(this, thisClass,times);
}
/** Accept the visitor. * */
public Object childrenAccept(MiniJavaParserVisitor visitor, Object data) {
if (children != null) {
for (int i = 0; i < children.length; ++i) {
children[i].jjtAccept(visitor, data);
}
}
return data;
}
/*
* You can override these two methods in subclasses of SimpleNode to
* customize the way the node appears when the tree is dumped. If your
* output uses more than one line you should override toString(String),
* otherwise overriding toString() is probably all you need to do.
*/
public String toString() {
return MiniJavaParserTreeConstants.jjtNodeName[id];
}
public String toString(String prefix) {
return prefix + toString();
}
/*
* Override this method if you want to customize how the node dumps out its
* children.
*/
public void printFileContent(int lineBegin_, int lineEnd_,
int conlumnBegin_, int conlumnEnd_) {
System.out.println("(" + lineBegin_ + "), " + "(" + lineEnd_ + "), ");
System.out.println("(" + conlumnBegin_ + "), " + "(" + conlumnEnd_
+ "), ");
lineBegin_--;lineEnd_--;conlumnBegin_--;
try{
if (lineBegin_ == lineEnd_) {
System.out.println(MiniJavaTypeCheck.fileContent.get(lineBegin_)
.substring(conlumnBegin_, conlumnEnd_));
} else {
System.out.println(MiniJavaTypeCheck.fileContent.get(lineBegin_)
.substring(conlumnBegin_));
for (int i = lineBegin_ + 1; i < lineEnd_; i++) {
System.out.println(MiniJavaTypeCheck.fileContent.get(i));
}
System.out.println(MiniJavaTypeCheck.fileContent.get(lineEnd_)
.substring(0, conlumnEnd_));
}
}catch(Exception e){
e.printStackTrace();
System.out.println("");
}
}
public String getFileContent() {
int lineBegin_= this.getBeginLine(); int lineEnd_ = this.getEndLine();
int conlumnBegin_ = this.getBeginColumn(); int conlumnEnd_ = this.getEndColumn();
String ret="";
lineBegin_--;lineEnd_--;conlumnBegin_--;
try{
if (lineBegin_ == lineEnd_) {
ret+=MiniJavaTypeCheck.fileContent.get(lineBegin_)
.substring(conlumnBegin_, conlumnEnd_);
} else {
ret+=MiniJavaTypeCheck.fileContent.get(lineBegin_)
.substring(conlumnBegin_);
for (int i = lineBegin_ + 1; i < lineEnd_; i++) {
ret+=MiniJavaTypeCheck.fileContent.get(i);
}
ret+=MiniJavaTypeCheck.fileContent.get(lineEnd_)
.substring(0, conlumnEnd_);
}
return ret;
}catch(Exception e){
System.out.println("null in simple node");
e.printStackTrace();
return " null in simple node";
}
}
public void dump(String prefix) {
System.out.println(toString(prefix));
if (children != null) {
for (int i = 0; i < children.length; i++) {
Node temp = children[i];
SimpleNode n = (SimpleNode) children[i];
// if (n != null) {
printFileContent(n.getBeginLine(), n.getEndLine(),
n.getBeginColumn(), n.getEndColumn());
n.dump(prefix + " ");
// }
}
}
}
public Node[] getChildren() {
return children;
}
}
|
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/talent/v4beta1/profile.proto
package com.google.cloud.talent.v4beta1;
/**
*
*
* <pre>
* Candidate availability signal.
* </pre>
*
* Protobuf type {@code google.cloud.talent.v4beta1.AvailabilitySignal}
*/
public final class AvailabilitySignal extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.talent.v4beta1.AvailabilitySignal)
AvailabilitySignalOrBuilder {
private static final long serialVersionUID = 0L;
// Use AvailabilitySignal.newBuilder() to construct.
private AvailabilitySignal(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AvailabilitySignal() {
type_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new AvailabilitySignal();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private AvailabilitySignal(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8:
{
int rawValue = input.readEnum();
type_ = rawValue;
break;
}
case 18:
{
com.google.protobuf.Timestamp.Builder subBuilder = null;
if (lastUpdateTime_ != null) {
subBuilder = lastUpdateTime_.toBuilder();
}
lastUpdateTime_ =
input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(lastUpdateTime_);
lastUpdateTime_ = subBuilder.buildPartial();
}
break;
}
case 26:
{
com.google.protobuf.BoolValue.Builder subBuilder = null;
if (filterSatisfied_ != null) {
subBuilder = filterSatisfied_.toBuilder();
}
filterSatisfied_ =
input.readMessage(com.google.protobuf.BoolValue.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(filterSatisfied_);
filterSatisfied_ = subBuilder.buildPartial();
}
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.talent.v4beta1.ProfileResourceProto
.internal_static_google_cloud_talent_v4beta1_AvailabilitySignal_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.talent.v4beta1.ProfileResourceProto
.internal_static_google_cloud_talent_v4beta1_AvailabilitySignal_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.talent.v4beta1.AvailabilitySignal.class,
com.google.cloud.talent.v4beta1.AvailabilitySignal.Builder.class);
}
public static final int TYPE_FIELD_NUMBER = 1;
private int type_;
/**
*
*
* <pre>
* Type of signal.
* </pre>
*
* <code>.google.cloud.talent.v4beta1.AvailabilitySignalType type = 1;</code>
*
* @return The enum numeric value on the wire for type.
*/
@java.lang.Override
public int getTypeValue() {
return type_;
}
/**
*
*
* <pre>
* Type of signal.
* </pre>
*
* <code>.google.cloud.talent.v4beta1.AvailabilitySignalType type = 1;</code>
*
* @return The type.
*/
@java.lang.Override
public com.google.cloud.talent.v4beta1.AvailabilitySignalType getType() {
@SuppressWarnings("deprecation")
com.google.cloud.talent.v4beta1.AvailabilitySignalType result =
com.google.cloud.talent.v4beta1.AvailabilitySignalType.valueOf(type_);
return result == null
? com.google.cloud.talent.v4beta1.AvailabilitySignalType.UNRECOGNIZED
: result;
}
public static final int LAST_UPDATE_TIME_FIELD_NUMBER = 2;
private com.google.protobuf.Timestamp lastUpdateTime_;
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*
* @return Whether the lastUpdateTime field is set.
*/
@java.lang.Override
public boolean hasLastUpdateTime() {
return lastUpdateTime_ != null;
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*
* @return The lastUpdateTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getLastUpdateTime() {
return lastUpdateTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: lastUpdateTime_;
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getLastUpdateTimeOrBuilder() {
return getLastUpdateTime();
}
public static final int FILTER_SATISFIED_FIELD_NUMBER = 3;
private com.google.protobuf.BoolValue filterSatisfied_;
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*
* @return Whether the filterSatisfied field is set.
*/
@java.lang.Override
public boolean hasFilterSatisfied() {
return filterSatisfied_ != null;
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*
* @return The filterSatisfied.
*/
@java.lang.Override
public com.google.protobuf.BoolValue getFilterSatisfied() {
return filterSatisfied_ == null
? com.google.protobuf.BoolValue.getDefaultInstance()
: filterSatisfied_;
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*/
@java.lang.Override
public com.google.protobuf.BoolValueOrBuilder getFilterSatisfiedOrBuilder() {
return getFilterSatisfied();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (type_
!= com.google.cloud.talent.v4beta1.AvailabilitySignalType
.AVAILABILITY_SIGNAL_TYPE_UNSPECIFIED
.getNumber()) {
output.writeEnum(1, type_);
}
if (lastUpdateTime_ != null) {
output.writeMessage(2, getLastUpdateTime());
}
if (filterSatisfied_ != null) {
output.writeMessage(3, getFilterSatisfied());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (type_
!= com.google.cloud.talent.v4beta1.AvailabilitySignalType
.AVAILABILITY_SIGNAL_TYPE_UNSPECIFIED
.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, type_);
}
if (lastUpdateTime_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getLastUpdateTime());
}
if (filterSatisfied_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getFilterSatisfied());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.talent.v4beta1.AvailabilitySignal)) {
return super.equals(obj);
}
com.google.cloud.talent.v4beta1.AvailabilitySignal other =
(com.google.cloud.talent.v4beta1.AvailabilitySignal) obj;
if (type_ != other.type_) return false;
if (hasLastUpdateTime() != other.hasLastUpdateTime()) return false;
if (hasLastUpdateTime()) {
if (!getLastUpdateTime().equals(other.getLastUpdateTime())) return false;
}
if (hasFilterSatisfied() != other.hasFilterSatisfied()) return false;
if (hasFilterSatisfied()) {
if (!getFilterSatisfied().equals(other.getFilterSatisfied())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + TYPE_FIELD_NUMBER;
hash = (53 * hash) + type_;
if (hasLastUpdateTime()) {
hash = (37 * hash) + LAST_UPDATE_TIME_FIELD_NUMBER;
hash = (53 * hash) + getLastUpdateTime().hashCode();
}
if (hasFilterSatisfied()) {
hash = (37 * hash) + FILTER_SATISFIED_FIELD_NUMBER;
hash = (53 * hash) + getFilterSatisfied().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.talent.v4beta1.AvailabilitySignal prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Candidate availability signal.
* </pre>
*
* Protobuf type {@code google.cloud.talent.v4beta1.AvailabilitySignal}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.talent.v4beta1.AvailabilitySignal)
com.google.cloud.talent.v4beta1.AvailabilitySignalOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.talent.v4beta1.ProfileResourceProto
.internal_static_google_cloud_talent_v4beta1_AvailabilitySignal_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.talent.v4beta1.ProfileResourceProto
.internal_static_google_cloud_talent_v4beta1_AvailabilitySignal_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.talent.v4beta1.AvailabilitySignal.class,
com.google.cloud.talent.v4beta1.AvailabilitySignal.Builder.class);
}
// Construct using com.google.cloud.talent.v4beta1.AvailabilitySignal.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
type_ = 0;
if (lastUpdateTimeBuilder_ == null) {
lastUpdateTime_ = null;
} else {
lastUpdateTime_ = null;
lastUpdateTimeBuilder_ = null;
}
if (filterSatisfiedBuilder_ == null) {
filterSatisfied_ = null;
} else {
filterSatisfied_ = null;
filterSatisfiedBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.talent.v4beta1.ProfileResourceProto
.internal_static_google_cloud_talent_v4beta1_AvailabilitySignal_descriptor;
}
@java.lang.Override
public com.google.cloud.talent.v4beta1.AvailabilitySignal getDefaultInstanceForType() {
return com.google.cloud.talent.v4beta1.AvailabilitySignal.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.talent.v4beta1.AvailabilitySignal build() {
com.google.cloud.talent.v4beta1.AvailabilitySignal result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.talent.v4beta1.AvailabilitySignal buildPartial() {
com.google.cloud.talent.v4beta1.AvailabilitySignal result =
new com.google.cloud.talent.v4beta1.AvailabilitySignal(this);
result.type_ = type_;
if (lastUpdateTimeBuilder_ == null) {
result.lastUpdateTime_ = lastUpdateTime_;
} else {
result.lastUpdateTime_ = lastUpdateTimeBuilder_.build();
}
if (filterSatisfiedBuilder_ == null) {
result.filterSatisfied_ = filterSatisfied_;
} else {
result.filterSatisfied_ = filterSatisfiedBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.talent.v4beta1.AvailabilitySignal) {
return mergeFrom((com.google.cloud.talent.v4beta1.AvailabilitySignal) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.talent.v4beta1.AvailabilitySignal other) {
if (other == com.google.cloud.talent.v4beta1.AvailabilitySignal.getDefaultInstance())
return this;
if (other.type_ != 0) {
setTypeValue(other.getTypeValue());
}
if (other.hasLastUpdateTime()) {
mergeLastUpdateTime(other.getLastUpdateTime());
}
if (other.hasFilterSatisfied()) {
mergeFilterSatisfied(other.getFilterSatisfied());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.talent.v4beta1.AvailabilitySignal parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.talent.v4beta1.AvailabilitySignal) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int type_ = 0;
/**
*
*
* <pre>
* Type of signal.
* </pre>
*
* <code>.google.cloud.talent.v4beta1.AvailabilitySignalType type = 1;</code>
*
* @return The enum numeric value on the wire for type.
*/
@java.lang.Override
public int getTypeValue() {
return type_;
}
/**
*
*
* <pre>
* Type of signal.
* </pre>
*
* <code>.google.cloud.talent.v4beta1.AvailabilitySignalType type = 1;</code>
*
* @param value The enum numeric value on the wire for type to set.
* @return This builder for chaining.
*/
public Builder setTypeValue(int value) {
type_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Type of signal.
* </pre>
*
* <code>.google.cloud.talent.v4beta1.AvailabilitySignalType type = 1;</code>
*
* @return The type.
*/
@java.lang.Override
public com.google.cloud.talent.v4beta1.AvailabilitySignalType getType() {
@SuppressWarnings("deprecation")
com.google.cloud.talent.v4beta1.AvailabilitySignalType result =
com.google.cloud.talent.v4beta1.AvailabilitySignalType.valueOf(type_);
return result == null
? com.google.cloud.talent.v4beta1.AvailabilitySignalType.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* Type of signal.
* </pre>
*
* <code>.google.cloud.talent.v4beta1.AvailabilitySignalType type = 1;</code>
*
* @param value The type to set.
* @return This builder for chaining.
*/
public Builder setType(com.google.cloud.talent.v4beta1.AvailabilitySignalType value) {
if (value == null) {
throw new NullPointerException();
}
type_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Type of signal.
* </pre>
*
* <code>.google.cloud.talent.v4beta1.AvailabilitySignalType type = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearType() {
type_ = 0;
onChanged();
return this;
}
private com.google.protobuf.Timestamp lastUpdateTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
lastUpdateTimeBuilder_;
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*
* @return Whether the lastUpdateTime field is set.
*/
public boolean hasLastUpdateTime() {
return lastUpdateTimeBuilder_ != null || lastUpdateTime_ != null;
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*
* @return The lastUpdateTime.
*/
public com.google.protobuf.Timestamp getLastUpdateTime() {
if (lastUpdateTimeBuilder_ == null) {
return lastUpdateTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: lastUpdateTime_;
} else {
return lastUpdateTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*/
public Builder setLastUpdateTime(com.google.protobuf.Timestamp value) {
if (lastUpdateTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
lastUpdateTime_ = value;
onChanged();
} else {
lastUpdateTimeBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*/
public Builder setLastUpdateTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (lastUpdateTimeBuilder_ == null) {
lastUpdateTime_ = builderForValue.build();
onChanged();
} else {
lastUpdateTimeBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*/
public Builder mergeLastUpdateTime(com.google.protobuf.Timestamp value) {
if (lastUpdateTimeBuilder_ == null) {
if (lastUpdateTime_ != null) {
lastUpdateTime_ =
com.google.protobuf.Timestamp.newBuilder(lastUpdateTime_)
.mergeFrom(value)
.buildPartial();
} else {
lastUpdateTime_ = value;
}
onChanged();
} else {
lastUpdateTimeBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*/
public Builder clearLastUpdateTime() {
if (lastUpdateTimeBuilder_ == null) {
lastUpdateTime_ = null;
onChanged();
} else {
lastUpdateTime_ = null;
lastUpdateTimeBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*/
public com.google.protobuf.Timestamp.Builder getLastUpdateTimeBuilder() {
onChanged();
return getLastUpdateTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*/
public com.google.protobuf.TimestampOrBuilder getLastUpdateTimeOrBuilder() {
if (lastUpdateTimeBuilder_ != null) {
return lastUpdateTimeBuilder_.getMessageOrBuilder();
} else {
return lastUpdateTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: lastUpdateTime_;
}
}
/**
*
*
* <pre>
* Timestamp of when the given availability activity last happened.
* </pre>
*
* <code>.google.protobuf.Timestamp last_update_time = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getLastUpdateTimeFieldBuilder() {
if (lastUpdateTimeBuilder_ == null) {
lastUpdateTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getLastUpdateTime(), getParentForChildren(), isClean());
lastUpdateTime_ = null;
}
return lastUpdateTimeBuilder_;
}
private com.google.protobuf.BoolValue filterSatisfied_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.BoolValue,
com.google.protobuf.BoolValue.Builder,
com.google.protobuf.BoolValueOrBuilder>
filterSatisfiedBuilder_;
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*
* @return Whether the filterSatisfied field is set.
*/
public boolean hasFilterSatisfied() {
return filterSatisfiedBuilder_ != null || filterSatisfied_ != null;
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*
* @return The filterSatisfied.
*/
public com.google.protobuf.BoolValue getFilterSatisfied() {
if (filterSatisfiedBuilder_ == null) {
return filterSatisfied_ == null
? com.google.protobuf.BoolValue.getDefaultInstance()
: filterSatisfied_;
} else {
return filterSatisfiedBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*/
public Builder setFilterSatisfied(com.google.protobuf.BoolValue value) {
if (filterSatisfiedBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
filterSatisfied_ = value;
onChanged();
} else {
filterSatisfiedBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*/
public Builder setFilterSatisfied(com.google.protobuf.BoolValue.Builder builderForValue) {
if (filterSatisfiedBuilder_ == null) {
filterSatisfied_ = builderForValue.build();
onChanged();
} else {
filterSatisfiedBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*/
public Builder mergeFilterSatisfied(com.google.protobuf.BoolValue value) {
if (filterSatisfiedBuilder_ == null) {
if (filterSatisfied_ != null) {
filterSatisfied_ =
com.google.protobuf.BoolValue.newBuilder(filterSatisfied_)
.mergeFrom(value)
.buildPartial();
} else {
filterSatisfied_ = value;
}
onChanged();
} else {
filterSatisfiedBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*/
public Builder clearFilterSatisfied() {
if (filterSatisfiedBuilder_ == null) {
filterSatisfied_ = null;
onChanged();
} else {
filterSatisfied_ = null;
filterSatisfiedBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*/
public com.google.protobuf.BoolValue.Builder getFilterSatisfiedBuilder() {
onChanged();
return getFilterSatisfiedFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*/
public com.google.protobuf.BoolValueOrBuilder getFilterSatisfiedOrBuilder() {
if (filterSatisfiedBuilder_ != null) {
return filterSatisfiedBuilder_.getMessageOrBuilder();
} else {
return filterSatisfied_ == null
? com.google.protobuf.BoolValue.getDefaultInstance()
: filterSatisfied_;
}
}
/**
*
*
* <pre>
* Indicates if the [last_update_time][google.cloud.talent.v4beta1.AvailabilitySignal.last_update_time] is within
* [AvailabilityFilter.range][google.cloud.talent.v4beta1.AvailabilityFilter.range].
* Returned only in a search response when there is an [AvailabilityFilter][google.cloud.talent.v4beta1.AvailabilityFilter]
* in [ProfileQuery.availability_filters][google.cloud.talent.v4beta1.ProfileQuery.availability_filters] where
* [signal_type][google.cloud.talent.v4beta1.AvailabilityFilter.signal_type] matches [type][google.cloud.talent.v4beta1.AvailabilitySignal.type].
* </pre>
*
* <code>.google.protobuf.BoolValue filter_satisfied = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.BoolValue,
com.google.protobuf.BoolValue.Builder,
com.google.protobuf.BoolValueOrBuilder>
getFilterSatisfiedFieldBuilder() {
if (filterSatisfiedBuilder_ == null) {
filterSatisfiedBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.BoolValue,
com.google.protobuf.BoolValue.Builder,
com.google.protobuf.BoolValueOrBuilder>(
getFilterSatisfied(), getParentForChildren(), isClean());
filterSatisfied_ = null;
}
return filterSatisfiedBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.talent.v4beta1.AvailabilitySignal)
}
// @@protoc_insertion_point(class_scope:google.cloud.talent.v4beta1.AvailabilitySignal)
private static final com.google.cloud.talent.v4beta1.AvailabilitySignal DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.talent.v4beta1.AvailabilitySignal();
}
public static com.google.cloud.talent.v4beta1.AvailabilitySignal getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AvailabilitySignal> PARSER =
new com.google.protobuf.AbstractParser<AvailabilitySignal>() {
@java.lang.Override
public AvailabilitySignal parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new AvailabilitySignal(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<AvailabilitySignal> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AvailabilitySignal> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.talent.v4beta1.AvailabilitySignal getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.contrib.bkjournal;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.hadoop.hdfs.server.namenode.EditLogInputStream;
import org.apache.hadoop.hdfs.server.namenode.FSEditLogOp;
import org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader;
import org.apache.bookkeeper.client.LedgerHandle;
import org.apache.bookkeeper.client.LedgerEntry;
import org.apache.bookkeeper.client.BKException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Input stream which reads from a BookKeeper ledger.
*/
class BookKeeperEditLogInputStream extends EditLogInputStream {
static final Log LOG = LogFactory.getLog(BookKeeperEditLogInputStream.class);
private final long firstTxId;
private final long lastTxId;
private final int logVersion;
private final boolean inProgress;
private final LedgerHandle lh;
private final FSEditLogOp.Reader reader;
private final FSEditLogLoader.PositionTrackingInputStream tracker;
/**
* Construct BookKeeper edit log input stream.
* Starts reading from the first entry of the ledger.
*/
BookKeeperEditLogInputStream(final LedgerHandle lh,
final EditLogLedgerMetadata metadata)
throws IOException {
this(lh, metadata, 0);
}
/**
* Construct BookKeeper edit log input stream.
* Starts reading from firstBookKeeperEntry. This allows the stream
* to take a shortcut during recovery, as it doesn't have to read
* every edit log transaction to find out what the last one is.
*/
BookKeeperEditLogInputStream(LedgerHandle lh, EditLogLedgerMetadata metadata,
long firstBookKeeperEntry)
throws IOException {
this.lh = lh;
this.firstTxId = metadata.getFirstTxId();
this.lastTxId = metadata.getLastTxId();
this.logVersion = metadata.getDataLayoutVersion();
this.inProgress = metadata.isInProgress();
if (firstBookKeeperEntry < 0
|| firstBookKeeperEntry > lh.getLastAddConfirmed()) {
throw new IOException("Invalid first bk entry to read: "
+ firstBookKeeperEntry + ", LAC: " + lh.getLastAddConfirmed());
}
BufferedInputStream bin = new BufferedInputStream(
new LedgerInputStream(lh, firstBookKeeperEntry));
tracker = new FSEditLogLoader.PositionTrackingInputStream(bin);
DataInputStream in = new DataInputStream(tracker);
reader = new FSEditLogOp.Reader(in, tracker, logVersion);
}
@Override
public long getFirstTxId() {
return firstTxId;
}
@Override
public long getLastTxId() {
return lastTxId;
}
@Override
public int getVersion(boolean verifyVersion) throws IOException {
return logVersion;
}
@Override
protected FSEditLogOp nextOp() throws IOException {
return reader.readOp(false);
}
@Override
public void close() throws IOException {
try {
lh.close();
} catch (BKException e) {
throw new IOException("Exception closing ledger", e);
} catch (InterruptedException e) {
throw new IOException("Interrupted closing ledger", e);
}
}
@Override
public long getPosition() {
return tracker.getPos();
}
@Override
public long length() throws IOException {
return lh.getLength();
}
@Override
public String getName() {
return String.format(
"BookKeeperLedger[ledgerId=%d,firstTxId=%d,lastTxId=%d]", lh.getId(),
firstTxId, lastTxId);
}
@Override
public boolean isInProgress() {
return inProgress;
}
/**
* Skip forward to specified transaction id.
* Currently we do this by just iterating forward.
* If this proves to be too expensive, this can be reimplemented
* with a binary search over bk entries
*/
public void skipTo(long txId) throws IOException {
long numToSkip = getFirstTxId() - txId;
FSEditLogOp op = null;
for (long i = 0; i < numToSkip; i++) {
op = readOp();
}
if (op != null && op.getTransactionId() != txId-1) {
throw new IOException("Corrupt stream, expected txid "
+ (txId-1) + ", got " + op.getTransactionId());
}
}
@Override
public String toString() {
return ("BookKeeperEditLogInputStream {" + this.getName() + "}");
}
@Override
public void setMaxOpSize(int maxOpSize) {
reader.setMaxOpSize(maxOpSize);
}
/**
* Input stream implementation which can be used by
* FSEditLogOp.Reader
*/
private static class LedgerInputStream extends InputStream {
private long readEntries;
private InputStream entryStream = null;
private final LedgerHandle lh;
private final long maxEntry;
/**
* Construct ledger input stream
* @param lh the ledger handle to read from
* @param firstBookKeeperEntry ledger entry to start reading from
*/
LedgerInputStream(LedgerHandle lh, long firstBookKeeperEntry)
throws IOException {
this.lh = lh;
readEntries = firstBookKeeperEntry;
maxEntry = lh.getLastAddConfirmed();
}
/**
* Get input stream representing next entry in the
* ledger.
* @return input stream, or null if no more entries
*/
private InputStream nextStream() throws IOException {
try {
if (readEntries > maxEntry) {
return null;
}
Enumeration<LedgerEntry> entries
= lh.readEntries(readEntries, readEntries);
readEntries++;
if (entries.hasMoreElements()) {
LedgerEntry e = entries.nextElement();
assert !entries.hasMoreElements();
return e.getEntryInputStream();
}
} catch (BKException e) {
throw new IOException("Error reading entries from bookkeeper", e);
} catch (InterruptedException e) {
throw new IOException("Interrupted reading entries from bookkeeper", e);
}
return null;
}
@Override
public int read() throws IOException {
byte[] b = new byte[1];
if (read(b, 0, 1) != 1) {
return -1;
} else {
return b[0];
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
try {
int read = 0;
if (entryStream == null) {
entryStream = nextStream();
if (entryStream == null) {
return read;
}
}
while (read < len) {
int thisread = entryStream.read(b, off+read, (len-read));
if (thisread == -1) {
entryStream = nextStream();
if (entryStream == null) {
return read;
}
} else {
read += thisread;
}
}
return read;
} catch (IOException e) {
throw e;
}
}
}
}
|
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.plugin;
import java.net.URI;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerPlugin;
import org.apache.activemq.broker.BrokerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A BrokerStatisticsPluginTest
* A testcase for https://issues.apache.org/activemq/browse/AMQ-2379
*/
public class BrokerStatisticsPluginTest extends TestCase {
private static final Logger LOG = LoggerFactory.getLogger(BrokerStatisticsPluginTest.class);
private Connection connection;
private BrokerService broker;
public void testBrokerStats() throws Exception {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue replyTo = session.createTemporaryQueue();
MessageConsumer consumer = session.createConsumer(replyTo);
Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX);
MessageProducer producer = session.createProducer(query);
Message msg = session.createMessage();
msg.setJMSReplyTo(replyTo);
producer.send(msg);
MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
assertNotNull(reply);
assertTrue(reply.getMapNames().hasMoreElements());
assertTrue(reply.getJMSTimestamp() > 0);
assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
/*
for (Enumeration e = reply.getMapNames();e.hasMoreElements();) {
String name = e.nextElement().toString();
System.err.println(name+"="+reply.getObject(name));
}
*/
}
public void testBrokerStatsReset() throws Exception {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue replyTo = session.createTemporaryQueue();
MessageConsumer consumer = session.createConsumer(replyTo);
Queue testQueue = session.createQueue("Test.Queue");
Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX);
MessageProducer producer = session.createProducer(null);
producer.send(testQueue, session.createMessage());
Message msg = session.createMessage();
msg.setJMSReplyTo(replyTo);
producer.send(query, msg);
MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
assertNotNull(reply);
assertTrue(reply.getMapNames().hasMoreElements());
assertTrue(reply.getLong("enqueueCount") >= 1);
msg = session.createMessage();
msg.setBooleanProperty(StatisticsBroker.STATS_BROKER_RESET_HEADER, true);
msg.setJMSReplyTo(replyTo);
producer.send(query, msg);
reply = (MapMessage) consumer.receive(10 * 1000);
assertNotNull(reply);
assertTrue(reply.getMapNames().hasMoreElements());
assertEquals(0, reply.getLong("enqueueCount"));
assertTrue(reply.getJMSTimestamp() > 0);
assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
}
public void testDestinationStats() throws Exception {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue replyTo = session.createTemporaryQueue();
MessageConsumer consumer = session.createConsumer(replyTo);
Queue testQueue = session.createQueue("Test.Queue");
MessageProducer producer = session.createProducer(null);
Queue query = session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + testQueue.getQueueName());
Message msg = session.createMessage();
producer.send(testQueue, msg);
msg.setJMSReplyTo(replyTo);
producer.send(query, msg);
MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
assertNotNull(reply);
assertTrue(reply.getMapNames().hasMoreElements());
assertTrue(reply.getJMSTimestamp() > 0);
assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
/*
for (Enumeration e = reply.getMapNames();e.hasMoreElements();) {
String name = e.nextElement().toString();
System.err.println(name+"="+reply.getObject(name));
}
*/
}
public void testDestinationStatsWithDot() throws Exception {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue replyTo = session.createTemporaryQueue();
MessageConsumer consumer = session.createConsumer(replyTo);
Queue testQueue = session.createQueue("Test.Queue");
MessageProducer producer = session.createProducer(null);
Queue query = session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + "." + testQueue.getQueueName());
Message msg = session.createMessage();
producer.send(testQueue, msg);
msg.setJMSReplyTo(replyTo);
producer.send(query, msg);
MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
assertNotNull(reply);
assertTrue(reply.getMapNames().hasMoreElements());
assertTrue(reply.getJMSTimestamp() > 0);
assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
/*
for (Enumeration e = reply.getMapNames();e.hasMoreElements();) {
String name = e.nextElement().toString();
System.err.println(name+"="+reply.getObject(name));
}
*/
}
@SuppressWarnings("unused")
public void testSubscriptionStats() throws Exception {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue replyTo = session.createTemporaryQueue();
MessageConsumer consumer = session.createConsumer(replyTo);
Queue testQueue = session.createQueue("Test.Queue");
MessageConsumer testConsumer = session.createConsumer(testQueue);
MessageProducer producer = session.createProducer(null);
Queue query = session.createQueue(StatisticsBroker.STATS_SUBSCRIPTION_PREFIX);
Message msg = session.createMessage();
producer.send(testQueue, msg);
msg.setJMSReplyTo(replyTo);
producer.send(query, msg);
MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
assertNotNull(reply);
assertTrue(reply.getMapNames().hasMoreElements());
assertTrue(reply.getJMSTimestamp() > 0);
assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
/*for (Enumeration e = reply.getMapNames();e.hasMoreElements();) {
String name = e.nextElement().toString();
System.err.println(name+"="+reply.getObject(name));
}*/
}
@Override
protected void setUp() throws Exception {
broker = createBroker();
ConnectionFactory factory = new ActiveMQConnectionFactory(broker.getTransportConnectorURIsAsMap().get("tcp"));
connection = factory.createConnection();
connection.start();
}
@Override
protected void tearDown() throws Exception {
if (this.connection != null) {
this.connection.close();
}
if (this.broker != null) {
this.broker.stop();
}
}
protected BrokerService createBroker() throws Exception {
BrokerService answer = new BrokerService();
BrokerPlugin[] plugins = new BrokerPlugin[1];
plugins[0] = new StatisticsBrokerPlugin();
answer.setPlugins(plugins);
answer.setDeleteAllMessagesOnStartup(true);
answer.addConnector("tcp://localhost:0");
answer.start();
return answer;
}
protected BrokerService createBroker(String uri) throws Exception {
LOG.info("Loading broker configuration from the classpath with URI: " + uri);
return BrokerFactory.createBroker(new URI("xbean:" + uri));
}
}
|
|
/*
* 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.druid.indexer;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.data.input.MapBasedInputRow;
import org.apache.druid.indexer.partitions.DimensionBasedPartitionsSpec;
import org.apache.druid.indexer.partitions.HashedPartitionsSpec;
import org.apache.druid.indexer.partitions.PartitionsSpec;
import org.apache.druid.indexer.partitions.SingleDimensionPartitionsSpec;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.segment.indexing.DataSchema;
import org.apache.druid.segment.indexing.granularity.UniformGranularitySpec;
import org.apache.druid.timeline.partition.HashBasedNumberedShardSpec;
import org.apache.druid.timeline.partition.NoneShardSpec;
import org.junit.Assert;
import org.junit.Test;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class HadoopDruidIndexerConfigTest
{
private static final ObjectMapper JSON_MAPPER;
static {
JSON_MAPPER = new DefaultObjectMapper();
JSON_MAPPER.setInjectableValues(new InjectableValues.Std().addValue(ObjectMapper.class, JSON_MAPPER));
}
@Test
public void testHashedBucketSelection()
{
List<HadoopyShardSpec> shardSpecs = new ArrayList<>();
final int partitionCount = 10;
for (int i = 0; i < partitionCount; i++) {
shardSpecs.add(new HadoopyShardSpec(
new HashBasedNumberedShardSpec(i, partitionCount, null, new DefaultObjectMapper()),
i
));
}
HadoopIngestionSpec spec = new HadoopIngestionSpecBuilder()
.shardSpecs(ImmutableMap.of(DateTimes.of("2010-01-01T01:00:00").getMillis(), shardSpecs))
.build();
HadoopDruidIndexerConfig config = HadoopDruidIndexerConfig.fromSpec(spec);
final List<String> dims = Arrays.asList("diM1", "dIM2");
final ImmutableMap<String, Object> values = ImmutableMap.of(
"Dim1",
"1",
"DiM2",
"2",
"dim1",
"3",
"dim2",
"4"
);
final long timestamp = DateTimes.of("2010-01-01T01:00:01").getMillis();
final Bucket expectedBucket = config.getBucket(new MapBasedInputRow(timestamp, dims, values)).get();
final long nextBucketTimestamp = Granularities.MINUTE.bucketEnd(DateTimes.utc(timestamp)).getMillis();
// check that all rows having same set of dims and truncated timestamp hash to same bucket
for (int i = 0; timestamp + i < nextBucketTimestamp; i++) {
Assert.assertEquals(
expectedBucket.partitionNum,
config.getBucket(new MapBasedInputRow(timestamp + i, dims, values)).get().partitionNum
);
}
}
@Test
public void testNoneShardSpecBucketSelection()
{
Map<Long, List<HadoopyShardSpec>> shardSpecs = ImmutableMap.of(
DateTimes.of("2010-01-01T01:00:00").getMillis(),
Collections.singletonList(new HadoopyShardSpec(
NoneShardSpec.instance(),
1
)),
DateTimes.of("2010-01-01T02:00:00").getMillis(),
Collections.singletonList(new HadoopyShardSpec(
NoneShardSpec.instance(),
2
))
);
HadoopIngestionSpec spec = new HadoopIngestionSpecBuilder()
.shardSpecs(shardSpecs)
.build();
HadoopDruidIndexerConfig config = HadoopDruidIndexerConfig.fromSpec(spec);
final List<String> dims = Arrays.asList("diM1", "dIM2");
final ImmutableMap<String, Object> values = ImmutableMap.of(
"Dim1",
"1",
"DiM2",
"2",
"dim1",
"3",
"dim2",
"4"
);
final long ts1 = DateTimes.of("2010-01-01T01:00:01").getMillis();
Assert.assertEquals(1, config.getBucket(new MapBasedInputRow(ts1, dims, values)).get().getShardNum());
final long ts2 = DateTimes.of("2010-01-01T02:00:01").getMillis();
Assert.assertEquals(2, config.getBucket(new MapBasedInputRow(ts2, dims, values)).get().getShardNum());
}
@Test
public void testGetTargetPartitionSizeWithHashedPartitions()
{
HadoopIngestionSpec spec = new HadoopIngestionSpecBuilder()
.partitionsSpec(HashedPartitionsSpec.defaultSpec())
.build();
HadoopDruidIndexerConfig config = new HadoopDruidIndexerConfig(spec);
int targetPartitionSize = config.getTargetPartitionSize();
Assert.assertEquals(PartitionsSpec.DEFAULT_MAX_ROWS_PER_SEGMENT, targetPartitionSize);
}
@Test
public void testGetTargetPartitionSizeWithSingleDimensionPartitionsTargetRowsPerSegment()
{
int targetRowsPerSegment = 123;
SingleDimensionPartitionsSpec partitionsSpec = new SingleDimensionPartitionsSpec(
targetRowsPerSegment,
null,
null,
false
);
HadoopIngestionSpec spec = new HadoopIngestionSpecBuilder()
.partitionsSpec(partitionsSpec)
.build();
HadoopDruidIndexerConfig config = new HadoopDruidIndexerConfig(spec);
int targetPartitionSize = config.getTargetPartitionSize();
Assert.assertEquals(targetRowsPerSegment, targetPartitionSize);
}
@Test
public void testGetTargetPartitionSizeWithSingleDimensionPartitionsMaxRowsPerSegment()
{
int maxRowsPerSegment = 456;
SingleDimensionPartitionsSpec partitionsSpec = new SingleDimensionPartitionsSpec(
null,
maxRowsPerSegment,
null,
false
);
HadoopIngestionSpec spec = new HadoopIngestionSpecBuilder()
.partitionsSpec(partitionsSpec)
.build();
HadoopDruidIndexerConfig config = new HadoopDruidIndexerConfig(spec);
int targetPartitionSize = config.getTargetPartitionSize();
Assert.assertEquals(maxRowsPerSegment, targetPartitionSize);
}
private static class HadoopIngestionSpecBuilder
{
private static final DataSchema DATA_SCHEMA = new DataSchema(
"foo",
null,
new AggregatorFactory[0],
new UniformGranularitySpec(
Granularities.MINUTE,
Granularities.MINUTE,
ImmutableList.of(Intervals.of("2010-01-01/P1D"))
),
null,
HadoopDruidIndexerConfigTest.JSON_MAPPER
);
private static final HadoopIOConfig HADOOP_IO_CONFIG = new HadoopIOConfig(
ImmutableMap.of("paths", "bar", "type", "static"),
null,
null
);
@Nullable
private DimensionBasedPartitionsSpec partitionsSpec = null;
private Map<Long, List<HadoopyShardSpec>> shardSpecs = Collections.emptyMap();
HadoopIngestionSpecBuilder partitionsSpec(DimensionBasedPartitionsSpec partitionsSpec)
{
this.partitionsSpec = partitionsSpec;
return this;
}
HadoopIngestionSpecBuilder shardSpecs(Map<Long, List<HadoopyShardSpec>> shardSpecs)
{
this.shardSpecs = shardSpecs;
return this;
}
HadoopIngestionSpec build()
{
HadoopTuningConfig hadoopTuningConfig = new HadoopTuningConfig(
null,
null,
partitionsSpec,
shardSpecs,
null,
null,
null,
null,
false,
false,
false,
false,
null,
false,
false,
null,
null,
null,
false,
false,
null,
null,
null,
null
);
return new HadoopIngestionSpec(
DATA_SCHEMA,
HADOOP_IO_CONFIG,
hadoopTuningConfig
);
}
}
}
|
|
package io.github.nasso.nhengine.ui.control;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import io.github.nasso.nhengine.core.Nhengine;
import io.github.nasso.nhengine.graphics.Color;
import io.github.nasso.nhengine.graphics.GraphicsContext2D;
import io.github.nasso.nhengine.ui.UIComponent;
import io.github.nasso.nhengine.ui.UIContainer;
import io.github.nasso.nhengine.ui.layout.UIBorderLayout;
import io.github.nasso.nhengine.ui.layout.UIBoxLayout;
import io.github.nasso.nhengine.ui.layout.UICardLayout;
import io.github.nasso.nhengine.utils.FloatTransition;
import io.github.nasso.nhengine.utils.MathUtils;
import io.github.nasso.nhengine.utils.Nhutils;
public class UITabbedPane extends UIContainer {
private class TabView extends UIContainer {
private class TabViewCloseButton extends UIComponent {
private FloatTransition hoverTransition = new FloatTransition(0.2f, this::transitionStep, 0);
public TabViewCloseButton() {
}
private void transitionStep(float x) {
this.repaint();
}
public boolean mouseEntered(float x, float y, float rx, float ry) {
this.hoverTransition.setTargetValue(1);
return true;
}
public boolean mouseExited(float x, float y, float rx, float ry) {
this.hoverTransition.setTargetValue(0);
return true;
}
public boolean mouseClicked(int btn) {
if(btn == Nhengine.MOUSE_BUTTON_LEFT) {
TabView.this.closeTab();
}
return false;
}
protected void paintComponent(GraphicsContext2D gtx) {
float w = this.getWidth() - this.getPaddingLeft() - this.getPaddingRight();
float h = this.getHeight() - this.getPaddingTop() - this.getPaddingBottom();
gtx.translate(this.getPaddingLeft(), this.getPaddingTop());
if(this.hoverTransition.isFinished()) {
gtx.setFill(this.isMouseOver() ? UITabbedPane.this.getTabCloseButtonHoverBackground() : UITabbedPane.this.getTabCloseButtonBackground());
} else {
gtx.setFill(Nhutils.colorBlend(UITabbedPane.this.getTabCloseButtonBackground(), UITabbedPane.this.getTabCloseButtonHoverBackground(), this.hoverTransition.getValue()));
}
gtx.fillRoundedRect(0, 0, w, h, UITabbedPane.this.getTabCloseButtonBorderRadius());
gtx.setStroke(UITabbedPane.this.getTabCloseButtonForeground());
gtx.beginPath();
gtx.moveTo(w * 0.25f, h * 0.25f);
gtx.lineTo(w * 0.75f, h * 0.75f);
gtx.moveTo(w * 0.75f, h * 0.25f);
gtx.lineTo(w * 0.25f, h * 0.75f);
gtx.stroke();
}
public void computePreferredSize() {
this.preferredSize.set(UITabbedPane.this.getTabCloseButtonSize());
this.preferredSize.x += this.getPaddingLeft() + this.getPaddingRight();
this.preferredSize.y += this.getPaddingTop() + this.getPaddingBottom();
}
}
private Tab tab;
private UILabel label;
private TabViewCloseButton closeBtn;
public TabView(Tab t) {
this.tab = t;
this.label = new UILabel(null, UILabel.ANCHOR_LEFT) {
public CharSequence getText() {
return TabView.this.tab.title;
}
};
this.label.setPadding(0, 4, 0, 2);
this.closeBtn = new TabViewCloseButton();
this.closeBtn.setPadding(0, 0, 2, 0);
this.setLayout(new UIBoxLayout(UIBoxLayout.HORIZONTAL, 4, UIBoxLayout.BOTTOM, false));
this.setOpaque(false);
this.add(this.label);
if(this.tab.closeable) this.add(this.closeBtn);
this.setPadding(2, 4);
}
private void closeTab() {
this.tab.closeTab();
}
public float getPaddingLeft() {
return super.getPaddingLeft() + UITabbedPane.this.getTabAngleWidth();
}
public float getPaddingRight() {
return super.getPaddingRight() + UITabbedPane.this.getTabAngleWidth();
}
public boolean mouseClicked(int btn) {
if(btn == Nhengine.MOUSE_BUTTON_LEFT) UITabbedPane.this.setTab(this.tab);
return true;
}
private boolean isActive() {
return this.tab == UITabbedPane.this.getCurrentTab();
}
protected void paintComponent(GraphicsContext2D gtx) {
gtx.setFill(this.isActive() ? UITabbedPane.this.getActiveTabBackground() : UITabbedPane.this.getTabBackground());
float angleW = UITabbedPane.this.getTabAngleWidth();
if(angleW <= 0) {
gtx.fillRect(0, 0, this.getWidth(), this.getHeight());
} else {
gtx.beginPath();
gtx.moveTo(0, this.getHeight());
gtx.lineTo(angleW, 0);
gtx.lineTo(this.getWidth() - angleW, 0);
gtx.lineTo(this.getWidth(), this.getHeight());
gtx.fill();
gtx.translate(angleW, 0);
}
}
}
public class Tab {
private TabView view;
private CharSequence title;
private boolean closeable;
private UIComponent comp;
private Consumer<Tab> onClosing, onClosed;
private Tab(UIComponent comp, CharSequence title, boolean closeable) {
this.comp = comp;
this.title = title;
this.closeable = closeable;
this.view = new TabView(this);
}
public boolean isCloseable() {
return this.closeable;
}
public void setCloseable(boolean closeable) {
this.closeable = closeable;
}
private void closeTab() {
if(!this.closeable) return;
if(this.onClosing != null) this.onClosing.accept(this);
UITabbedPane.this.removeTab(this);
if(this.onClosed != null) this.onClosed.accept(this);
}
public UIComponent getComponent() {
return this.comp;
}
public void setComponent(UIComponent comp) {
this.comp = comp;
}
public CharSequence getTitle() {
return this.title;
}
public void setTitle(CharSequence title) {
this.title = title;
}
public Consumer<Tab> getOnClosing() {
return this.onClosing;
}
public void setOnClosing(Consumer<Tab> onClosing) {
this.onClosing = onClosing;
}
public Consumer<Tab> getOnClosed() {
return this.onClosed;
}
public void setOnClosed(Consumer<Tab> onClosed) {
this.onClosed = onClosed;
}
}
private List<Tab> tabs = new ArrayList<Tab>();
private int currentTab = -1;
private float tabAngleWidth = USE_THEME_VALUE;
private float tabCloseBtnBorderRadius = USE_THEME_VALUE;
private float tabCloseBtnSize = USE_THEME_VALUE;
private UIContainer head;
private UIContainer body;
private UICardLayout cardLayout;
private Color tabBackground = null;
private Color activeTabBackground = null;
private Color tabCloseButtonBackground = null;
private Color tabCloseButtonForeground = null;
private Color tabCloseButtonHoverBackground = null;
private Consumer<UITabbedPane> onTabChange;
public UITabbedPane() {
this.head = new UIContainer();
this.head.setPadding(0, 2);
this.head.setOpaque(false);
this.head.setLayout(new UIBoxLayout(UIBoxLayout.HORIZONTAL, 2));
this.body = new UIContainer() {
public Color getBackground() {
return UITabbedPane.this.getActiveTabBackground();
}
};
this.body.setPadding(1);
this.body.setLayout(this.cardLayout = new UICardLayout());
this.setLayout(new UIBorderLayout());
this.add(this.head, UIBorderLayout.NORTH);
this.add(this.body, UIBorderLayout.CENTER);
}
public Color getBackground() {
return this.getTheme().getColor("tabPane.background", this.background);
}
private void fireTabChange() {
if(this.onTabChange != null) this.onTabChange.accept(this);
}
public Tab insertTab(int i, CharSequence title, boolean closeable, UIComponent comp) {
i = MathUtils.clamp(i, 0, this.tabs.size());
Tab newTab = new Tab(comp, title, closeable);
this.tabs.add(i, newTab);
this.head.add(i, newTab.view);
this.body.add(i, newTab.comp);
this.repack();
if(this.currentTab < 0) this.setTab(i);
return newTab;
}
public Tab insertTab(String title, UIComponent comp) {
return this.insertTab(this.tabs.size(), title, true, comp);
}
public void removeTab(int i) {
if(i < 0 || i >= this.tabs.size()) return;
this.tabs.remove(i);
this.head.remove(i);
this.body.remove(i);
this.head.repack();
if(this.currentTab == i) {
this.currentTab = -1; // Trick to force change
if(i < this.tabs.size()) this.setTab(i);
else this.setTab(this.tabs.size() - 1);
} else if(this.currentTab > i) {
this.currentTab--;
}
}
public void removeTab(Tab t) {
if(!this.tabs.contains(t)) return;
this.removeTab(this.tabs.indexOf(t));
}
public Tab getTab(int i) {
if(i < 0 || i >= this.tabs.size()) return null;
return this.tabs.get(i);
}
public void setTab(Tab t) {
if(!this.tabs.contains(t)) return;
this.setTab(this.tabs.indexOf(t));
}
public void setTab(int i) {
if(this.currentTab == i) return;
this.cardLayout.setCurrentCard(i);
this.currentTab = i;
this.fireTabChange();
}
public Tab getCurrentTab() {
return this.getTab(this.getCurrentTabIndex());
}
public int getCurrentTabIndex() {
return this.currentTab;
}
public Color getTabBackground() {
return this.getTheme().getColor("tabPane.tab.background", this.tabBackground);
}
public void setTabBackground(Color tabBackground) {
this.tabBackground = tabBackground;
}
public float getTabAngleWidth() {
return this.getTheme().getFloat("tabPane.tab.angleWidth", this.tabAngleWidth);
}
public void setTabAngleWidth(float tabAngleWidth) {
this.tabAngleWidth = tabAngleWidth;
}
public Color getActiveTabBackground() {
return this.getTheme().getColor("tabPane.activeTab.background", this.activeTabBackground);
}
public void setActiveTabBackground(Color activeTabBackground) {
this.activeTabBackground = activeTabBackground;
}
public float getTabCloseButtonSize() {
return this.getTheme().getFloat("tabPane.tab.closeButton.size", this.tabCloseBtnSize);
}
public void setTabCloseButtonSize(float tabCloseBtnSize) {
this.tabCloseBtnSize = tabCloseBtnSize;
}
public float getTabCloseButtonBorderRadius() {
return this.getTheme().getFloat("tabPane.tab.closeButton.borderRadius", this.tabCloseBtnBorderRadius);
}
public void setTabCloseButtonBorderRadius(float tabCloseBtnBorderRadius) {
this.tabCloseBtnBorderRadius = tabCloseBtnBorderRadius;
}
public Color getTabCloseButtonBackground() {
return this.getTheme().getColor("tabPane.tab.closeButton.background", this.tabCloseButtonBackground);
}
public void setTabCloseButtonBackground(Color tabCloseButtonBackground) {
this.tabCloseButtonBackground = tabCloseButtonBackground;
}
public Color getTabCloseButtonForeground() {
return this.getTheme().getColor("tabPane.tab.closeButton.foreground", this.tabCloseButtonForeground);
}
public void setTabCloseButtonForeground(Color tabCloseButtonForeground) {
this.tabCloseButtonForeground = tabCloseButtonForeground;
}
public Color getTabCloseButtonHoverBackground() {
return this.getTheme().getColor("tabPane.tab.closeButton.hoverBackground", this.tabCloseButtonHoverBackground);
}
public void setTabCloseButtonHoverBackground(Color tabCloseButtonHoverBackground) {
this.tabCloseButtonHoverBackground = tabCloseButtonHoverBackground;
}
public Consumer<UITabbedPane> getOnTabChange() {
return this.onTabChange;
}
public void setOnTabChange(Consumer<UITabbedPane> onTabChange) {
this.onTabChange = onTabChange;
}
}
|
|
/*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.client;
import android.net.SSLCertificateSocketFactory;
import java.io.Closeable;
import java.net.ProxySelector;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.BackoffManager;
import org.apache.http.client.ConnectionBackoffStrategy;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.client.UserTokenHandler;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.RequestAcceptEncoding;
import org.apache.http.client.protocol.RequestAddCookiesHC4;
import org.apache.http.client.protocol.RequestAuthCache;
import org.apache.http.client.protocol.RequestClientConnControl;
import org.apache.http.client.protocol.RequestDefaultHeadersHC4;
import org.apache.http.client.protocol.RequestExpectContinue;
import org.apache.http.client.protocol.ResponseContentEncoding;
import org.apache.http.client.protocol.ResponseProcessCookiesHC4;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.Lookup;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.SchemePortResolver;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.impl.DefaultConnectionReuseStrategyHC4;
import org.apache.http.impl.NoConnectionReuseStrategyHC4;
import org.apache.http.impl.auth.BasicSchemeFactoryHC4;
import org.apache.http.impl.auth.DigestSchemeFactoryHC4;
import org.apache.http.impl.auth.NTLMSchemeFactory;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.impl.cookie.BestMatchSpecFactoryHC4;
import org.apache.http.impl.cookie.BrowserCompatSpecFactoryHC4;
import org.apache.http.impl.cookie.IgnoreSpecFactory;
import org.apache.http.impl.cookie.NetscapeDraftSpecFactoryHC4;
import org.apache.http.impl.cookie.RFC2109SpecFactoryHC4;
import org.apache.http.impl.cookie.RFC2965SpecFactoryHC4;
import org.apache.http.impl.execchain.BackoffStrategyExec;
import org.apache.http.impl.execchain.ClientExecChain;
import org.apache.http.impl.execchain.MainClientExec;
import org.apache.http.impl.execchain.ProtocolExec;
import org.apache.http.impl.execchain.RedirectExec;
import org.apache.http.impl.execchain.RetryExec;
import org.apache.http.impl.execchain.ServiceUnavailableRetryExec;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestContentHC4;
import org.apache.http.protocol.RequestTargetHostHC4;
import org.apache.http.protocol.RequestUserAgentHC4;
import org.apache.http.util.TextUtils;
import org.apache.http.util.VersionInfoHC4;
/**
* Builder for {@link CloseableHttpClient} instances.
* <p/>
* When a particular component is not explicitly this class will
* use its default implementation. System properties will be taken
* into account when configuring the default implementations when
* {@link #useSystemProperties()} method is called prior to calling
* {@link #build()}.
* <ul>
* <li>ssl.TrustManagerFactory.algorithm</li>
* <li>javax.net.ssl.trustStoreType</li>
* <li>javax.net.ssl.trustStore</li>
* <li>javax.net.ssl.trustStoreProvider</li>
* <li>javax.net.ssl.trustStorePassword</li>
* <li>ssl.KeyManagerFactory.algorithm</li>
* <li>javax.net.ssl.keyStoreType</li>
* <li>javax.net.ssl.keyStore</li>
* <li>javax.net.ssl.keyStoreProvider</li>
* <li>javax.net.ssl.keyStorePassword</li>
* <li>https.protocols</li>
* <li>https.cipherSuites</li>
* <li>http.proxyHost</li>
* <li>http.proxyPort</li>
* <li>http.nonProxyHosts</li>
* <li>http.keepAlive</li>
* <li>http.maxConnections</li>
* <li>http.agent</li>
* </ul>
* <p/>
* Please note that some settings used by this class can be mutually
* exclusive and may not apply when building {@link CloseableHttpClient}
* instances.
*
* @since 4.3
*/
@NotThreadSafe
public class HttpClientBuilder {
private HttpRequestExecutor requestExec;
private X509HostnameVerifier hostnameVerifier;
private LayeredConnectionSocketFactory sslSocketFactory;
private SSLContext sslcontext;
private HttpClientConnectionManager connManager;
private SchemePortResolver schemePortResolver;
private ConnectionReuseStrategy reuseStrategy;
private ConnectionKeepAliveStrategy keepAliveStrategy;
private AuthenticationStrategy targetAuthStrategy;
private AuthenticationStrategy proxyAuthStrategy;
private UserTokenHandler userTokenHandler;
private HttpProcessor httpprocessor;
private LinkedList<HttpRequestInterceptor> requestFirst;
private LinkedList<HttpRequestInterceptor> requestLast;
private LinkedList<HttpResponseInterceptor> responseFirst;
private LinkedList<HttpResponseInterceptor> responseLast;
private HttpRequestRetryHandler retryHandler;
private HttpRoutePlanner routePlanner;
private RedirectStrategy redirectStrategy;
private ConnectionBackoffStrategy connectionBackoffStrategy;
private BackoffManager backoffManager;
private ServiceUnavailableRetryStrategy serviceUnavailStrategy;
private Lookup<AuthSchemeProvider> authSchemeRegistry;
private Lookup<CookieSpecProvider> cookieSpecRegistry;
private CookieStore cookieStore;
private CredentialsProvider credentialsProvider;
private String userAgent;
private HttpHost proxy;
private Collection<? extends Header> defaultHeaders;
private SocketConfig defaultSocketConfig;
private ConnectionConfig defaultConnectionConfig;
private RequestConfig defaultRequestConfig;
private boolean systemProperties;
private boolean redirectHandlingDisabled;
private boolean automaticRetriesDisabled;
private boolean contentCompressionDisabled;
private boolean cookieManagementDisabled;
private boolean authCachingDisabled;
private boolean connectionStateDisabled;
private int maxConnTotal = 0;
private int maxConnPerRoute = 0;
private List<Closeable> closeables;
static final String DEFAULT_USER_AGENT;
static {
final VersionInfoHC4 vi = VersionInfoHC4.loadVersionInfo
("org.apache.http.client", HttpClientBuilder.class.getClassLoader());
final String release = (vi != null) ?
vi.getRelease() : VersionInfoHC4.UNAVAILABLE;
DEFAULT_USER_AGENT = "Apache-HttpClient/" + release + " (java 1.5)";
}
public static HttpClientBuilder create() {
return new HttpClientBuilder();
}
protected HttpClientBuilder() {
super();
}
/**
* Assigns {@link HttpRequestExecutor} instance.
*/
public final HttpClientBuilder setRequestExecutor(final HttpRequestExecutor requestExec) {
this.requestExec = requestExec;
return this;
}
/**
* Assigns {@link X509HostnameVerifier} instance.
* <p/>
* Please note this value can be overridden by the {@link #setConnectionManager(
* org.apache.http.conn.HttpClientConnectionManager)} and the {@link #setSSLSocketFactory(
* org.apache.http.conn.socket.LayeredConnectionSocketFactory)} methods.
*/
public final HttpClientBuilder setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
return this;
}
/**
* Assigns {@link SSLContext} instance.
* <p/>
* <p/>
* Please note this value can be overridden by the {@link #setConnectionManager(
* org.apache.http.conn.HttpClientConnectionManager)} and the {@link #setSSLSocketFactory(
* org.apache.http.conn.socket.LayeredConnectionSocketFactory)} methods.
*/
public final HttpClientBuilder setSslcontext(final SSLContext sslcontext) {
this.sslcontext = sslcontext;
return this;
}
/**
* Assigns {@link LayeredConnectionSocketFactory} instance.
* <p/>
* Please note this value can be overridden by the {@link #setConnectionManager(
* org.apache.http.conn.HttpClientConnectionManager)} method.
*/
public final HttpClientBuilder setSSLSocketFactory(
final LayeredConnectionSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
return this;
}
/**
* Assigns maximum total connection value.
* <p/>
* Please note this value can be overridden by the {@link #setConnectionManager(
* org.apache.http.conn.HttpClientConnectionManager)} method.
*/
public final HttpClientBuilder setMaxConnTotal(final int maxConnTotal) {
this.maxConnTotal = maxConnTotal;
return this;
}
/**
* Assigns maximum connection per route value.
* <p/>
* Please note this value can be overridden by the {@link #setConnectionManager(
* org.apache.http.conn.HttpClientConnectionManager)} method.
*/
public final HttpClientBuilder setMaxConnPerRoute(final int maxConnPerRoute) {
this.maxConnPerRoute = maxConnPerRoute;
return this;
}
/**
* Assigns default {@link SocketConfig}.
* <p/>
* Please note this value can be overridden by the {@link #setConnectionManager(
* org.apache.http.conn.HttpClientConnectionManager)} method.
*/
public final HttpClientBuilder setDefaultSocketConfig(final SocketConfig config) {
this.defaultSocketConfig = config;
return this;
}
/**
* Assigns default {@link ConnectionConfig}.
* <p/>
* Please note this value can be overridden by the {@link #setConnectionManager(
* org.apache.http.conn.HttpClientConnectionManager)} method.
*/
public final HttpClientBuilder setDefaultConnectionConfig(final ConnectionConfig config) {
this.defaultConnectionConfig = config;
return this;
}
/**
* Assigns {@link HttpClientConnectionManager} instance.
*/
public final HttpClientBuilder setConnectionManager(
final HttpClientConnectionManager connManager) {
this.connManager = connManager;
return this;
}
/**
* Assigns {@link ConnectionReuseStrategy} instance.
*/
public final HttpClientBuilder setConnectionReuseStrategy(
final ConnectionReuseStrategy reuseStrategy) {
this.reuseStrategy = reuseStrategy;
return this;
}
/**
* Assigns {@link ConnectionKeepAliveStrategy} instance.
*/
public final HttpClientBuilder setKeepAliveStrategy(
final ConnectionKeepAliveStrategy keepAliveStrategy) {
this.keepAliveStrategy = keepAliveStrategy;
return this;
}
/**
* Assigns {@link AuthenticationStrategy} instance for proxy
* authentication.
*/
public final HttpClientBuilder setTargetAuthenticationStrategy(
final AuthenticationStrategy targetAuthStrategy) {
this.targetAuthStrategy = targetAuthStrategy;
return this;
}
/**
* Assigns {@link AuthenticationStrategy} instance for target
* host authentication.
*/
public final HttpClientBuilder setProxyAuthenticationStrategy(
final AuthenticationStrategy proxyAuthStrategy) {
this.proxyAuthStrategy = proxyAuthStrategy;
return this;
}
/**
* Assigns {@link UserTokenHandler} instance.
* <p/>
* Please note this value can be overridden by the {@link #disableConnectionState()}
* method.
*/
public final HttpClientBuilder setUserTokenHandler(final UserTokenHandler userTokenHandler) {
this.userTokenHandler = userTokenHandler;
return this;
}
/**
* Disables connection state tracking.
*/
public final HttpClientBuilder disableConnectionState() {
connectionStateDisabled = true;
return this;
}
/**
* Assigns {@link SchemePortResolver} instance.
*/
public final HttpClientBuilder setSchemePortResolver(
final SchemePortResolver schemePortResolver) {
this.schemePortResolver = schemePortResolver;
return this;
}
/**
* Assigns <tt>User-Agent</tt> value.
* <p/>
* Please note this value can be overridden by the {@link #setHttpProcessor(
* org.apache.http.protocol.HttpProcessor)} method.
*/
public final HttpClientBuilder setUserAgent(final String userAgent) {
this.userAgent = userAgent;
return this;
}
/**
* Assigns default request header values.
* <p/>
* Please note this value can be overridden by the {@link #setHttpProcessor(
* org.apache.http.protocol.HttpProcessor)} method.
*/
public final HttpClientBuilder setDefaultHeaders(final Collection<? extends Header> defaultHeaders) {
this.defaultHeaders = defaultHeaders;
return this;
}
/**
* Adds this protocol interceptor to the head of the protocol processing list.
* <p/>
* Please note this value can be overridden by the {@link #setHttpProcessor(
* org.apache.http.protocol.HttpProcessor)} method.
*/
public final HttpClientBuilder addInterceptorFirst(final HttpResponseInterceptor itcp) {
if (itcp == null) {
return this;
}
if (responseFirst == null) {
responseFirst = new LinkedList<HttpResponseInterceptor>();
}
responseFirst.addFirst(itcp);
return this;
}
/**
* Adds this protocol interceptor to the tail of the protocol processing list.
* <p/>
* Please note this value can be overridden by the {@link #setHttpProcessor(
* org.apache.http.protocol.HttpProcessor)} method.
*/
public final HttpClientBuilder addInterceptorLast(final HttpResponseInterceptor itcp) {
if (itcp == null) {
return this;
}
if (responseLast == null) {
responseLast = new LinkedList<HttpResponseInterceptor>();
}
responseLast.addLast(itcp);
return this;
}
/**
* Adds this protocol interceptor to the head of the protocol processing list.
* <p/>
* Please note this value can be overridden by the {@link #setHttpProcessor(
* org.apache.http.protocol.HttpProcessor)} method.
*/
public final HttpClientBuilder addInterceptorFirst(final HttpRequestInterceptor itcp) {
if (itcp == null) {
return this;
}
if (requestFirst == null) {
requestFirst = new LinkedList<HttpRequestInterceptor>();
}
requestFirst.addFirst(itcp);
return this;
}
/**
* Adds this protocol interceptor to the tail of the protocol processing list.
* <p/>
* Please note this value can be overridden by the {@link #setHttpProcessor(
* org.apache.http.protocol.HttpProcessor)} method.
*/
public final HttpClientBuilder addInterceptorLast(final HttpRequestInterceptor itcp) {
if (itcp == null) {
return this;
}
if (requestLast == null) {
requestLast = new LinkedList<HttpRequestInterceptor>();
}
requestLast.addLast(itcp);
return this;
}
/**
* Disables state (cookie) management.
* <p/>
* Please note this value can be overridden by the {@link #setHttpProcessor(
* org.apache.http.protocol.HttpProcessor)} method.
*/
public final HttpClientBuilder disableCookieManagement() {
this.cookieManagementDisabled = true;
return this;
}
/**
* Disables automatic content decompression.
* <p/>
* Please note this value can be overridden by the {@link #setHttpProcessor(
* org.apache.http.protocol.HttpProcessor)} method.
*/
public final HttpClientBuilder disableContentCompression() {
contentCompressionDisabled = true;
return this;
}
/**
* Disables authentication scheme caching.
* <p/>
* Please note this value can be overridden by the {@link #setHttpProcessor(
* org.apache.http.protocol.HttpProcessor)} method.
*/
public final HttpClientBuilder disableAuthCaching() {
this.authCachingDisabled = true;
return this;
}
/**
* Assigns {@link HttpProcessor} instance.
*/
public final HttpClientBuilder setHttpProcessor(final HttpProcessor httpprocessor) {
this.httpprocessor = httpprocessor;
return this;
}
/**
* Assigns {@link HttpRequestRetryHandler} instance.
* <p/>
* Please note this value can be overridden by the {@link #disableAutomaticRetries()}
* method.
*/
public final HttpClientBuilder setRetryHandler(final HttpRequestRetryHandler retryHandler) {
this.retryHandler = retryHandler;
return this;
}
/**
* Disables automatic request recovery and re-execution.
*/
public final HttpClientBuilder disableAutomaticRetries() {
automaticRetriesDisabled = true;
return this;
}
/**
* Assigns default proxy value.
* <p/>
* Please note this value can be overridden by the {@link #setRoutePlanner(
* org.apache.http.conn.routing.HttpRoutePlanner)} method.
*/
public final HttpClientBuilder setProxy(final HttpHost proxy) {
this.proxy = proxy;
return this;
}
/**
* Assigns {@link HttpRoutePlanner} instance.
*/
public final HttpClientBuilder setRoutePlanner(final HttpRoutePlanner routePlanner) {
this.routePlanner = routePlanner;
return this;
}
/**
* Assigns {@link RedirectStrategy} instance.
* <p/>
* Please note this value can be overridden by the {@link #disableRedirectHandling()}
* method.
` */
public final HttpClientBuilder setRedirectStrategy(final RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
return this;
}
/**
* Disables automatic redirect handling.
*/
public final HttpClientBuilder disableRedirectHandling() {
redirectHandlingDisabled = true;
return this;
}
/**
* Assigns {@link ConnectionBackoffStrategy} instance.
*/
public final HttpClientBuilder setConnectionBackoffStrategy(
final ConnectionBackoffStrategy connectionBackoffStrategy) {
this.connectionBackoffStrategy = connectionBackoffStrategy;
return this;
}
/**
* Assigns {@link BackoffManager} instance.
*/
public final HttpClientBuilder setBackoffManager(final BackoffManager backoffManager) {
this.backoffManager = backoffManager;
return this;
}
/**
* Assigns {@link ServiceUnavailableRetryStrategy} instance.
*/
public final HttpClientBuilder setServiceUnavailableRetryStrategy(
final ServiceUnavailableRetryStrategy serviceUnavailStrategy) {
this.serviceUnavailStrategy = serviceUnavailStrategy;
return this;
}
/**
* Assigns default {@link CookieStore} instance which will be used for
* request execution if not explicitly set in the client execution context.
*/
public final HttpClientBuilder setDefaultCookieStore(final CookieStore cookieStore) {
this.cookieStore = cookieStore;
return this;
}
/**
* Assigns default {@link CredentialsProvider} instance which will be used
* for request execution if not explicitly set in the client execution
* context.
*/
public final HttpClientBuilder setDefaultCredentialsProvider(
final CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
/**
* Assigns default {@link org.apache.http.auth.AuthScheme} registry which will
* be used for request execution if not explicitly set in the client execution
* context.
*/
public final HttpClientBuilder setDefaultAuthSchemeRegistry(
final Lookup<AuthSchemeProvider> authSchemeRegistry) {
this.authSchemeRegistry = authSchemeRegistry;
return this;
}
/**
* Assigns default {@link org.apache.http.cookie.CookieSpec} registry which will
* be used for request execution if not explicitly set in the client execution
* context.
*/
public final HttpClientBuilder setDefaultCookieSpecRegistry(
final Lookup<CookieSpecProvider> cookieSpecRegistry) {
this.cookieSpecRegistry = cookieSpecRegistry;
return this;
}
/**
* Assigns default {@link RequestConfig} instance which will be used
* for request execution if not explicitly set in the client execution
* context.
*/
public final HttpClientBuilder setDefaultRequestConfig(final RequestConfig config) {
this.defaultRequestConfig = config;
return this;
}
/**
* Use system properties when creating and configuring default
* implementations.
*/
public final HttpClientBuilder useSystemProperties() {
systemProperties = true;
return this;
}
/**
* For internal use.
*/
protected ClientExecChain decorateMainExec(final ClientExecChain mainExec) {
return mainExec;
}
/**
* For internal use.
*/
protected ClientExecChain decorateProtocolExec(final ClientExecChain protocolExec) {
return protocolExec;
}
/**
* For internal use.
*/
protected void addCloseable(final Closeable closeable) {
if (closeable == null) {
return;
}
if (closeables == null) {
closeables = new ArrayList<Closeable>();
}
closeables.add(closeable);
}
private static String[] split(final String s) {
if (TextUtils.isBlank(s)) {
return null;
}
return s.split(" *, *");
}
public CloseableHttpClient build() {
// Create main request executor
HttpRequestExecutor requestExec = this.requestExec;
if (requestExec == null) {
requestExec = new HttpRequestExecutor();
}
HttpClientConnectionManager connManager = this.connManager;
if (connManager == null) {
LayeredConnectionSocketFactory sslSocketFactory = this.sslSocketFactory;
if (sslSocketFactory == null) {
final String[] supportedProtocols = systemProperties ? split(
System.getProperty("https.protocols")) : null;
final String[] supportedCipherSuites = systemProperties ? split(
System.getProperty("https.cipherSuites")) : null;
X509HostnameVerifier hostnameVerifier = this.hostnameVerifier;
if (hostnameVerifier == null) {
hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
}
if (sslcontext != null) {
sslSocketFactory = new SSLConnectionSocketFactory(
sslcontext, supportedProtocols, supportedCipherSuites, hostnameVerifier);
} else {
if (systemProperties) {
if (systemProperties) {
sslSocketFactory = new SSLConnectionSocketFactory(
(SSLSocketFactory) SSLCertificateSocketFactory.getDefault(0),
supportedProtocols, supportedCipherSuites, hostnameVerifier);
} else {
sslSocketFactory = new SSLConnectionSocketFactory(
(SSLSocketFactory) SSLCertificateSocketFactory.getDefault(0),
hostnameVerifier);
}
}
}
}
@SuppressWarnings("resource")
final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build());
if (defaultSocketConfig != null) {
poolingmgr.setDefaultSocketConfig(defaultSocketConfig);
}
if (defaultConnectionConfig != null) {
poolingmgr.setDefaultConnectionConfig(defaultConnectionConfig);
}
if (systemProperties) {
String s = System.getProperty("http.keepAlive", "true");
if ("true".equalsIgnoreCase(s)) {
s = System.getProperty("http.maxConnections", "5");
final int max = Integer.parseInt(s);
poolingmgr.setDefaultMaxPerRoute(max);
poolingmgr.setMaxTotal(2 * max);
}
}
if (maxConnTotal > 0) {
poolingmgr.setMaxTotal(maxConnTotal);
}
if (maxConnPerRoute > 0) {
poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute);
}
connManager = poolingmgr;
}
ConnectionReuseStrategy reuseStrategy = this.reuseStrategy;
if (reuseStrategy == null) {
if (systemProperties) {
final String s = System.getProperty("http.keepAlive", "true");
if ("true".equalsIgnoreCase(s)) {
reuseStrategy = DefaultConnectionReuseStrategyHC4.INSTANCE;
} else {
reuseStrategy = NoConnectionReuseStrategyHC4.INSTANCE;
}
} else {
reuseStrategy = DefaultConnectionReuseStrategyHC4.INSTANCE;
}
}
ConnectionKeepAliveStrategy keepAliveStrategy = this.keepAliveStrategy;
if (keepAliveStrategy == null) {
keepAliveStrategy = DefaultConnectionKeepAliveStrategyHC4.INSTANCE;
}
AuthenticationStrategy targetAuthStrategy = this.targetAuthStrategy;
if (targetAuthStrategy == null) {
targetAuthStrategy = TargetAuthenticationStrategy.INSTANCE;
}
AuthenticationStrategy proxyAuthStrategy = this.proxyAuthStrategy;
if (proxyAuthStrategy == null) {
proxyAuthStrategy = ProxyAuthenticationStrategy.INSTANCE;
}
UserTokenHandler userTokenHandler = this.userTokenHandler;
if (userTokenHandler == null) {
if (!connectionStateDisabled) {
userTokenHandler = DefaultUserTokenHandlerHC4.INSTANCE;
} else {
userTokenHandler = NoopUserTokenHandler.INSTANCE;
}
}
ClientExecChain execChain = new MainClientExec(
requestExec,
connManager,
reuseStrategy,
keepAliveStrategy,
targetAuthStrategy,
proxyAuthStrategy,
userTokenHandler);
execChain = decorateMainExec(execChain);
HttpProcessor httpprocessor = this.httpprocessor;
if (httpprocessor == null) {
String userAgent = this.userAgent;
if (userAgent == null) {
if (systemProperties) {
userAgent = System.getProperty("http.agent");
}
if (userAgent == null) {
userAgent = DEFAULT_USER_AGENT;
}
}
final HttpProcessorBuilder b = HttpProcessorBuilder.create();
if (requestFirst != null) {
for (final HttpRequestInterceptor i: requestFirst) {
b.addFirst(i);
}
}
if (responseFirst != null) {
for (final HttpResponseInterceptor i: responseFirst) {
b.addFirst(i);
}
}
b.addAll(
new RequestDefaultHeadersHC4(defaultHeaders),
new RequestContentHC4(),
new RequestTargetHostHC4(),
new RequestClientConnControl(),
new RequestUserAgentHC4(userAgent),
new RequestExpectContinue());
if (!cookieManagementDisabled) {
b.add(new RequestAddCookiesHC4());
}
if (!contentCompressionDisabled) {
b.add(new RequestAcceptEncoding());
}
if (!authCachingDisabled) {
b.add(new RequestAuthCache());
}
if (!cookieManagementDisabled) {
b.add(new ResponseProcessCookiesHC4());
}
if (!contentCompressionDisabled) {
b.add(new ResponseContentEncoding());
}
if (requestLast != null) {
for (final HttpRequestInterceptor i: requestLast) {
b.addLast(i);
}
}
if (responseLast != null) {
for (final HttpResponseInterceptor i: responseLast) {
b.addLast(i);
}
}
httpprocessor = b.build();
}
execChain = new ProtocolExec(execChain, httpprocessor);
execChain = decorateProtocolExec(execChain);
// Add request retry executor, if not disabled
if (!automaticRetriesDisabled) {
HttpRequestRetryHandler retryHandler = this.retryHandler;
if (retryHandler == null) {
retryHandler = DefaultHttpRequestRetryHandlerHC4.INSTANCE;
}
execChain = new RetryExec(execChain, retryHandler);
}
HttpRoutePlanner routePlanner = this.routePlanner;
if (routePlanner == null) {
SchemePortResolver schemePortResolver = this.schemePortResolver;
if (schemePortResolver == null) {
schemePortResolver = DefaultSchemePortResolver.INSTANCE;
}
if (proxy != null) {
routePlanner = new DefaultProxyRoutePlanner(proxy, schemePortResolver);
} else if (systemProperties) {
routePlanner = new SystemDefaultRoutePlanner(
schemePortResolver, ProxySelector.getDefault());
} else {
routePlanner = new DefaultRoutePlanner(schemePortResolver);
}
}
// Add redirect executor, if not disabled
if (!redirectHandlingDisabled) {
RedirectStrategy redirectStrategy = this.redirectStrategy;
if (redirectStrategy == null) {
redirectStrategy = DefaultRedirectStrategy.INSTANCE;
}
execChain = new RedirectExec(execChain, routePlanner, redirectStrategy);
}
// Optionally, add service unavailable retry executor
final ServiceUnavailableRetryStrategy serviceUnavailStrategy = this.serviceUnavailStrategy;
if (serviceUnavailStrategy != null) {
execChain = new ServiceUnavailableRetryExec(execChain, serviceUnavailStrategy);
}
// Optionally, add connection back-off executor
final BackoffManager backoffManager = this.backoffManager;
final ConnectionBackoffStrategy connectionBackoffStrategy = this.connectionBackoffStrategy;
if (backoffManager != null && connectionBackoffStrategy != null) {
execChain = new BackoffStrategyExec(execChain, connectionBackoffStrategy, backoffManager);
}
Lookup<AuthSchemeProvider> authSchemeRegistry = this.authSchemeRegistry;
if (authSchemeRegistry == null) {
authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactoryHC4())
.register(AuthSchemes.DIGEST, new DigestSchemeFactoryHC4())
.register(AuthSchemes.NTLM, new NTLMSchemeFactory())
.build();
}
Lookup<CookieSpecProvider> cookieSpecRegistry = this.cookieSpecRegistry;
if (cookieSpecRegistry == null) {
cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactoryHC4())
.register(CookieSpecs.STANDARD, new RFC2965SpecFactoryHC4())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactoryHC4())
.register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecFactoryHC4())
.register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecFactory())
.register("rfc2109", new RFC2109SpecFactoryHC4())
.register("rfc2965", new RFC2965SpecFactoryHC4())
.build();
}
CookieStore defaultCookieStore = this.cookieStore;
if (defaultCookieStore == null) {
defaultCookieStore = new BasicCookieStoreHC4();
}
CredentialsProvider defaultCredentialsProvider = this.credentialsProvider;
if (defaultCredentialsProvider == null) {
if (systemProperties) {
defaultCredentialsProvider = new SystemDefaultCredentialsProvider();
} else {
defaultCredentialsProvider = new BasicCredentialsProviderHC4();
}
}
return new InternalHttpClient(
execChain,
connManager,
routePlanner,
cookieSpecRegistry,
authSchemeRegistry,
defaultCookieStore,
defaultCredentialsProvider,
defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT,
closeables != null ? new ArrayList<Closeable>(closeables) : null);
}
}
|
|
package ij.plugin;
import ij.*;
import ij.macro.Interpreter;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.measure.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
import ij.plugin.filter.*;
/** This plugin, which concatenates two or more images or stacks,
* implements the Image/Stacks/Tools/Concatenate command.
* Gives the option of viewing the concatenated stack as a 4D image.
* @author Jon Jackson j.jackson # ucl.ac.uk
* last modified June 29 2006
*/
public class Concatenator implements PlugIn, ItemListener{
public String pluginName = "Concatenator";
static boolean all_option = false;
boolean keep = false;
static boolean keep_option = false;
boolean batch = false;
boolean macro = false;
boolean im4D = true;
static boolean im4D_option = false;
public int maxEntries = 18; // limit number of entries to fit on screen
String[] imageTitles;
ImagePlus[] images;
Vector choices;
Checkbox allWindows;
final String none = "-- None --";
String newtitle = "Concatenated Stacks";
ImagePlus newImp;
int stackSize;
double min = 0, max = Float.MAX_VALUE;
/** Optional string argument sets the name dialog boxes if called from another plugin
*/
public void run(String arg) {
macro = ! arg.equals("");
if (!showDialog()) return;
ImagePlus imp0 = images!=null&&images.length>0?images[0]:null;
if (imp0.isComposite() || imp0.isHyperStack())
newImp =concatenateHyperstacks(images, newtitle, keep);
else
newImp = createHypervol();
if (newImp!=null)
newImp.show();
}
// Launch a dialog requiring user to choose images
// returns ImagePlus of concatenated images
public ImagePlus run() {
if (!showDialog()) return null;
newImp = createHypervol();
return newImp;
}
// concatenate two images
public ImagePlus concatenate(ImagePlus imp1, ImagePlus imp2, boolean keep) {
images = new ImagePlus[2];
images[0] = imp1;
images[1] = imp2;
return concatenate(images, keep);
}
// concatenate more than two images
public ImagePlus concatenate(ImagePlus[] ims, boolean keepIms) {
images = ims;
imageTitles = new String[ims.length];
for (int i = 0; i < ims.length; i++) {
if (ims[i] != null) {
imageTitles[i] = ims[i].getTitle();
} else {
IJ.error(pluginName, "Null ImagePlus passed to concatenate(...) method");
return null;
}
}
keep = keepIms;
batch = true;
newImp = createHypervol();
return newImp;
}
ImagePlus createHypervol() {
boolean firstImage = true;
boolean duplicated;
Properties[] propertyArr = new Properties[images.length];
ImagePlus currentImp = null;
ImageStack concat_Stack = null;
stackSize = 0;
int dataType = 0, width= 0, height = 0;
Calibration cal = null;
int count = 0;
for (int i = 0; i < images.length; i++) {
if (images[i] != null) { // Should only find null imp if user has closed an image after starting plugin (unlikely...)
currentImp = images[i];
if (firstImage) { // Initialise based on first image
//concat_Imp = images[i];
cal = currentImp.getCalibration();
width = currentImp.getWidth();
height = currentImp.getHeight();
stackSize = currentImp.getNSlices();
dataType = currentImp.getType();
concat_Stack = currentImp.createEmptyStack();
min = currentImp.getProcessor().getMin();
max = currentImp.getProcessor().getMax();
firstImage = false;
}
// Safety Checks
if (currentImp.getNSlices() != stackSize && im4D) {
IJ.error(pluginName, "Cannot create 4D image because stack sizes are not equal.");
return null;
}
if (currentImp.getType() != dataType) {
IJ.log("Omitting " + imageTitles[i] + " - image type not matched");
continue;
}
if (currentImp.getWidth() != width || currentImp.getHeight() != height) {
IJ.log("Omitting " + imageTitles[i] + " - dimensions not matched");
continue;
}
// concatenate
duplicated = isDuplicated(currentImp, i);
concat(concat_Stack, currentImp.getStack(), (keep || duplicated));
propertyArr[count] = currentImp.getProperties();
imageTitles[count] = currentImp.getTitle();
if (! (keep || duplicated)) {
currentImp.changes = false;
currentImp.hide();
}
count++;
}
}
// Copy across info fields
ImagePlus imp = new ImagePlus(newtitle, concat_Stack);
imp.setCalibration(cal);
imp.setProperty("Number of Stacks", new Integer(count));
imp.setProperty("Stacks Properties", propertyArr);
imp.setProperty("Image Titles", imageTitles);
imp.getProcessor().setMinAndMax(min, max);
if (im4D) {
imp.setDimensions(1, stackSize, imp.getStackSize()/stackSize);
imp.setOpenAsHyperStack(true);
}
return imp;
}
// taken from WSR's Concatenator_.java
void concat(ImageStack stack3, ImageStack stack1, boolean dup) {
int slice = 1;
int size = stack1.getSize();
for (int i = 1; i <= size; i++) {
ImageProcessor ip = stack1.getProcessor(slice);
String label = stack1.getSliceLabel(slice);
if (dup) {
ip = ip.duplicate();
slice++;
} else
stack1.deleteSlice(slice);
stack3.addSlice(label, ip);
}
}
public ImagePlus concatenateHyperstacks(ImagePlus[] images, String newTitle, boolean keep) {
int n = images.length;
int width = images[0].getWidth();
int height = images[0].getHeight();
int bitDepth = images[0].getBitDepth();
int channels = images[0].getNChannels();
int slices = images[0].getNSlices();
int frames = images[0].getNFrames();
boolean concatSlices = slices>1 && frames==1;
for (int i=1; i<n; i++) {
if (images[i].getNFrames()>1) concatSlices = false;
if (images[i].getWidth()!=width
|| images[i].getHeight()!=height
|| images[i].getBitDepth()!=bitDepth
|| images[i].getNChannels()!=channels
|| (!concatSlices && images[i].getNSlices()!=slices)) {
IJ.error(pluginName, "Images do not all have the same dimensions or type");
return null;
}
}
ImageStack stack2 = new ImageStack(width, height);
int slices2=0, frames2=0;
for (int i=0;i<n;i++) {
ImageStack stack = images[i].getStack();
slices = images[i].getNSlices();
if (concatSlices) {
slices = images[i].getNSlices();
slices2 += slices;
frames2 = frames;
} else {
frames = images[i].getNFrames();
frames2 += frames;
slices2 = slices;
}
for (int f=1; f<=frames; f++) {
for (int s=1; s<=slices; s++) {
for (int c=1; c<=channels; c++) {
int index = (f-1)*channels*slices + (s-1)*channels + c;
ImageProcessor ip = stack.getProcessor(index);
if (keep)
ip = ip.duplicate();
String label = stack.getSliceLabel(index);
stack2.addSlice(label, ip);
}
}
}
}
ImagePlus imp2 = new ImagePlus(newTitle, stack2);
imp2.setDimensions(channels, slices2, frames2);
if (channels>1) {
int mode = 0;
if (images[0].isComposite())
mode = ((CompositeImage)images[0]).getMode();
imp2 = new CompositeImage(imp2, mode);
((CompositeImage)imp2).copyLuts(images[0]);
}
if (channels>1 && frames2>1)
imp2.setOpenAsHyperStack(true);
if (!keep) {
for (int i=0; i<n; i++) {
images[i].changes = false;
images[i].close();
}
}
return imp2;
}
boolean showDialog() {
boolean all_windows = false;
batch = Interpreter.isBatchMode();
macro = macro || (IJ.isMacro()&&Macro.getOptions()!=null);
im4D = Menus.commandInUse("Stack to Image5D") && ! batch;
if (macro) {
String options = Macro.getOptions();
if (options.contains("stack1")&&options.contains("stack2"))
Macro.setOptions(options.replaceAll("stack", "image"));
int macroImageCount = 0;
options = Macro.getOptions();
while (true) {
if (options.contains("image"+(macroImageCount+1)))
macroImageCount++;
else
break;
}
maxEntries = macroImageCount;
}
// Checks
int[] wList = WindowManager.getIDList();
if (wList==null) {
IJ.error("No windows are open.");
return false;
} else if (wList.length < 2) {
IJ.error("Two or more windows must be open");
return false;
}
int nImages = wList.length;
String[] titles = new String[nImages];
String[] titles_none = new String[nImages + 1];
for (int i=0; i<nImages; i++) {
ImagePlus imp = WindowManager.getImage(wList[i]);
if (imp!=null) {
titles[i] = imp.getTitle();
titles_none[i] = imp.getTitle();
} else {
titles[i] = "";
titles_none[i] = "";
}
}
titles_none[nImages] = none;
GenericDialog gd = new GenericDialog(pluginName);
gd.addCheckbox("All_open windows", all_option);
gd.addChoice("Image1:", titles, titles[0]);
gd.addChoice("Image2:", titles, titles[1]);
for (int i = 2; i < ((nImages+1)<maxEntries?(nImages+1):maxEntries); i++)
gd.addChoice("Image" + (i+1)+":", titles_none, titles_none[i]);
gd.addStringField("Title:", newtitle, 16);
gd.addCheckbox("Keep original images", keep_option);
gd.addCheckbox("Open as 4D_image", im4D_option);
if (!macro) { // Monitor user selections
choices = gd.getChoices();
for (Enumeration e = choices.elements() ; e.hasMoreElements() ;)
((Choice)e.nextElement()).addItemListener(this);
Vector v = gd.getCheckboxes();
allWindows = (Checkbox)v.firstElement();
allWindows.addItemListener(this);
if (all_option) itemStateChanged(new ItemEvent(allWindows, ItemEvent.ITEM_STATE_CHANGED, null, ItemEvent.SELECTED));
}
gd.showDialog();
if (gd.wasCanceled())
return false;
all_windows = gd.getNextBoolean();
all_option = all_windows;
newtitle = gd.getNextString();
keep = gd.getNextBoolean();
keep_option = keep;
im4D = gd.getNextBoolean();
im4D_option = im4D;
ImagePlus[] tmpImpArr = new ImagePlus[nImages+1];
String[] tmpStrArr = new String[nImages+1];
int index, count = 0;
for (int i=0; i<(nImages+1); i++) { // compile a list of images to concatenate from user selection
if (all_windows) { // Useful to not have to specify images in batch mode
index = i;
} else {
if (i == ((nImages+1)<maxEntries?(nImages+1):maxEntries) ) break;
index = gd.getNextChoiceIndex();
}
if (index >= nImages) break; // reached the 'none' string or handled all images (in case of all_windows)
if (! titles[index].equals("")) {
tmpStrArr[count] = titles[index];
tmpImpArr[count] = WindowManager.getImage(wList[index]);
count++;
}
}
if (count<2) {
IJ.error(pluginName, "Please select at least 2 images");
return false;
}
imageTitles = new String[count];
images = new ImagePlus[count];
System.arraycopy(tmpStrArr, 0, imageTitles, 0, count);
System.arraycopy(tmpImpArr, 0, images, 0, count);
return true;
}
// test if this imageplus appears again in the list
boolean isDuplicated(ImagePlus imp, int index) {
int length = images.length;
if (index >= length - 1) return false;
for (int i = index + 1; i < length; i++) {
if (imp == images[i]) return true;
}
return false;
}
public void itemStateChanged(ItemEvent ie) {
Choice c;
if (ie.getSource() == allWindows) { // User selected / unselected 'all windows' button
int count = 0;
if (allWindows.getState()) {
for (Enumeration e = choices.elements() ; e.hasMoreElements() ;) {
c = (Choice)e.nextElement();
c.select(count++);
c.setEnabled(false);
}
} else {
for (Enumeration e = choices.elements() ; e.hasMoreElements() ;) {
c = (Choice)e.nextElement();
c.setEnabled(true);
}
}
} else { // User image selection triggered event
boolean foundNone = false;
// All image choices after an occurance of 'none' are reset to 'none'
for (Enumeration e = choices.elements() ; e.hasMoreElements() ;) {
c = (Choice)e.nextElement();
if (! foundNone) {
c.setEnabled(true);
if (c.getSelectedItem().equals(none)) foundNone = true;
} else { // a previous choice was 'none'
c.select(none);
c.setEnabled(false);
}
}
}
}
public void setIm5D(boolean bool) {
im4D_option = bool;
}
}
|
|
/*
* 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 junit.framework.*;
import org.apache.ignite.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.processors.cache.query.*;
import org.apache.ignite.internal.util.lang.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.testframework.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static org.apache.ignite.cache.CacheMode.*;
/**
* Cache set tests.
*/
public abstract class GridCacheSetAbstractSelfTest extends IgniteCollectionAbstractTest {
/** */
protected static final String SET_NAME = "testSet";
/** {@inheritDoc} */
@Override protected int gridCount() {
return 4;
}
/** {@inheritDoc} */
@Override protected CollectionConfiguration collectionConfiguration() {
CollectionConfiguration colCfg = super.collectionConfiguration();
if (colCfg.getCacheMode() == PARTITIONED)
colCfg.setBackups(1);
return colCfg;
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
IgniteSet<Object> set = grid(0).set(SET_NAME, null);
if (set != null)
set.close();
waitSetResourcesCleared();
assertNull(grid(0).set(SET_NAME, null));
super.afterTest();
}
/**
* Waits when internal set maps are cleared.
*
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("ErrorNotRethrown")
private void waitSetResourcesCleared() throws IgniteCheckedException {
final int MAX_CHECK = 5;
for (int i = 0; i < MAX_CHECK; i++) {
try {
assertSetResourcesCleared();
return;
}
catch (AssertionFailedError e) {
if (i == MAX_CHECK - 1)
throw e;
log.info("Set resources not cleared, will wait more.");
U.sleep(1000);
}
}
}
/**
* Checks internal set maps are cleared.
*/
private void assertSetResourcesCleared() {
assertSetIteratorsCleared();
for (int i = 0; i < gridCount(); i++) {
IgniteKernal grid = (IgniteKernal)grid(i);
for (IgniteCache cache : grid.caches()) {
CacheDataStructuresManager dsMgr = grid.internalCache(cache.getName()).context().dataStructures();
Map map = GridTestUtils.getFieldValue(dsMgr, "setsMap");
assertEquals("Set not removed [grid=" + i + ", map=" + map + ']', 0, map.size());
map = GridTestUtils.getFieldValue(dsMgr, "setDataMap");
assertEquals("Set data not removed [grid=" + i + ", cache=" + cache.getName() + ", map=" + map + ']',
0,
map.size());
}
}
}
/**
* Checks internal iterators maps are cleared.
*/
private void assertSetIteratorsCleared() {
for (int i = 0; i < gridCount(); i++) {
IgniteKernal grid = (IgniteKernal) grid(i);
for (IgniteCache cache : grid.caches()) {
GridCacheQueryManager queries = grid.internalCache(cache.getName()).context().queries();
Map map = GridTestUtils.getFieldValue(queries, GridCacheQueryManager.class, "qryIters");
for (Object obj : map.values())
assertEquals("Iterators not removed for grid " + i, 0, ((Map) obj).size());
}
}
}
/** {@inheritDoc} */
@Override protected long getTestTimeout() {
return 2 * 60 * 1000;
}
/**
* @throws Exception If failed.
*/
public void testCreateRemove() throws Exception {
testCreateRemove(false);
}
/**
* @throws Exception If failed.
*/
public void testCreateRemoveCollocated() throws Exception {
testCreateRemove(true);
}
/**
* @param collocated Collocation flag.
* @throws Exception If failed.
*/
private void testCreateRemove(boolean collocated) throws Exception {
for (int i = 0; i < gridCount(); i++)
assertNull(grid(i).set(SET_NAME, null));
CollectionConfiguration colCfg0 = config(collocated);
IgniteSet<Integer> set0 = grid(0).set(SET_NAME, colCfg0);
assertNotNull(set0);
for (int i = 0; i < gridCount(); i++) {
CollectionConfiguration colCfg = config(collocated);
IgniteSet<Integer> set = grid(i).set(SET_NAME, colCfg);
assertNotNull(set);
assertTrue(set.isEmpty());
assertEquals(0, set.size());
assertEquals(SET_NAME, set.name());
if (collectionCacheMode() == PARTITIONED)
assertEquals(collocated, set.collocated());
}
set0.close();
GridTestUtils.waitForCondition(new GridAbsPredicate() {
@Override public boolean apply() {
try {
for (int i = 0; i < gridCount(); i++) {
if (grid(i).set(SET_NAME, null) != null)
return false;
}
return true;
}
catch (Exception e) {
fail("Unexpected exception: " + e);
return true;
}
}
}, 1000);
for (int i = 0; i < gridCount(); i++)
assertNull(grid(i).set(SET_NAME, null));
}
/**
* @throws Exception If failed.
*/
public void testApi() throws Exception {
testApi(false);
}
/**
* @throws Exception If failed.
*/
public void testApiCollocated() throws Exception {
testApi(true);
}
/**
* @param collocated Collocation flag.
* @throws Exception If failed.
*/
private void testApi(boolean collocated) throws Exception {
CollectionConfiguration colCfg = config(collocated);
assertNotNull(grid(0).set(SET_NAME, colCfg));
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertNotNull(set);
assertFalse(set.contains(1));
assertEquals(0, set.size());
assertTrue(set.isEmpty());
}
// Add, isEmpty.
assertTrue(grid(0).set(SET_NAME, null).add(1));
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertEquals(1, set.size());
assertFalse(set.isEmpty());
assertTrue(set.contains(1));
assertFalse(set.add(1));
assertFalse(set.contains(100));
}
// Remove.
assertTrue(grid(0).set(SET_NAME, null).remove(1));
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertEquals(0, set.size());
assertTrue(set.isEmpty());
assertFalse(set.contains(1));
assertFalse(set.remove(1));
}
// Contains all.
Collection<Integer> col1 = new ArrayList<>();
Collection<Integer> col2 = new ArrayList<>();
final int ITEMS = 100;
for (int i = 0; i < ITEMS; i++) {
assertTrue(grid(i % gridCount()).set(SET_NAME, null).add(i));
col1.add(i);
col2.add(i);
}
col2.add(ITEMS);
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertEquals(ITEMS, set.size());
assertTrue(set.containsAll(col1));
assertFalse(set.containsAll(col2));
}
// To array.
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertArrayContent(set.toArray(), ITEMS);
assertArrayContent(set.toArray(new Integer[ITEMS]), ITEMS);
}
// Remove all.
Collection<Integer> rmvCol = new ArrayList<>();
for (int i = ITEMS - 10; i < ITEMS; i++)
rmvCol.add(i);
assertTrue(grid(0).set(SET_NAME, null).removeAll(rmvCol));
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertFalse(set.removeAll(rmvCol));
for (Integer val : rmvCol)
assertFalse(set.contains(val));
assertArrayContent(set.toArray(), ITEMS - 10);
assertArrayContent(set.toArray(new Integer[ITEMS - 10]), ITEMS - 10);
}
// Add all.
assertTrue(grid(0).set(SET_NAME, null).addAll(rmvCol));
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertEquals(ITEMS, set.size());
assertFalse(set.addAll(rmvCol));
for (Integer val : rmvCol)
assertTrue(set.contains(val));
}
// Retain all.
assertTrue(grid(0).set(SET_NAME, null).retainAll(rmvCol));
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertEquals(rmvCol.size(), set.size());
assertFalse(set.retainAll(rmvCol));
for (int val = 0; val < 10; val++)
assertFalse(set.contains(val));
for (int val : rmvCol)
assertTrue(set.contains(val));
}
// Clear.
grid(0).set(SET_NAME, null).clear();
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertEquals(0, set.size());
assertTrue(set.isEmpty());
assertFalse(set.contains(0));
}
}
/**
* @throws Exception If failed.
*/
public void testIterator() throws Exception {
testIterator(false);
}
/**
* @throws Exception If failed.
*/
public void testIteratorCollocated() throws Exception {
testIterator(true);
}
/**
* @param collocated Collocation flag.
* @throws Exception If failed.
*/
@SuppressWarnings("deprecation")
private void testIterator(boolean collocated) throws Exception {
CollectionConfiguration colCfg = config(collocated);
final IgniteSet<Integer> set0 = grid(0).set(SET_NAME, colCfg);
for (int i = 0; i < gridCount(); i++) {
IgniteSet<Integer> set = grid(i).set(SET_NAME, null);
assertFalse(set.iterator().hasNext());
}
int cnt = 0;
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
for (int j = 0; j < 100; j++)
assertTrue(set.add(cnt++));
}
for (int i = 0; i < gridCount(); i++) {
IgniteSet<Integer> set = grid(i).set(SET_NAME, null);
assertSetContent(set, cnt);
}
// Try to do not use hasNext.
Collection<Integer> data = new HashSet<>(cnt);
Iterator<Integer> iter = set0.iterator();
for (int i = 0; i < cnt; i++)
assertTrue(data.add(iter.next()));
assertFalse(iter.hasNext());
assertEquals(cnt, data.size());
for (int i = 0; i < cnt; i++)
assertTrue(data.contains(i));
// Iterator for empty set.
set0.clear();
for (int i = 0; i < gridCount(); i++) {
IgniteSet<Integer> set = grid(i).set(SET_NAME, null);
assertFalse(set.iterator().hasNext());
}
// Iterator.remove().
for (int i = 0; i < 10; i++)
assertTrue(set0.add(i));
iter = set0.iterator();
while (iter.hasNext()) {
Integer val = iter.next();
if (val % 2 == 0)
iter.remove();
}
for (int i = 0; i < gridCount(); i++) {
Set<Integer> set = grid(i).set(SET_NAME, null);
assertEquals(i % 2 != 0, set.contains(i));
}
}
/**
* @throws Exception If failed.
*/
public void testIteratorClose() throws Exception {
testIteratorClose(false);
}
/**
* @throws Exception If failed.
*/
public void testIteratorCloseCollocated() throws Exception {
testIteratorClose(true);
}
/**
* @param collocated Collocation flag.
* @throws Exception If failed.
*/
@SuppressWarnings({"BusyWait", "ErrorNotRethrown"})
private void testIteratorClose(boolean collocated) throws Exception {
CollectionConfiguration colCfg = config(collocated);
IgniteSet<Integer> set0 = grid(0).set(SET_NAME, colCfg);
for (int i = 0; i < 5000; i++)
assertTrue(set0.add(i));
createIterators(set0);
System.gc();
for (int i = 0; i < 10; i++) {
try {
set0.size(); // Trigger weak queue poll.
assertSetIteratorsCleared();
}
catch (AssertionFailedError e) {
if (i == 9)
throw e;
log.info("Set iterators not cleared, will wait");
Thread.sleep(500);
}
}
// Check iterators are closed on set remove.
createIterators(set0);
int idx = gridCount() > 1 ? 1 : 0;
grid(idx).set(SET_NAME, null).close();
for (int i = 0; i < 10; i++) {
try {
assertSetIteratorsCleared();
}
catch (AssertionFailedError e) {
if (i == 9)
throw e;
log.info("Set iterators not cleared, will wait");
Thread.sleep(500);
}
}
}
/**
* @param set Set.
*/
private void createIterators(IgniteSet<Integer> set) {
for (int i = 0; i < 10; i++) {
Iterator<Integer> iter = set.iterator();
assertTrue(iter.hasNext());
iter.next();
assertTrue(iter.hasNext());
}
}
/**
* @throws Exception If failed.
*/
public void testNodeJoinsAndLeaves() throws Exception {
if (collectionCacheMode() == LOCAL)
return;
fail("https://issues.apache.org/jira/browse/IGNITE-584");
testNodeJoinsAndLeaves(false);
}
/**
* @throws Exception If failed.
*/
public void testNodeJoinsAndLeavesCollocated() throws Exception {
if (collectionCacheMode() == LOCAL)
return;
fail("https://issues.apache.org/jira/browse/IGNITE-584");
testNodeJoinsAndLeaves(true);
}
/**
* @param collocated Collocation flag.
* @throws Exception If failed.
*/
private void testNodeJoinsAndLeaves(boolean collocated) throws Exception {
CollectionConfiguration colCfg = config(collocated);
Set<Integer> set0 = grid(0).set(SET_NAME, colCfg);
final int ITEMS = 10_000;
for (int i = 0; i < ITEMS; i++)
set0.add(i);
startGrid(gridCount());
try {
IgniteSet<Integer> set1 = grid(0).set(SET_NAME, null);
assertNotNull(set1);
for (int i = 0; i < gridCount() + 1; i++) {
IgniteSet<Integer> set = grid(i).set(SET_NAME, null);
assertEquals(ITEMS, set.size());
assertSetContent(set, ITEMS);
}
}
finally {
stopGrid(gridCount());
}
for (int i = 0; i < gridCount(); i++) {
IgniteSet<Integer> set = grid(i).set(SET_NAME, null);
assertSetContent(set, ITEMS);
}
}
/**
* @throws Exception If failed.
*/
public void testMultithreaded() throws Exception {
testMultithreaded(false);
}
/**
* @throws Exception If failed.
*/
public void testMultithreadedCollocated() throws Exception {
if (collectionCacheMode() != PARTITIONED)
return;
testMultithreaded(true);
}
/**
* @param collocated Collocation flag.
* @throws Exception If failed.
*/
private void testMultithreaded(final boolean collocated) throws Exception {
CollectionConfiguration colCfg = config(collocated);
Set<Integer> set0 = grid(0).set(SET_NAME, colCfg);
assertNotNull(set0);
Collection<IgniteInternalFuture> futs = new ArrayList<>();
final int THREADS_PER_NODE = 5;
final int KEY_RANGE = 10_000;
final int ITERATIONS = 3000;
for (int i = 0; i < gridCount(); i++) {
final int idx = i;
futs.add(GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {
@Override public Void call() throws Exception {
IgniteSet<Integer> set = grid(idx).set(SET_NAME, null);
assertNotNull(set);
ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int i = 0; i < ITERATIONS; i++) {
switch (rnd.nextInt(4)) {
case 0:
set.add(rnd.nextInt(KEY_RANGE));
break;
case 1:
set.remove(rnd.nextInt(KEY_RANGE));
break;
case 2:
set.contains(rnd.nextInt(KEY_RANGE));
break;
case 3:
for (Integer val : set)
assertNotNull(val);
break;
default:
fail();
}
if ((i + 1) % 500 == 0)
log.info("Executed iterations: " + (i + 1));
}
return null;
}
}, THREADS_PER_NODE, "testSetMultithreaded"));
}
for (IgniteInternalFuture fut : futs)
fut.get();
}
/**
* @throws Exception If failed.
*/
public void testCleanup() throws Exception {
testCleanup(false);
}
/**
* @throws Exception If failed.
*/
public void testCleanupCollocated() throws Exception {
testCleanup(true);
}
/**
* @param collocated Collocation flag.
* @throws Exception If failed.
*/
@SuppressWarnings("WhileLoopReplaceableByForEach")
private void testCleanup(boolean collocated) throws Exception {
CollectionConfiguration colCfg = config(collocated);
final IgniteSet<Integer> set0 = grid(0).set(SET_NAME, colCfg);
assertNotNull(set0);
final Collection<Set<Integer>> sets = new ArrayList<>();
for (int i = 0; i < gridCount(); i++) {
IgniteSet<Integer> set = grid(i).set(SET_NAME, null);
assertNotNull(set);
sets.add(set);
}
Collection<Integer> items = new ArrayList<>(10_000);
for (int i = 0; i < 10_000; i++)
items.add(i);
set0.addAll(items);
assertEquals(10_000, set0.size());
final AtomicBoolean stop = new AtomicBoolean();
final AtomicInteger val = new AtomicInteger(10_000);
IgniteInternalFuture<?> fut;
try {
fut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
try {
while (!stop.get()) {
for (Set<Integer> set : sets)
set.add(val.incrementAndGet());
}
}
catch (IllegalStateException e) {
log.info("Set removed: " + e);
}
return null;
}
}, 5, "set-add-thread");
set0.close();
}
finally {
stop.set(true);
}
fut.get();
int cnt = 0;
GridCacheContext cctx = GridTestUtils.getFieldValue(set0, "cctx");
for (int i = 0; i < gridCount(); i++) {
Iterator<GridCacheEntryEx> entries =
(grid(i)).context().cache().internalCache(cctx.name()).map().allEntries0().iterator();
while (entries.hasNext()) {
GridCacheEntryEx entry = entries.next();
if (entry.hasValue()) {
cnt++;
log.info("Unexpected entry: " + entry);
}
}
}
assertEquals("Found unexpected cache entries", 0, cnt);
for (final Set<Integer> set : sets) {
GridTestUtils.assertThrows(log, new Callable<Void>() {
@Override public Void call() throws Exception {
set.add(10);
return null;
}
}, IllegalStateException.class, null);
}
}
/**
* @throws Exception If failed.
*/
public void testSerialization() throws Exception {
final IgniteSet<Integer> set = grid(0).set(SET_NAME, config(false));
assertNotNull(set);
for (int i = 0; i < 10; i++)
set.add(i);
Collection<Integer> c = grid(0).compute().broadcast(new IgniteCallable<Integer>() {
@Override public Integer call() throws Exception {
assertEquals(SET_NAME, set.name());
return set.size();
}
});
assertEquals(gridCount(), c.size());
for (Integer size : c)
assertEquals((Integer)10, size);
}
/**
* @param set Set.
* @param size Expected size.
*/
private void assertSetContent(IgniteSet<Integer> set, int size) {
Collection<Integer> data = new HashSet<>(size);
for (Integer val : set)
assertTrue(data.add(val));
assertEquals(size, data.size());
for (int val = 0; val < size; val++)
assertTrue(data.contains(val));
}
/**
* @param arr Array.
* @param size Expected size.
*/
private void assertArrayContent(Object[] arr, int size) {
assertEquals(size, arr.length);
for (int i = 0; i < size; i++) {
boolean found = false;
for (Object obj : arr) {
if (obj.equals(i)) {
found = true;
break;
}
}
assertTrue(found);
}
}
}
|
|
package com.flipkart.vitess.jdbc.test;
import com.flipkart.vitess.jdbc.VitessResultSet;
import com.google.protobuf.ByteString;
import com.youtube.vitess.client.cursor.Cursor;
import com.youtube.vitess.client.cursor.SimpleCursor;
import com.youtube.vitess.proto.Query;
import org.junit.Assert;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
/**
* Created by harshit.gangal on 19/01/16.
*/
public class VitessResultSetTest {
public Cursor getCursorWithRows() {
/*
INT8(1, 257), -50
UINT8(2, 770), 50
INT16(3, 259), -23000
UINT16(4, 772), 23000
INT24(5, 261), -100
UINT24(6, 774), 100
INT32(7, 263), -100
UINT32(8, 776), 100
INT64(9, 265), -1000
UINT64(10, 778), 1000
FLOAT32(11, 1035), 24.53
FLOAT64(12, 1036), 100.43
TIMESTAMP(13, 2061), 2016-02-06 14:15:16
DATE(14, 2062), 2016-02-06
TIME(15, 2063), 12:34:56
DATETIME(16, 2064), 2016-02-06 14:15:16
YEAR(17, 785), 2016
DECIMAL(18, 18), 1234.56789
TEXT(19, 6163), HELLO TDS TEAM
BLOB(20, 10260), HELLO TDS TEAM
VARCHAR(21, 6165), HELLO TDS TEAM
VARBINARY(22, 10262), HELLO TDS TEAM
CHAR(23, 6167), N
BINARY(24, 10264), HELLO TDS TEAM
BIT(25, 2073), 1
ENUM(26, 2074), val123
SET(27, 2075), val123
TUPLE(28, 28),
UNRECOGNIZED(-1, -1);
*/
return new SimpleCursor(Query.QueryResult.newBuilder()
.addFields(Query.Field.newBuilder().setName("col1").setType(Query.Type.INT8).build())
.addFields(Query.Field.newBuilder().setName("col2").setType(Query.Type.UINT8).build())
.addFields(Query.Field.newBuilder().setName("col3").setType(Query.Type.INT16).build())
.addFields(Query.Field.newBuilder().setName("col4").setType(Query.Type.UINT16).build())
.addFields(Query.Field.newBuilder().setName("col5").setType(Query.Type.INT24).build())
.addFields(Query.Field.newBuilder().setName("col6").setType(Query.Type.UINT24).build())
.addFields(Query.Field.newBuilder().setName("col7").setType(Query.Type.INT32).build())
.addFields(Query.Field.newBuilder().setName("col8").setType(Query.Type.UINT32).build())
.addFields(Query.Field.newBuilder().setName("col9").setType(Query.Type.INT64).build())
.addFields(Query.Field.newBuilder().setName("col10").setType(Query.Type.UINT64).build())
.addFields(
Query.Field.newBuilder().setName("col11").setType(Query.Type.FLOAT32).build())
.addFields(
Query.Field.newBuilder().setName("col12").setType(Query.Type.FLOAT64).build())
.addFields(
Query.Field.newBuilder().setName("col13").setType(Query.Type.TIMESTAMP).build())
.addFields(Query.Field.newBuilder().setName("col14").setType(Query.Type.DATE).build())
.addFields(Query.Field.newBuilder().setName("col15").setType(Query.Type.TIME).build())
.addFields(
Query.Field.newBuilder().setName("col16").setType(Query.Type.DATETIME).build())
.addFields(Query.Field.newBuilder().setName("col17").setType(Query.Type.YEAR).build())
.addFields(
Query.Field.newBuilder().setName("col18").setType(Query.Type.DECIMAL).build())
.addFields(Query.Field.newBuilder().setName("col19").setType(Query.Type.TEXT).build())
.addFields(Query.Field.newBuilder().setName("col20").setType(Query.Type.BLOB).build())
.addFields(
Query.Field.newBuilder().setName("col21").setType(Query.Type.VARCHAR).build())
.addFields(
Query.Field.newBuilder().setName("col22").setType(Query.Type.VARBINARY).build())
.addFields(Query.Field.newBuilder().setName("col23").setType(Query.Type.CHAR).build())
.addFields(Query.Field.newBuilder().setName("col24").setType(Query.Type.BINARY).build())
.addFields(Query.Field.newBuilder().setName("col25").setType(Query.Type.BIT).build())
.addFields(Query.Field.newBuilder().setName("col26").setType(Query.Type.ENUM).build())
.addFields(Query.Field.newBuilder().setName("col27").setType(Query.Type.SET).build())
.addRows(Query.Row.newBuilder().addLengths("-50".length()).addLengths("50".length())
.addLengths("-23000".length()).addLengths("23000".length())
.addLengths("-100".length()).addLengths("100".length()).addLengths("-100".length())
.addLengths("100".length()).addLengths("-1000".length()).addLengths("1000".length())
.addLengths("24.52".length()).addLengths("100.43".length())
.addLengths("2016-02-06 14:15:16".length()).addLengths("2016-02-06".length())
.addLengths("12:34:56".length()).addLengths("2016-02-06 14:15:16".length())
.addLengths("2016".length()).addLengths("1234.56789".length())
.addLengths("HELLO TDS TEAM".length()).addLengths("HELLO TDS TEAM".length())
.addLengths("HELLO TDS TEAM".length()).addLengths("HELLO TDS TEAM".length())
.addLengths("N".length()).addLengths("HELLO TDS TEAM".length())
.addLengths("1".length()).addLengths("val123".length())
.addLengths("val123".length()).setValues(ByteString
.copyFromUtf8("-5050-2300023000-100100-100100-1000100024.52100.432016-02-06 " +
"14:15:162016-02-0612:34:562016-02-06 14:15:1620161234.56789HELLO TDS TEAMHELLO TDS TEAMHELLO"
+
" TDS TEAMHELLO TDS TEAMNHELLO TDS TEAM1val123val123"))).build());
}
public Cursor getCursorWithRowsAsNull() {
/*
INT8(1, 257), -50
UINT8(2, 770), 50
INT16(3, 259), -23000
UINT16(4, 772), 23000
INT24(5, 261), -100
UINT24(6, 774), 100
INT32(7, 263), -100
UINT32(8, 776), 100
INT64(9, 265), -1000
UINT64(10, 778), 1000
FLOAT32(11, 1035), 24.53
FLOAT64(12, 1036), 100.43
TIMESTAMP(13, 2061), 2016-02-06 14:15:16
DATE(14, 2062), 2016-02-06
TIME(15, 2063), 12:34:56
DATETIME(16, 2064), 2016-02-06 14:15:16
YEAR(17, 785), 2016
DECIMAL(18, 18), 1234.56789
TEXT(19, 6163), HELLO TDS TEAM
BLOB(20, 10260), HELLO TDS TEAM
VARCHAR(21, 6165), HELLO TDS TEAM
VARBINARY(22, 10262), HELLO TDS TEAM
CHAR(23, 6167), N
BINARY(24, 10264), HELLO TDS TEAM
BIT(25, 2073), 0
ENUM(26, 2074), val123
SET(27, 2075), val123
TUPLE(28, 28),
UNRECOGNIZED(-1, -1);
*/
return new SimpleCursor(Query.QueryResult.newBuilder()
.addFields(Query.Field.newBuilder().setName("col1").setType(Query.Type.INT8).build())
.addFields(Query.Field.newBuilder().setName("col2").setType(Query.Type.UINT8).build())
.addFields(Query.Field.newBuilder().setName("col3").setType(Query.Type.INT16).build())
.addFields(Query.Field.newBuilder().setName("col4").setType(Query.Type.UINT16).build())
.addFields(Query.Field.newBuilder().setName("col5").setType(Query.Type.INT24).build())
.addFields(Query.Field.newBuilder().setName("col6").setType(Query.Type.UINT24).build())
.addFields(Query.Field.newBuilder().setName("col7").setType(Query.Type.INT32).build())
.addFields(Query.Field.newBuilder().setName("col8").setType(Query.Type.UINT32).build())
.addFields(Query.Field.newBuilder().setName("col9").setType(Query.Type.INT64).build())
.addFields(Query.Field.newBuilder().setName("col10").setType(Query.Type.UINT64).build())
.addFields(
Query.Field.newBuilder().setName("col11").setType(Query.Type.FLOAT32).build())
.addFields(
Query.Field.newBuilder().setName("col12").setType(Query.Type.FLOAT64).build())
.addFields(
Query.Field.newBuilder().setName("col13").setType(Query.Type.TIMESTAMP).build())
.addFields(Query.Field.newBuilder().setName("col14").setType(Query.Type.DATE).build())
.addFields(Query.Field.newBuilder().setName("col15").setType(Query.Type.TIME).build())
.addFields(
Query.Field.newBuilder().setName("col16").setType(Query.Type.DATETIME).build())
.addFields(Query.Field.newBuilder().setName("col17").setType(Query.Type.YEAR).build())
.addFields(
Query.Field.newBuilder().setName("col18").setType(Query.Type.DECIMAL).build())
.addFields(Query.Field.newBuilder().setName("col19").setType(Query.Type.TEXT).build())
.addFields(Query.Field.newBuilder().setName("col20").setType(Query.Type.BLOB).build())
.addFields(
Query.Field.newBuilder().setName("col21").setType(Query.Type.VARCHAR).build())
.addFields(
Query.Field.newBuilder().setName("col22").setType(Query.Type.VARBINARY).build())
.addFields(Query.Field.newBuilder().setName("col23").setType(Query.Type.CHAR).build())
.addFields(Query.Field.newBuilder().setName("col24").setType(Query.Type.BINARY).build())
.addFields(Query.Field.newBuilder().setName("col25").setType(Query.Type.BIT).build())
.addFields(Query.Field.newBuilder().setName("col26").setType(Query.Type.ENUM).build())
.addFields(Query.Field.newBuilder().setName("col27").setType(Query.Type.SET).build())
.addRows(Query.Row.newBuilder().addLengths("-50".length()).addLengths("50".length())
.addLengths("-23000".length()).addLengths("23000".length())
.addLengths("-100".length()).addLengths("100".length()).addLengths("-100".length())
.addLengths("100".length()).addLengths("-1000".length()).addLengths("1000".length())
.addLengths("24.52".length()).addLengths("100.43".length())
.addLengths("2016-02-06 14:15:16".length()).addLengths("2016-02-06".length())
.addLengths("12:34:56".length()).addLengths("2016-02-06 14:15:16".length())
.addLengths("2016".length()).addLengths("1234.56789".length())
.addLengths("HELLO TDS TEAM".length()).addLengths("HELLO TDS TEAM".length())
.addLengths("HELLO TDS TEAM".length()).addLengths("HELLO TDS TEAM".length())
.addLengths("N".length()).addLengths("HELLO TDS TEAM".length())
.addLengths("0".length()).addLengths("val123".length()).addLengths(-1).setValues(
ByteString.copyFromUtf8(
"-5050-2300023000-100100-100100-1000100024.52100.432016-02-06 " +
"14:15:162016-02-0612:34:562016-02-06 14:15:1620161234.56789HELLO TDS TEAMHELLO TDS "
+
"TEAMHELLO TDS TEAMHELLO TDS TEAMNHELLO TDS TEAM0val123"))).build());
}
@Test public void testNextWithZeroRows() throws Exception {
Cursor cursor = new SimpleCursor(Query.QueryResult.newBuilder()
.addFields(Query.Field.newBuilder().setName("col0").build())
.addFields(Query.Field.newBuilder().setName("col1").build())
.addFields(Query.Field.newBuilder().setName("col2").build()).build());
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
Assert.assertEquals(false, vitessResultSet.next());
}
@Test public void testNextWithNonZeroRows() throws Exception {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
Assert.assertEquals(true, vitessResultSet.next());
Assert.assertEquals(false, vitessResultSet.next());
}
@Test public void testgetString() throws SQLException {
Cursor cursor = getCursorWithRowsAsNull();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals("-50", vitessResultSet.getString(1));
Assert.assertEquals("50", vitessResultSet.getString(2));
Assert.assertEquals("-23000", vitessResultSet.getString(3));
Assert.assertEquals("23000", vitessResultSet.getString(4));
Assert.assertEquals("-100", vitessResultSet.getString(5));
Assert.assertEquals("100", vitessResultSet.getString(6));
Assert.assertEquals("-100", vitessResultSet.getString(7));
Assert.assertEquals("100", vitessResultSet.getString(8));
Assert.assertEquals("-1000", vitessResultSet.getString(9));
Assert.assertEquals("1000", vitessResultSet.getString(10));
Assert.assertEquals("24.52", vitessResultSet.getString(11));
Assert.assertEquals("100.43", vitessResultSet.getString(12));
Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString(13));
Assert.assertEquals("2016-02-06", vitessResultSet.getString(14));
Assert.assertEquals("12:34:56", vitessResultSet.getString(15));
Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString(16));
Assert.assertEquals("2016", vitessResultSet.getString(17));
Assert.assertEquals("1234.56789", vitessResultSet.getString(18));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(19));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(20));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(21));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(22));
Assert.assertEquals("N", vitessResultSet.getString(23));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(24));
Assert.assertEquals("0", vitessResultSet.getString(25));
Assert.assertEquals("val123", vitessResultSet.getString(26));
Assert.assertEquals(null, vitessResultSet.getString(27));
}
@Test public void testgetBoolean() throws SQLException {
Cursor cursor = getCursorWithRows();
Cursor cursorWithRowsAsNull = getCursorWithRowsAsNull();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(true, vitessResultSet.getBoolean(25));
Assert.assertEquals(false, vitessResultSet.getBoolean(1));
vitessResultSet = new VitessResultSet(cursorWithRowsAsNull);
vitessResultSet.next();
Assert.assertEquals(false, vitessResultSet.getBoolean(25));
Assert.assertEquals(false, vitessResultSet.getBoolean(1));
}
@Test public void testgetByte() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(-50, vitessResultSet.getByte(1));
Assert.assertEquals(1, vitessResultSet.getByte(25));
}
@Test public void testgetShort() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(-23000, vitessResultSet.getShort(3));
}
@Test public void testgetInt() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(-100, vitessResultSet.getInt(7));
}
@Test public void testgetLong() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(-1000, vitessResultSet.getInt(9));
}
@Test public void testgetFloat() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(24.52f, vitessResultSet.getFloat(11), 0.001);
}
@Test public void testgetDouble() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(100.43, vitessResultSet.getFloat(12), 0.001);
}
@Test public void testBigDecimal() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(new BigDecimal(BigInteger.valueOf(123456789), 5),
vitessResultSet.getBigDecimal(18));
}
@Test public void testgetBytes() throws SQLException, UnsupportedEncodingException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertArrayEquals("HELLO TDS TEAM".getBytes("UTF-8"), vitessResultSet.getBytes(19));
}
@Test public void testgetDate() throws SQLException, UnsupportedEncodingException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(new java.sql.Date(116, 1, 6), vitessResultSet.getDate(14));
}
@Test public void testgetTime() throws SQLException, UnsupportedEncodingException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(new Time(12, 34, 56), vitessResultSet.getTime(15));
}
@Test public void testgetTimestamp() throws SQLException, UnsupportedEncodingException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(new Timestamp(116, 1, 6, 14, 15, 16, 0),
vitessResultSet.getTimestamp(13));
}
@Test public void testgetStringbyColumnLabel() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals("-50", vitessResultSet.getString("col1"));
Assert.assertEquals("50", vitessResultSet.getString("col2"));
Assert.assertEquals("-23000", vitessResultSet.getString("col3"));
Assert.assertEquals("23000", vitessResultSet.getString("col4"));
Assert.assertEquals("-100", vitessResultSet.getString("col5"));
Assert.assertEquals("100", vitessResultSet.getString("col6"));
Assert.assertEquals("-100", vitessResultSet.getString("col7"));
Assert.assertEquals("100", vitessResultSet.getString("col8"));
Assert.assertEquals("-1000", vitessResultSet.getString("col9"));
Assert.assertEquals("1000", vitessResultSet.getString("col10"));
Assert.assertEquals("24.52", vitessResultSet.getString("col11"));
Assert.assertEquals("100.43", vitessResultSet.getString("col12"));
Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString("col13"));
Assert.assertEquals("2016-02-06", vitessResultSet.getString("col14"));
Assert.assertEquals("12:34:56", vitessResultSet.getString("col15"));
Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString("col16"));
Assert.assertEquals("2016", vitessResultSet.getString("col17"));
Assert.assertEquals("1234.56789", vitessResultSet.getString("col18"));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col19"));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col20"));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col21"));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col22"));
Assert.assertEquals("N", vitessResultSet.getString("col23"));
Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col24"));
Assert.assertEquals("1", vitessResultSet.getString("col25"));
Assert.assertEquals("val123", vitessResultSet.getString("col26"));
Assert.assertEquals("val123", vitessResultSet.getString("col27"));
}
@Test public void testgetBooleanbyColumnLabel() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(true, vitessResultSet.getBoolean("col25"));
Assert.assertEquals(false, vitessResultSet.getBoolean("col1"));
}
@Test public void testgetBytebyColumnLabel() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(-50, vitessResultSet.getByte("col1"));
Assert.assertEquals(1, vitessResultSet.getByte("col25"));
}
@Test public void testgetShortbyColumnLabel() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(-23000, vitessResultSet.getShort("col3"));
}
@Test public void testgetIntbyColumnLabel() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(-100, vitessResultSet.getInt("col7"));
}
@Test public void testgetLongbyColumnLabel() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(-1000, vitessResultSet.getInt("col9"));
}
@Test public void testgetFloatbyColumnLabel() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(24.52f, vitessResultSet.getFloat("col11"), 0.001);
}
@Test public void testgetDoublebyColumnLabel() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(100.43, vitessResultSet.getFloat("col12"), 0.001);
}
@Test public void testBigDecimalbyColumnLabel() throws SQLException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(new BigDecimal(BigInteger.valueOf(123456789), 5),
vitessResultSet.getBigDecimal("col18"));
}
@Test public void testgetBytesbyColumnLabel()
throws SQLException, UnsupportedEncodingException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertArrayEquals("HELLO TDS TEAM".getBytes("UTF-8"),
vitessResultSet.getBytes("col19"));
}
@Test public void testgetDatebyColumnLabel() throws SQLException, UnsupportedEncodingException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(new java.sql.Date(116, 1, 6), vitessResultSet.getDate("col14"));
}
@Test public void testgetTimebyColumnLabel() throws SQLException, UnsupportedEncodingException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(new Time(12, 34, 56), vitessResultSet.getTime("col15"));
}
@Test public void testgetTimestampbyColumnLabel()
throws SQLException, UnsupportedEncodingException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
Assert.assertEquals(new Timestamp(116, 1, 6, 14, 15, 16, 0),
vitessResultSet.getTimestamp("col13"));
}
@Test public void testgetAsciiStream() throws SQLException, UnsupportedEncodingException {
Cursor cursor = getCursorWithRows();
VitessResultSet vitessResultSet = new VitessResultSet(cursor);
vitessResultSet.next();
// Need to implement AssertEquivalant
//Assert.assertEquals((InputStream)(new ByteArrayInputStream("HELLO TDS TEAM".getBytes())), vitessResultSet
// .getAsciiStream(19));
}
}
|
|
/*
* Copyright 2003 - 2013 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.db.databases;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.RowProcessor;
import org.efaps.db.databases.information.TableInformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Database class for the MySQL database.
*
* @author The eFaps Team
* @version $Id$
*/
public class MySQLDatabase
extends AbstractDatabase<MySQLDatabase>
{
/**
* Logging instance used in this class.
*/
private static final Logger LOG = LoggerFactory.getLogger(PostgreSQLDatabase.class);
/**
* Prefix used for tables which simulates sequences.
*
* @see #createSequence(Connection, String, long)
* @see #deleteSequence(Connection, String)
* @see #existsSequence(Connection, String)
* @see #nextSequence(Connection, String)
* @see #setSequence(Connection, String, long)
*/
private static final String PREFIX_SEQUENCE = "seq_";
/**
* Select statement to select all unique keys for current logged in
* MySQL database user.
*
* @see #initTableInfoUniqueKeys(Connection, String, Map)
*/
private static final String SQL_UNIQUE_KEYS = "select "
+ "a.constraint_name as INDEX_NAME, "
+ "a.table_name as TABLE_NAME, "
+ "b.column_name as COLUMN_NAME, "
+ "b.ordinal_position as ORDINAL_POSITION "
+ "from "
+ "information_schema.table_constraints a,"
+ "information_schema.key_column_usage b "
+ "where "
+ "a.constraint_type='UNIQUE' "
+ "and a.table_schema=b.table_schema "
+ "and a.table_name=b.table_name "
+ "and a.constraint_name=b.constraint_name";
/**
* Select statement for all foreign keys for current logged in MySQL
* database user.
*
* @see #initTableInfoForeignKeys(Connection, String, Map)
*/
private static final String SQL_FOREIGN_KEYS = "select "
+ "a.TABLE_NAME as TABLE_NAME, "
+ "a.CONSTRAINT_NAME as FK_NAME, "
+ "b.COLUMN_NAME as FKCOLUMN_NAME, "
+ "'' as DELETE_RULE, "
+ "b.REFERENCED_TABLE_NAME as PKTABLE_NAME, "
+ "b.REFERENCED_COLUMN_NAME as PKCOLUMN_NAME "
+ "from "
+ "information_schema.table_constraints a, "
+ "information_schema.key_column_usage b "
+ "where "
+ "a.constraint_type='FOREIGN KEY' "
+ "and a.CONSTRAINT_SCHEMA=b.CONSTRAINT_SCHEMA "
+ "and a.CONSTRAINT_NAME=b.CONSTRAINT_NAME ";
/**
* Singleton processor instance that handlers share to save memory. Notice
* the default scoping to allow only classes in this package to use this
* instance.
*/
private static final RowProcessor ROWPROCESSOR = new BasicRowProcessor();
/**
* Initializes the mapping between the eFaps column types and the MySQL
* specific column types.
*/
public MySQLDatabase()
{
addMapping(ColumnType.INTEGER, "bigint", "null", "bigint", "integer", "int", "mediumint");
addMapping(ColumnType.DECIMAL, "decimal", "null", "decimal", "dec");
addMapping(ColumnType.REAL, "double", "null", "double", "float");
addMapping(ColumnType.STRING_SHORT, "varchar", "null", "text", "tinytext");
addMapping(ColumnType.STRING_LONG, "varchar", "null", "varchar");
addMapping(ColumnType.DATETIME, "datetime", "null", "datetime", "timestamp");
addMapping(ColumnType.BLOB, "longblob", "null", "longblob", "mediumblob", "blob", "tinyblob",
"varbinary", "binary");
addMapping(ColumnType.CLOB, "longtext", "null", "longtext");
addMapping(ColumnType.BOOLEAN, "boolean", "null", "boolean", "bool", "tinyint", "bit");
}
/**
* {@inheritDoc}
*/
@Override
public boolean isConnected(final Connection _connection)
{
// FIXME must be implemented
return false;
}
/**
* @see org.efaps.db.databases.AbstractDatabase#getCurrentTimeStamp()
* @return "current_timestamp"
*/
@Override
public String getCurrentTimeStamp()
{
return "current_timestamp";
}
/**
* {@inheritDoc}
*/
@Override
public String getTimestampValue(final String _isoDateTime)
{
return "timestamp '" + _isoDateTime + "'";
}
/**
* {@inheritDoc}
*/
@Override
public Object getBooleanValue(final Boolean _value)
{
return _value;
}
/**
* <p>This is the MySQL specific implementation of an all deletion.
* Following order is used to remove all eFaps specific information:
* <ul>
* <li>remove all views of the user</li>
* <li>remove all tables of the user</li>
* <li>remove all sequences of the user</li>
* </ul></p>
* <p>The table are dropped with cascade, so all depending sequences etc.
* are also dropped automatically. </p>
* <p>Attention! If application specific tables, views or constraints are
* defined, this database objects are also removed!</p>
*
* @param _con sql connection
* @throws SQLException on error while executing sql statements
*/
@Override
@SuppressFBWarnings("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE")
public void deleteAll(final Connection _con)
throws SQLException
{
final Statement stmtSel = _con.createStatement();
final Statement stmtExec = _con.createStatement();
try {
if (MySQLDatabase.LOG.isInfoEnabled()) {
MySQLDatabase.LOG.info("Remove all Tables");
}
final DatabaseMetaData metaData = _con.getMetaData();
// delete all views
final ResultSet rsViews = metaData.getTables(null, null, "%", new String[] { "VIEW" });
while (rsViews.next()) {
final String viewName = rsViews.getString("TABLE_NAME");
if (MySQLDatabase.LOG.isDebugEnabled()) {
MySQLDatabase.LOG.debug(" - View '" + viewName + "'");
}
stmtExec.execute("drop view " + viewName);
}
rsViews.close();
// delete all constraints
final ResultSet rsTables = metaData.getTables(null, null, "%", new String[] { "TABLE" });
while (rsTables.next()) {
final String tableName = rsTables.getString("TABLE_NAME");
final ResultSet rsf = _con.getMetaData().getImportedKeys(null, null, tableName);
while (rsf.next()) {
final String fkName = rsf.getString("FK_NAME").toUpperCase();
if (MySQLDatabase.LOG.isDebugEnabled()) {
MySQLDatabase.LOG.debug(" - Foreign Key '" + fkName + "'");
}
stmtExec.execute("alter table " + tableName + " drop foreign key " + fkName);
}
}
// delete all tables
rsTables.beforeFirst();
while (rsTables.next()) {
final String tableName = rsTables.getString("TABLE_NAME");
if (MySQLDatabase.LOG.isDebugEnabled()) {
MySQLDatabase.LOG.debug(" - Table '" + tableName + "'");
}
stmtExec.execute("drop table " + tableName + " cascade");
}
rsTables.close();
} finally {
stmtSel.close();
stmtExec.close();
}
}
/**
* {@inheritDoc}
*/
@Override
public MySQLDatabase deleteView(final Connection _con,
final String _name)
throws SQLException
{
final Statement stmtExec = _con.createStatement();
stmtExec.execute("drop view " + _name);
return this;
}
/**
* For the MySQL database, an eFaps SQL table is created in this steps.
* <ul>
* <li>SQL table itself with column <code>ID</code> and unique key on the
* column is created</li>
* <li>if the table is an auto increment table (parent table is
* <code>null</code>, the column <code>ID</code> is set as auto increment
* column</li>
* <li>if no parent table is defined, the foreign key to the parent table is
* automatically set</li>
* </ul>
*
* @see org.efaps.db.databases.AbstractDatabase#createTable(java.sql.Connection, java.lang.String, java.lang.String)
* @param _con Connection to be used for the SQL statements
* @param _table name for the table
* @return this MySQL DB definition instance
* @throws SQLException if the table could not be created
*/
@Override
public MySQLDatabase createTable(final Connection _con,
final String _table)
throws SQLException
{
final Statement stmt = _con.createStatement();
try {
stmt.executeUpdate(new StringBuilder()
.append("create table `").append(_table).append("` (")
.append("`ID` bigint ")
.append(",").append("constraint `").append(_table).append("_PK_ID` primary key (`ID`)")
.append(") engine InnoDB character set utf8;")
.toString());
} finally {
stmt.close();
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MySQLDatabase defineTableAutoIncrement(final Connection _con,
final String _table)
throws SQLException
{
final Statement stmt = _con.createStatement();
try {
// define for ID column the auto increment value
stmt.execute(new StringBuilder()
.append("alter table `").append(_table)
.append("` modify column `ID` bigint not null auto_increment")
.toString());
} finally {
stmt.close();
}
return this;
}
/**
* Overwrites original method because MySQL supports automatically
* generated keys.
*
* @return always <i>true</i> because generated keys are supported by MySQL
* database
* @see AbstractDatabase#supportsGetGeneratedKeys()
*/
@Override
public boolean supportsGetGeneratedKeys()
{
return true;
}
/**
* Overwrites original method because MySQL supports binary input stream.
*
* @return always <i>true</i> because supported by MySQL database
* @see AbstractDatabase#supportsBinaryInputStream()
*/
@Override
public boolean supportsBinaryInputStream()
{
return true;
}
/**
* Returns a single reversed apostrophe ` used to select tables within
* SQL statements for a MySQL database..
*
* @return always single reversed apostrophe
*/
@Override
public String getTableQuote()
{
return "`";
}
/**
* Returns a single reversed apostrophe ` used to select columns within
* SQL statements for a MySQL database..
*
* @return always single reversed apostrophe
*/
@Override
public String getColumnQuote()
{
return "`";
}
/**
* Creates a table with auto generated keys with table name as
* concatenation of the prefix {@link #PREFIX_SEQUENCE} and the lower case
* of <code>_name</code>. This table "simulates" the sequences (which are
* not supported by MySQL).
*
* @param _con SQL connection
* @param _name name of the sequence
* @param _startValue start value of the sequence number
* @return this instance
* @throws SQLException if SQL table could not be created; defined as auto
* increment table or if the sequence number could not
* be defined
* @see #createTable(Connection, String)
* @see #defineTableAutoIncrement(Connection, String)
* @see #setSequence(Connection, String, long)
* @see #PREFIX_SEQUENCE
*/
@Override
public MySQLDatabase createSequence(final Connection _con,
final String _name,
final long _startValue)
throws SQLException
{
final String name = new StringBuilder()
.append(MySQLDatabase.PREFIX_SEQUENCE).append(_name.toLowerCase())
.toString();
createTable(_con, name);
defineTableAutoIncrement(_con, name);
setSequence(_con, _name, _startValue);
return this;
}
/**
* Deletes given sequence <code>_name</code> which is internally
* represented by this MySQL connector as normal SQL table. The name of the
* SQL table to delete is a concatenation of {@link #PREFIX_SEQUENCE} and
* <code>_name</code> in lower case.
*
* @param _con SQL connection
* @param _name name of the sequence
* @return this instance
* @throws SQLException if sequence (simulated by an auto increment SQL
* table) could not be deleted
* @see #PREFIX_SEQUENCE
*/
@Override
public MySQLDatabase deleteSequence(final Connection _con,
final String _name)
throws SQLException
{
final String cmd = new StringBuilder()
.append("DROP TABLE `").append(MySQLDatabase.PREFIX_SEQUENCE).append(_name.toLowerCase()).append("`")
.toString();
final Statement stmt = _con.createStatement();
try {
stmt.executeUpdate(cmd);
} finally {
stmt.close();
}
return this;
}
/**
* Checks if the related table representing sequence <code>_name</code>
* exists.
*
* @param _con SQL connection
* @param _name name of the sequence
* @return <i>true</i> if a table with name as concatenation of
* {@link #PREFIX_SEQUENCE} and <code>_name</code> (in lower case)
* representing the sequence exists; otherwise <i>false</i>
* @throws SQLException if check for the existence of the table
* representing the sequence failed
* @see #existsTable(Connection, String)
* @see #PREFIX_SEQUENCE
*/
@Override
public boolean existsSequence(final Connection _con,
final String _name)
throws SQLException
{
return existsTable(
_con,
new StringBuilder().append(MySQLDatabase.PREFIX_SEQUENCE).append(_name.toLowerCase()).toString());
}
/**
* Fetches next number for sequence <code>_name</code> by inserting new
* row into representing table. The new auto generated key is returned as
* next number of the sequence.
*
* @param _con SQL connection
* @param _name name of the sequence
* @return current inserted value of the table
* @throws SQLException if next number from the sequence could not be
* fetched
* @see #PREFIX_SEQUENCE
*/
@Override
public long nextSequence(final Connection _con,
final String _name)
throws SQLException
{
final long ret;
final Statement stmt = _con.createStatement();
try {
// insert new line
final String insertCmd = new StringBuilder()
.append("INSERT INTO `").append(MySQLDatabase.PREFIX_SEQUENCE).append(_name.toLowerCase())
.append("` VALUES ()")
.toString();
final int row = stmt.executeUpdate(insertCmd, Statement.RETURN_GENERATED_KEYS);
if (row != 1) {
throw new SQLException("no sequence found for '" + _name + "'");
}
// fetch new number
final ResultSet resultset = stmt.getGeneratedKeys();
if (resultset.next()) {
ret = resultset.getLong(1);
} else {
throw new SQLException("no sequence found for '" + _name + "'");
}
} finally {
stmt.close();
}
return ret;
}
/**
* Defines new <code>_value</code> for sequence <code>_name</code>. Because
* in MySQL the sequences are simulated and the values from fetched
* sequence numbers are not deleted, all existing values in the table are
* first deleted (to be sure that the sequence could be reseted to already
* fetched numbers). After the new starting value is defined a first auto
* generated value is fetched from the database so that this value is also
* stored if the MySQL database is restarted.
*
* @param _con SQL connection
* @param _name name of the sequence
* @param _value new value of the sequence
* @return this instance
* @throws SQLException if new number of the sequence could not be defined
* for the table
* @see #PREFIX_SEQUENCE
*/
@Override
public MySQLDatabase setSequence(final Connection _con,
final String _name,
final long _value)
throws SQLException
{
final String name = _name.toLowerCase();
final String lockCmd = new StringBuilder()
.append("LOCK TABLES `").append(MySQLDatabase.PREFIX_SEQUENCE).append(name)
.append("` WRITE")
.toString();
final String deleteCmd = new StringBuilder()
.append("DELETE FROM `").append(MySQLDatabase.PREFIX_SEQUENCE).append(name).append("`")
.toString();
final String alterCmd = new StringBuilder()
.append("ALTER TABLE `").append(MySQLDatabase.PREFIX_SEQUENCE).append(name)
.append("` AUTO_INCREMENT=").append(_value - 1)
.toString();
final String insertCmd = new StringBuilder()
.append("INSERT INTO `").append(MySQLDatabase.PREFIX_SEQUENCE).append(name)
.append("` VALUES ()")
.toString();
final String unlockCmd = new StringBuilder()
.append("UNLOCK TABLES")
.toString();
final Statement stmt = _con.createStatement();
try {
stmt.executeUpdate(lockCmd);
stmt.executeUpdate(deleteCmd);
stmt.executeUpdate(alterCmd);
stmt.executeUpdate(insertCmd);
stmt.executeUpdate(unlockCmd);
} finally {
stmt.close();
}
return this;
}
/**
* {@inheritDoc}
*/
@Override
public String getHibernateDialect()
{
return "org.hibernate.dialect.MySQL5Dialect";
}
/**
* Overwrites the original method to specify SQL statement
* {@link #SQL_UNIQUE_KEYS} as replacement because the JDBC driver for
* MySQL does not handle matching table names.
*
* @param _con SQL connection
* @param _sql SQL statement (not used)
* @param _cache4Name map used to fetch depending on the table name the
* related table information
* @throws SQLException if unique keys could not be fetched
* @see #SQL_UNIQUE_KEYS
*/
@Override
protected void initTableInfoUniqueKeys(final Connection _con,
final String _sql,
final Map<String, TableInformation> _cache4Name)
throws SQLException
{
super.initTableInfoUniqueKeys(_con, MySQLDatabase.SQL_UNIQUE_KEYS, _cache4Name);
}
/**
* Overwrites the original method to specify SQL statement
* {@link #SQL_FOREIGN_KEYS} as replacement because the JDBC driver for
* MySQL does not handle matching table names.
*
* @param _con SQL connection
* @param _sql SQL statement (not used)
* @param _cache4Name map used to fetch depending on the table name the
* related table information
* @throws SQLException if foreign keys could not be fetched
* @see #SQL_FOREIGN_KEYS
*/
@Override
protected void initTableInfoForeignKeys(final Connection _con,
final String _sql,
final Map<String, TableInformation> _cache4Name)
throws SQLException
{
super.initTableInfoForeignKeys(_con, MySQLDatabase.SQL_FOREIGN_KEYS, _cache4Name);
}
/**
* {@inheritDoc}
*/
@Override
protected StringBuilder getAlterColumn(final String _columnName,
final org.efaps.db.databases.AbstractDatabase.ColumnType _columnType)
{
final StringBuilder ret = new StringBuilder()
.append(" alter ").append(getColumnQuote()).append(_columnName).append(getColumnQuote())
.append(" ")
.append(getWriteSQLTypeName(_columnType));
return ret;
}
/**
* {@inheritDoc}
*/
@Override
protected StringBuilder getAlterColumnIsNotNull(final String _columnName,
final boolean _isNotNull)
{
final StringBuilder ret = new StringBuilder()
.append(" alter column ").append(getColumnQuote()).append(_columnName).append(getColumnQuote());
if (_isNotNull) {
ret.append(" set ");
} else {
ret.append(" drop ");
}
ret.append(" not null");
return ret;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean check4NullValues(final Connection _con,
final String _tableName,
final String _columnName)
throws SQLException
{
boolean ret = true;
final StringBuilder cmd = new StringBuilder();
cmd.append("select count(*) from ").append(getTableQuote()).append(_tableName).append(getTableQuote())
.append(" where ").append(getColumnQuote()).append(_columnName).append(getColumnQuote())
.append(" is null");
MySQLDatabase.LOG.debug(" ..SQL> {}", cmd);
final Statement stmt = _con.createStatement();
ResultSet rs = null;
try {
rs = stmt.executeQuery(cmd.toString());
rs.next();
ret = rs.getInt(1) > 0;
} finally {
if (rs != null) {
rs.close();
}
stmt.close();
}
return ret;
}
/**
* {@inheritDoc}
*/
@Override
public RowProcessor getRowProcessor()
{
return MySQLDatabase.ROWPROCESSOR;
}
}
|
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.translate.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/translate-2017-07-01/TranslateText" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TranslateTextRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The text to translate. The text string can be a maximum of 5,000 bytes long. Depending on your character set,
* this may be fewer than 5,000 characters.
* </p>
*/
private String text;
/**
* <p>
* The TerminologyNames list that is taken as input to the TranslateText request. This has a minimum length of 0 and
* a maximum length of 1.
* </p>
*/
private java.util.List<String> terminologyNames;
/**
* <p>
* The language code for the language of the source text. The language must be a language supported by Amazon
* Translate.
* </p>
* <p>
* To have Amazon Translate determine the source language of your text, you can specify <code>auto</code> in the
* <code>SourceLanguageCode</code> field. If you specify <code>auto</code>, Amazon Translate will call Amazon
* Comprehend to determine the source language.
* </p>
*/
private String sourceLanguageCode;
/**
* <p>
* The language code requested for the language of the target text. The language must be a language supported by
* Amazon Translate.
* </p>
*/
private String targetLanguageCode;
/**
* <p>
* The text to translate. The text string can be a maximum of 5,000 bytes long. Depending on your character set,
* this may be fewer than 5,000 characters.
* </p>
*
* @param text
* The text to translate. The text string can be a maximum of 5,000 bytes long. Depending on your character
* set, this may be fewer than 5,000 characters.
*/
public void setText(String text) {
this.text = text;
}
/**
* <p>
* The text to translate. The text string can be a maximum of 5,000 bytes long. Depending on your character set,
* this may be fewer than 5,000 characters.
* </p>
*
* @return The text to translate. The text string can be a maximum of 5,000 bytes long. Depending on your character
* set, this may be fewer than 5,000 characters.
*/
public String getText() {
return this.text;
}
/**
* <p>
* The text to translate. The text string can be a maximum of 5,000 bytes long. Depending on your character set,
* this may be fewer than 5,000 characters.
* </p>
*
* @param text
* The text to translate. The text string can be a maximum of 5,000 bytes long. Depending on your character
* set, this may be fewer than 5,000 characters.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public TranslateTextRequest withText(String text) {
setText(text);
return this;
}
/**
* <p>
* The TerminologyNames list that is taken as input to the TranslateText request. This has a minimum length of 0 and
* a maximum length of 1.
* </p>
*
* @return The TerminologyNames list that is taken as input to the TranslateText request. This has a minimum length
* of 0 and a maximum length of 1.
*/
public java.util.List<String> getTerminologyNames() {
return terminologyNames;
}
/**
* <p>
* The TerminologyNames list that is taken as input to the TranslateText request. This has a minimum length of 0 and
* a maximum length of 1.
* </p>
*
* @param terminologyNames
* The TerminologyNames list that is taken as input to the TranslateText request. This has a minimum length
* of 0 and a maximum length of 1.
*/
public void setTerminologyNames(java.util.Collection<String> terminologyNames) {
if (terminologyNames == null) {
this.terminologyNames = null;
return;
}
this.terminologyNames = new java.util.ArrayList<String>(terminologyNames);
}
/**
* <p>
* The TerminologyNames list that is taken as input to the TranslateText request. This has a minimum length of 0 and
* a maximum length of 1.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTerminologyNames(java.util.Collection)} or {@link #withTerminologyNames(java.util.Collection)} if you
* want to override the existing values.
* </p>
*
* @param terminologyNames
* The TerminologyNames list that is taken as input to the TranslateText request. This has a minimum length
* of 0 and a maximum length of 1.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public TranslateTextRequest withTerminologyNames(String... terminologyNames) {
if (this.terminologyNames == null) {
setTerminologyNames(new java.util.ArrayList<String>(terminologyNames.length));
}
for (String ele : terminologyNames) {
this.terminologyNames.add(ele);
}
return this;
}
/**
* <p>
* The TerminologyNames list that is taken as input to the TranslateText request. This has a minimum length of 0 and
* a maximum length of 1.
* </p>
*
* @param terminologyNames
* The TerminologyNames list that is taken as input to the TranslateText request. This has a minimum length
* of 0 and a maximum length of 1.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public TranslateTextRequest withTerminologyNames(java.util.Collection<String> terminologyNames) {
setTerminologyNames(terminologyNames);
return this;
}
/**
* <p>
* The language code for the language of the source text. The language must be a language supported by Amazon
* Translate.
* </p>
* <p>
* To have Amazon Translate determine the source language of your text, you can specify <code>auto</code> in the
* <code>SourceLanguageCode</code> field. If you specify <code>auto</code>, Amazon Translate will call Amazon
* Comprehend to determine the source language.
* </p>
*
* @param sourceLanguageCode
* The language code for the language of the source text. The language must be a language supported by Amazon
* Translate. </p>
* <p>
* To have Amazon Translate determine the source language of your text, you can specify <code>auto</code> in
* the <code>SourceLanguageCode</code> field. If you specify <code>auto</code>, Amazon Translate will call
* Amazon Comprehend to determine the source language.
*/
public void setSourceLanguageCode(String sourceLanguageCode) {
this.sourceLanguageCode = sourceLanguageCode;
}
/**
* <p>
* The language code for the language of the source text. The language must be a language supported by Amazon
* Translate.
* </p>
* <p>
* To have Amazon Translate determine the source language of your text, you can specify <code>auto</code> in the
* <code>SourceLanguageCode</code> field. If you specify <code>auto</code>, Amazon Translate will call Amazon
* Comprehend to determine the source language.
* </p>
*
* @return The language code for the language of the source text. The language must be a language supported by
* Amazon Translate. </p>
* <p>
* To have Amazon Translate determine the source language of your text, you can specify <code>auto</code> in
* the <code>SourceLanguageCode</code> field. If you specify <code>auto</code>, Amazon Translate will call
* Amazon Comprehend to determine the source language.
*/
public String getSourceLanguageCode() {
return this.sourceLanguageCode;
}
/**
* <p>
* The language code for the language of the source text. The language must be a language supported by Amazon
* Translate.
* </p>
* <p>
* To have Amazon Translate determine the source language of your text, you can specify <code>auto</code> in the
* <code>SourceLanguageCode</code> field. If you specify <code>auto</code>, Amazon Translate will call Amazon
* Comprehend to determine the source language.
* </p>
*
* @param sourceLanguageCode
* The language code for the language of the source text. The language must be a language supported by Amazon
* Translate. </p>
* <p>
* To have Amazon Translate determine the source language of your text, you can specify <code>auto</code> in
* the <code>SourceLanguageCode</code> field. If you specify <code>auto</code>, Amazon Translate will call
* Amazon Comprehend to determine the source language.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public TranslateTextRequest withSourceLanguageCode(String sourceLanguageCode) {
setSourceLanguageCode(sourceLanguageCode);
return this;
}
/**
* <p>
* The language code requested for the language of the target text. The language must be a language supported by
* Amazon Translate.
* </p>
*
* @param targetLanguageCode
* The language code requested for the language of the target text. The language must be a language supported
* by Amazon Translate.
*/
public void setTargetLanguageCode(String targetLanguageCode) {
this.targetLanguageCode = targetLanguageCode;
}
/**
* <p>
* The language code requested for the language of the target text. The language must be a language supported by
* Amazon Translate.
* </p>
*
* @return The language code requested for the language of the target text. The language must be a language
* supported by Amazon Translate.
*/
public String getTargetLanguageCode() {
return this.targetLanguageCode;
}
/**
* <p>
* The language code requested for the language of the target text. The language must be a language supported by
* Amazon Translate.
* </p>
*
* @param targetLanguageCode
* The language code requested for the language of the target text. The language must be a language supported
* by Amazon Translate.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public TranslateTextRequest withTargetLanguageCode(String targetLanguageCode) {
setTargetLanguageCode(targetLanguageCode);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getText() != null)
sb.append("Text: ").append(getText()).append(",");
if (getTerminologyNames() != null)
sb.append("TerminologyNames: ").append(getTerminologyNames()).append(",");
if (getSourceLanguageCode() != null)
sb.append("SourceLanguageCode: ").append(getSourceLanguageCode()).append(",");
if (getTargetLanguageCode() != null)
sb.append("TargetLanguageCode: ").append(getTargetLanguageCode());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof TranslateTextRequest == false)
return false;
TranslateTextRequest other = (TranslateTextRequest) obj;
if (other.getText() == null ^ this.getText() == null)
return false;
if (other.getText() != null && other.getText().equals(this.getText()) == false)
return false;
if (other.getTerminologyNames() == null ^ this.getTerminologyNames() == null)
return false;
if (other.getTerminologyNames() != null && other.getTerminologyNames().equals(this.getTerminologyNames()) == false)
return false;
if (other.getSourceLanguageCode() == null ^ this.getSourceLanguageCode() == null)
return false;
if (other.getSourceLanguageCode() != null && other.getSourceLanguageCode().equals(this.getSourceLanguageCode()) == false)
return false;
if (other.getTargetLanguageCode() == null ^ this.getTargetLanguageCode() == null)
return false;
if (other.getTargetLanguageCode() != null && other.getTargetLanguageCode().equals(this.getTargetLanguageCode()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getText() == null) ? 0 : getText().hashCode());
hashCode = prime * hashCode + ((getTerminologyNames() == null) ? 0 : getTerminologyNames().hashCode());
hashCode = prime * hashCode + ((getSourceLanguageCode() == null) ? 0 : getSourceLanguageCode().hashCode());
hashCode = prime * hashCode + ((getTargetLanguageCode() == null) ? 0 : getTargetLanguageCode().hashCode());
return hashCode;
}
@Override
public TranslateTextRequest clone() {
return (TranslateTextRequest) super.clone();
}
}
|
|
package com.hh.adapters;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.hh.clientdatatable.ClientDataTable;
import com.hh.clientdatatable.TCell;
import com.hh.droid.R;
import com.hh.execption.WrongTypeException;
import com.hh.listeners.*;
import com.hh.ui.widget.UiPicassoImageView;
/**
* Created by Wajdi Hh on 13/08/2015.
* [email protected]
*/
public class CDTRecycleAdapter extends RecyclerView.Adapter<RecycleViewHolder> {
protected Context mContext;
protected Resources mRes;
protected ClientDataTable mClientDataTable;
private boolean _mIsEnableOnClickWidget;
private int _mLayoutRes;
private int mBase64OptionSize=2;
private boolean mIsNotUsePicassoCache=false;
public void setPicassoCachePolicy(boolean isDisableCache){
mIsNotUsePicassoCache=isDisableCache;
}
public void setBase64OptionSize(int optionSize){
mBase64OptionSize=optionSize;
}
public CDTRecycleAdapter(Context pContext, int pLayoutRes, ClientDataTable pCDT){
mContext=pContext;
mRes=pContext.getResources();
mClientDataTable = pCDT;
_mLayoutRes = pLayoutRes;
setHasStableIds(true);
}
@Override
protected void finalize() throws Throwable {
mContext = null;
super.finalize();
}
@Override
public RecycleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(_mLayoutRes, parent,false);
onCreateRow(v);
return new RecycleViewHolder(mContext,v,mClientDataTable,_mIsEnableOnClickWidget);
}
public int getLayoutRes(){
return _mLayoutRes;
}
public void setEnableOnClickWidget(boolean pIsEnabled) {
_mIsEnableOnClickWidget = pIsEnabled;
}
@Override
public void onBindViewHolder(RecycleViewHolder holder, int position) {
if(mClientDataTable.isEmpty())
return;
mClientDataTable.moveToPosition(position);
if ((position >= getItemCount() - 1))
onLoadMore();
int lListHolderSize = holder.mSparseArrayHolderViews.size();
for (int i = 0; i < lListHolderSize; i++) {
int lColumnIndex = holder.mSparseArrayHolderViews.keyAt(i);
View lWidget = holder.mSparseArrayHolderViews.get(lColumnIndex);
if (lWidget != null) {
final TCell data = mClientDataTable.getCell(position, lColumnIndex);
if (lWidget instanceof Checkable) {
((Checkable) lWidget).setChecked(data.asBoolean());
} else if (lWidget instanceof TextView) {
((TextView) lWidget).setText(data.asString());
}else if (lWidget instanceof UiPicassoImageView) {
if(data.getValueType() == TCell.ValueType.BASE64){
try {
throw new WrongTypeException(mContext, R.string.exception_canotUserBase64);
} catch (WrongTypeException e) {
e.printStackTrace();
}
}else {
UiPicassoImageView picassoImageView = (UiPicassoImageView) lWidget;
picassoImageView.setData(data.asString(),mIsNotUsePicassoCache);
}
} else if (lWidget instanceof ImageView) {
ImageView im= (ImageView) lWidget;
if (data.getValueType() == TCell.ValueType.INTEGER && !data.asString().isEmpty()) {
im.setImageResource(data.asInteger());
} else if (data.getValueType() == TCell.ValueType.BASE64) {
byte[] decodedString = Base64.decode(data.asString(), Base64.NO_WRAP);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = mBase64OptionSize;
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
im.setImageBitmap(decodedByte);
} else {
if (!data.asString().equals(""))
setViewImage((ImageView) lWidget, data.asString());
else
im.setImageDrawable(null);
}
} else if (lWidget instanceof Spinner) {
Spinner spinner=((Spinner) lWidget);
if(spinner.getAdapter() instanceof ArrayAdapter){
ArrayAdapter arrayAdapter= (ArrayAdapter) spinner.getAdapter();
spinner.setSelection(arrayAdapter.getPosition(data.asString()));
}else
Log.e(this.getClass().getName(), "Cannot set Spinner default value, because Spinner Adapter is not ArrayAdapter Type, you need to customize it in onIterateWidget method");
}
onIteratedRow(holder.mRowView,lWidget, lWidget.getTag().toString());
}
}
int lListHolderSizeNotInCDT = holder.mSparseArrayHolderViewsNotInCDT.size();
for (int i = 0; i < lListHolderSizeNotInCDT; i++) {
int lColumnIndex = holder.mSparseArrayHolderViewsNotInCDT.keyAt(i);
View lWidget = holder.mSparseArrayHolderViewsNotInCDT.get(lColumnIndex);
if (lWidget != null) {
onIteratedRow(holder.mRowView, lWidget, lWidget.getTag().toString());
}
}
// ClickListener
holder.setClickListener(new OnRecycleClickListener() {
@Override
public void onClick(View v, int position) {
onClickRow(v,position);
}
@Override
public void onLongClick(View v, int position) {
onLongClickRow(v, position);
}
});
holder.setOnRecycleWidgetClickListener(new OnRecycleWidgetClickListener() {
@Override
public void onClick(View parentView, View clickedView, String tag, int position) {
onClickWidget(parentView, clickedView, tag, position);
}
});
holder.setOnRecycleCheckedRadioButtonGroupChangeListener(new OnRecycleCheckedRadioButtonGroupChangeListener() {
@Override
public void onCheckedChanged(View parentView, RadioGroup radioButtonGroup, String widgetTag, int radioButtonID, int position) {
onCheckRadioButtonGroupWidget(parentView, radioButtonGroup, widgetTag, radioButtonID, position);
}
});
holder.setOnRecycleCheckedChangeListener(new OnRecycleCheckedChangeListener() {
@Override
public void onCheckedChanged(boolean isWidgetInCDT,CompoundButton buttonView, boolean isChecked, int position) {
onOnCheckedChangeWidget(buttonView,buttonView.getTag().toString(),isChecked,position);
if (!isWidgetInCDT || position >= mClientDataTable.getRowsCount())
return;
String columnName = buttonView.getTag().toString();
mClientDataTable.moveToPosition(position);
mClientDataTable.cellByName(columnName).setValue(isChecked);
}
});
holder.setOnRecycleTextWatcher(new OnRecycleTextWatcher() {
@Override
public void afterTextChanged(boolean isWidgetInCDT,EditText v, String newText, int position) {
if (!isWidgetInCDT || position >= mClientDataTable.getRowsCount() || !(v.isFocusable() || v.isFocusableInTouchMode()))
return;
mClientDataTable.moveToPosition(position);
String columnName = v.getTag().toString();
mClientDataTable.cellByName(columnName).setValue(newText);
}
});
}
public void setViewImage(ImageView v, String value) {
try {
v.setImageResource(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
v.setImageURI(Uri.parse(value));
}
}
@Override
public int getItemCount() {
return mClientDataTable.getRowsCount();
}
@Override
public long getItemId(int position) {
return position;
}
public void clear() {
mClientDataTable.clear();
notifyDataRecycleChanged();
}
public void notifyDataRecycleChanged(){
mClientDataTable.requery();
notifyDataSetChanged();
}
/**
* override this method when we need to access to CDT content
* for each row when iterate all the data
*
* @param widget : Button , TextView etc...
* @param position : position of row
*/
protected void onIteratedRow(View row, View widget,String widgetTag){};
protected void onLoadMore(){};
protected void onCreateRow(View row){} ;
/**
* override this method to capture the click on selected row
*
* @param row
* @param position : position of selected row
*/
protected void onClickRow(View row, int position) {
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
;
/**
* override this method to capture the click on selected widget (Button, ImageView ...) inside a row
*
* @param tagWidget : the tag of the selected widget
* @param position : the position of row of selected widget
*/
protected void onClickWidget(View parentView,View clickedView,String tagWidget, int position) {
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
protected void onCheckRadioButtonGroupWidget(View parentView,RadioGroup radioGroup,String widgetTag,int radioButtonID, int position){
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
protected void onOnCheckedChangeWidget(CompoundButton compoundButton,String tag,boolean b, int position){
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
/**
* override this method to capture the Long click on selected Row,
* and we can create context Menu inside this method
*
* @param row : selected row
* @param position : position of selected row
*/
protected void onLongClickRow(View row, int position) {
if(position>=mClientDataTable.getRowsCount())
return;
mClientDataTable.moveToPosition(position);
}
public boolean isEmpty(){
return getItemCount()==0;
}
public String getString(int resID){
return mRes.getString(resID);
}
}
|
|
/**
*/
package CIM15.IEC61970.StateVariables.util;
import CIM15.Element;
import CIM15.IEC61970.Core.IdentifiedObject;
import CIM15.IEC61970.StateVariables.*;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.util.Switch;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see CIM15.IEC61970.StateVariables.StateVariablesPackage
* @generated
*/
public class StateVariablesSwitch<T> extends Switch<T> {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static StateVariablesPackage modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public StateVariablesSwitch() {
if (modelPackage == null) {
modelPackage = StateVariablesPackage.eINSTANCE;
}
}
/**
* Checks whether this is a switch for the given package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @parameter ePackage the package in question.
* @return whether this is a switch for the given package.
* @generated
*/
@Override
protected boolean isSwitchFor(EPackage ePackage) {
return ePackage == modelPackage;
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
@Override
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case StateVariablesPackage.SV_VOLTAGE: {
SvVoltage svVoltage = (SvVoltage)theEObject;
T result = caseSvVoltage(svVoltage);
if (result == null) result = caseStateVariable(svVoltage);
if (result == null) result = caseElement(svVoltage);
if (result == null) result = defaultCase(theEObject);
return result;
}
case StateVariablesPackage.SV_SHORT_CIRCUIT: {
SvShortCircuit svShortCircuit = (SvShortCircuit)theEObject;
T result = caseSvShortCircuit(svShortCircuit);
if (result == null) result = caseStateVariable(svShortCircuit);
if (result == null) result = caseElement(svShortCircuit);
if (result == null) result = defaultCase(theEObject);
return result;
}
case StateVariablesPackage.SV_SHUNT_COMPENSATOR_SECTIONS: {
SvShuntCompensatorSections svShuntCompensatorSections = (SvShuntCompensatorSections)theEObject;
T result = caseSvShuntCompensatorSections(svShuntCompensatorSections);
if (result == null) result = caseStateVariable(svShuntCompensatorSections);
if (result == null) result = caseElement(svShuntCompensatorSections);
if (result == null) result = defaultCase(theEObject);
return result;
}
case StateVariablesPackage.STATE_VARIABLE: {
StateVariable stateVariable = (StateVariable)theEObject;
T result = caseStateVariable(stateVariable);
if (result == null) result = caseElement(stateVariable);
if (result == null) result = defaultCase(theEObject);
return result;
}
case StateVariablesPackage.SV_TAP_STEP: {
SvTapStep svTapStep = (SvTapStep)theEObject;
T result = caseSvTapStep(svTapStep);
if (result == null) result = caseStateVariable(svTapStep);
if (result == null) result = caseElement(svTapStep);
if (result == null) result = defaultCase(theEObject);
return result;
}
case StateVariablesPackage.SV_STATUS: {
SvStatus svStatus = (SvStatus)theEObject;
T result = caseSvStatus(svStatus);
if (result == null) result = caseStateVariable(svStatus);
if (result == null) result = caseElement(svStatus);
if (result == null) result = defaultCase(theEObject);
return result;
}
case StateVariablesPackage.SV_INJECTION: {
SvInjection svInjection = (SvInjection)theEObject;
T result = caseSvInjection(svInjection);
if (result == null) result = caseStateVariable(svInjection);
if (result == null) result = caseElement(svInjection);
if (result == null) result = defaultCase(theEObject);
return result;
}
case StateVariablesPackage.SV_POWER_FLOW: {
SvPowerFlow svPowerFlow = (SvPowerFlow)theEObject;
T result = caseSvPowerFlow(svPowerFlow);
if (result == null) result = caseStateVariable(svPowerFlow);
if (result == null) result = caseElement(svPowerFlow);
if (result == null) result = defaultCase(theEObject);
return result;
}
case StateVariablesPackage.TOPOLOGICAL_ISLAND: {
TopologicalIsland topologicalIsland = (TopologicalIsland)theEObject;
T result = caseTopologicalIsland(topologicalIsland);
if (result == null) result = caseIdentifiedObject(topologicalIsland);
if (result == null) result = caseElement(topologicalIsland);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Sv Voltage</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Sv Voltage</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSvVoltage(SvVoltage object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Sv Short Circuit</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Sv Short Circuit</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSvShortCircuit(SvShortCircuit object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Sv Shunt Compensator Sections</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Sv Shunt Compensator Sections</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSvShuntCompensatorSections(SvShuntCompensatorSections object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>State Variable</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>State Variable</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseStateVariable(StateVariable object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Sv Tap Step</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Sv Tap Step</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSvTapStep(SvTapStep object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Sv Status</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Sv Status</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSvStatus(SvStatus object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Sv Injection</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Sv Injection</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSvInjection(SvInjection object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Sv Power Flow</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Sv Power Flow</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseSvPowerFlow(SvPowerFlow object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Topological Island</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Topological Island</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseTopologicalIsland(TopologicalIsland object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Element</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Element</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseElement(Element object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Identified Object</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Identified Object</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseIdentifiedObject(IdentifiedObject object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
@Override
public T defaultCase(EObject object) {
return null;
}
} //StateVariablesSwitch
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.binary;
import java.io.File;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.cache.CacheException;
import org.apache.ignite.IgniteBinary;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.binary.BinaryField;
import org.apache.ignite.binary.BinaryObject;
import org.apache.ignite.binary.BinaryObjectBuilder;
import org.apache.ignite.binary.BinaryObjectException;
import org.apache.ignite.binary.BinaryType;
import org.apache.ignite.binary.BinaryTypeConfiguration;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.BinaryConfiguration;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.events.Event;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteNodeAttributes;
import org.apache.ignite.internal.binary.BinaryContext;
import org.apache.ignite.internal.binary.BinaryEnumObjectImpl;
import org.apache.ignite.internal.binary.BinaryFieldMetadata;
import org.apache.ignite.internal.binary.BinaryMarshaller;
import org.apache.ignite.internal.binary.BinaryMetadata;
import org.apache.ignite.internal.binary.BinaryMetadataHandler;
import org.apache.ignite.internal.binary.BinaryObjectEx;
import org.apache.ignite.internal.binary.BinaryObjectImpl;
import org.apache.ignite.internal.binary.BinaryObjectOffheapImpl;
import org.apache.ignite.internal.binary.BinaryTypeImpl;
import org.apache.ignite.internal.binary.BinaryUtils;
import org.apache.ignite.internal.binary.GridBinaryMarshaller;
import org.apache.ignite.internal.binary.builder.BinaryObjectBuilderImpl;
import org.apache.ignite.internal.binary.streams.BinaryInputStream;
import org.apache.ignite.internal.binary.streams.BinaryOffheapInputStream;
import org.apache.ignite.internal.managers.eventstorage.GridLocalEventListener;
import org.apache.ignite.internal.processors.cache.CacheObject;
import org.apache.ignite.internal.processors.cache.CacheObjectContext;
import org.apache.ignite.internal.processors.cache.CacheObjectValueContext;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.GridCacheUtils;
import org.apache.ignite.internal.processors.cache.KeyCacheObject;
import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessorImpl;
import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.IgniteUtils;
import org.apache.ignite.internal.util.MutableSingletonList;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.lang.GridMapEntry;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.T1;
import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.internal.A;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.lang.IgniteClosure;
import org.apache.ignite.lang.IgniteFuture;
import org.apache.ignite.marshaller.Marshaller;
import org.apache.ignite.spi.IgniteNodeValidationResult;
import org.apache.ignite.spi.discovery.DiscoveryDataBag;
import org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData;
import org.apache.ignite.spi.discovery.IgniteDiscoveryThread;
import org.apache.ignite.thread.IgniteThread;
import org.jetbrains.annotations.Nullable;
import org.jsr166.ConcurrentHashMap8;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK;
import static org.apache.ignite.IgniteSystemProperties.getBoolean;
import static org.apache.ignite.events.EventType.EVT_CLIENT_NODE_DISCONNECTED;
import static org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType.BINARY_PROC;
/**
* Binary processor implementation.
*/
public class CacheObjectBinaryProcessorImpl extends IgniteCacheObjectProcessorImpl implements
CacheObjectBinaryProcessor {
/** */
private volatile boolean discoveryStarted;
/** */
private BinaryContext binaryCtx;
/** */
private Marshaller marsh;
/** */
private GridBinaryMarshaller binaryMarsh;
/** */
private BinaryMetadataFileStore metadataFileStore;
/**
* Custom folder specifying local folder for {@link #metadataFileStore}.<br>
* {@code null} means no specific folder is configured. <br>
* In this case folder for metadata is composed from work directory and consistentId <br>
*/
@Nullable private File binaryMetadataFileStoreDir;
/** */
@GridToStringExclude
private IgniteBinary binaries;
/** Listener removes all registered binary schemas and user type descriptors after the local client reconnected. */
private final GridLocalEventListener clientDisconLsnr = new GridLocalEventListener() {
@Override public void onEvent(Event evt) {
binaryContext().unregisterUserTypeDescriptors();
binaryContext().unregisterBinarySchemas();
metadataLocCache.clear();
}
};
/** Locally cached metadata. This local cache is managed by exchanging discovery custom events. */
private final ConcurrentMap<Integer, BinaryMetadataHolder> metadataLocCache = new ConcurrentHashMap8<>();
/** */
private BinaryMetadataTransport transport;
/** Cached affinity key field names. */
private final ConcurrentHashMap<Integer, T1<BinaryField>> affKeyFields = new ConcurrentHashMap<>();
/**
* @param ctx Kernal context.
*/
public CacheObjectBinaryProcessorImpl(GridKernalContext ctx) {
super(ctx);
marsh = ctx.grid().configuration().getMarshaller();
}
/** {@inheritDoc} */
@Override public void start() throws IgniteCheckedException {
if (marsh instanceof BinaryMarshaller) {
if (ctx.clientNode())
ctx.event().addLocalEventListener(clientDisconLsnr, EVT_CLIENT_NODE_DISCONNECTED);
if (!ctx.clientNode())
metadataFileStore = new BinaryMetadataFileStore(metadataLocCache, ctx, log, binaryMetadataFileStoreDir);
transport = new BinaryMetadataTransport(metadataLocCache, metadataFileStore, ctx, log);
BinaryMetadataHandler metaHnd = new BinaryMetadataHandler() {
@Override public void addMeta(int typeId, BinaryType newMeta) throws BinaryObjectException {
assert newMeta != null;
assert newMeta instanceof BinaryTypeImpl;
if (!discoveryStarted) {
BinaryMetadataHolder holder = metadataLocCache.get(typeId);
BinaryMetadata oldMeta = holder != null ? holder.metadata() : null;
BinaryMetadata mergedMeta = BinaryUtils.mergeMetadata(oldMeta, ((BinaryTypeImpl)newMeta).metadata());
if (oldMeta != mergedMeta)
metadataLocCache.put(typeId, new BinaryMetadataHolder(mergedMeta, 0, 0));
return;
}
BinaryMetadata newMeta0 = ((BinaryTypeImpl)newMeta).metadata();
CacheObjectBinaryProcessorImpl.this.addMeta(typeId, newMeta0.wrap(binaryCtx));
}
@Override public BinaryType metadata(int typeId) throws BinaryObjectException {
return CacheObjectBinaryProcessorImpl.this.metadata(typeId);
}
@Override public BinaryMetadata metadata0(int typeId) throws BinaryObjectException {
return CacheObjectBinaryProcessorImpl.this.metadata0(typeId);
}
@Override public BinaryType metadata(int typeId, int schemaId) throws BinaryObjectException {
return CacheObjectBinaryProcessorImpl.this.metadata(typeId, schemaId);
}
};
BinaryMarshaller bMarsh0 = (BinaryMarshaller)marsh;
binaryCtx = new BinaryContext(metaHnd, ctx.config(), ctx.log(BinaryContext.class));
IgniteUtils.invoke(BinaryMarshaller.class, bMarsh0, "setBinaryContext", binaryCtx, ctx.config());
binaryMarsh = new GridBinaryMarshaller(binaryCtx);
binaries = new IgniteBinaryImpl(ctx, this);
if (!getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK)) {
BinaryConfiguration bCfg = ctx.config().getBinaryConfiguration();
if (bCfg != null) {
Map<String, Object> map = new HashMap<>();
map.put("globIdMapper", bCfg.getIdMapper() != null ? bCfg.getIdMapper().getClass().getName() : null);
map.put("globSerializer", bCfg.getSerializer() != null ? bCfg.getSerializer().getClass() : null);
map.put("compactFooter", bCfg.isCompactFooter());
if (bCfg.getTypeConfigurations() != null) {
Map<Object, Object> typeCfgsMap = new HashMap<>();
for (BinaryTypeConfiguration c : bCfg.getTypeConfigurations()) {
typeCfgsMap.put(
c.getTypeName() != null,
Arrays.asList(
c.getIdMapper() != null ? c.getIdMapper().getClass() : null,
c.getSerializer() != null ? c.getSerializer().getClass() : null,
c.isEnum()
)
);
if (c.isEnum())
BinaryUtils.validateEnumValues(c.getTypeName(), c.getEnumValues());
}
map.put("typeCfgs", typeCfgsMap);
}
ctx.addNodeAttribute(IgniteNodeAttributes.ATTR_BINARY_CONFIGURATION, map);
}
}
if (!ctx.clientNode())
metadataFileStore.restoreMetadata();
}
}
/**
* @param lsnr Listener.
*/
public void addBinaryMetadataUpdateListener(BinaryMetadataUpdatedListener lsnr) {
if (transport != null)
transport.addBinaryMetadataUpdateListener(lsnr);
}
/** {@inheritDoc} */
@Override public void stop(boolean cancel) {
if (ctx.clientNode())
ctx.event().removeLocalEventListener(clientDisconLsnr);
if (transport != null)
transport.stop();
}
/** {@inheritDoc} */
@Override public void onDisconnected(IgniteFuture<?> reconnectFut) throws IgniteCheckedException {
if (transport != null)
transport.onDisconnected();
}
/** {@inheritDoc} */
@Override public void onKernalStart(boolean active) throws IgniteCheckedException {
super.onKernalStart(active);
discoveryStarted = true;
}
/** {@inheritDoc} */
@Override public int typeId(String typeName) {
if (binaryCtx == null)
return super.typeId(typeName);
return binaryCtx.typeId(typeName);
}
/**
* @param obj Object.
* @return Bytes.
* @throws BinaryObjectException If failed.
*/
public byte[] marshal(@Nullable Object obj) throws BinaryObjectException {
byte[] arr = binaryMarsh.marshal(obj);
assert arr.length > 0;
return arr;
}
/**
* @param ptr Off-heap pointer.
* @param forceHeap If {@code true} creates heap-based object.
* @return Object.
* @throws BinaryObjectException If failed.
*/
public Object unmarshal(long ptr, boolean forceHeap) throws BinaryObjectException {
assert ptr > 0 : ptr;
int size = GridUnsafe.getInt(ptr);
ptr += 4;
byte type = GridUnsafe.getByte(ptr++);
if (type != CacheObject.TYPE_BYTE_ARR) {
assert size > 0 : size;
BinaryInputStream in = new BinaryOffheapInputStream(ptr, size, forceHeap);
return binaryMarsh.unmarshal(in);
}
else
return U.copyMemory(ptr, size);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public Object marshalToBinary(@Nullable Object obj) throws BinaryObjectException {
if (obj == null)
return null;
if (BinaryUtils.isBinaryType(obj.getClass()))
return obj;
if (obj instanceof Object[]) {
Object[] arr = (Object[])obj;
Object[] pArr = new Object[arr.length];
for (int i = 0; i < arr.length; i++)
pArr[i] = marshalToBinary(arr[i]);
return pArr;
}
if (obj instanceof IgniteBiTuple) {
IgniteBiTuple tup = (IgniteBiTuple)obj;
if (obj instanceof T2)
return new T2<>(marshalToBinary(tup.get1()), marshalToBinary(tup.get2()));
return new IgniteBiTuple<>(marshalToBinary(tup.get1()), marshalToBinary(tup.get2()));
}
{
Collection<Object> pCol = BinaryUtils.newKnownCollection(obj);
if (pCol != null) {
Collection<?> col = (Collection<?>)obj;
for (Object item : col)
pCol.add(marshalToBinary(item));
return (pCol instanceof MutableSingletonList) ? U.convertToSingletonList(pCol) : pCol;
}
}
{
Map<Object, Object> pMap = BinaryUtils.newKnownMap(obj);
if (pMap != null) {
Map<?, ?> map = (Map<?, ?>)obj;
for (Map.Entry<?, ?> e : map.entrySet())
pMap.put(marshalToBinary(e.getKey()), marshalToBinary(e.getValue()));
return pMap;
}
}
if (obj instanceof Map.Entry) {
Map.Entry<?, ?> e = (Map.Entry<?, ?>)obj;
return new GridMapEntry<>(marshalToBinary(e.getKey()), marshalToBinary(e.getValue()));
}
if (binaryMarsh.mustDeserialize(obj))
return obj; // No need to go through marshal-unmarshal because result will be the same as initial object.
byte[] arr = binaryMarsh.marshal(obj);
assert arr.length > 0;
Object obj0 = binaryMarsh.unmarshal(arr, null);
// Possible if a class has writeObject method.
if (obj0 instanceof BinaryObjectImpl)
((BinaryObjectImpl)obj0).detachAllowed(true);
return obj0;
}
/**
* @return Marshaller.
*/
public GridBinaryMarshaller marshaller() {
return binaryMarsh;
}
/** {@inheritDoc} */
@Override public BinaryObjectBuilder builder(String clsName) {
return new BinaryObjectBuilderImpl(binaryCtx, clsName);
}
/** {@inheritDoc} */
@Override public BinaryObjectBuilder builder(BinaryObject binaryObj) {
return BinaryObjectBuilderImpl.wrap(binaryObj);
}
/** {@inheritDoc} */
@Override public void updateMetadata(int typeId, String typeName, @Nullable String affKeyFieldName,
Map<String, BinaryFieldMetadata> fieldTypeIds, boolean isEnum, @Nullable Map<String, Integer> enumMap)
throws BinaryObjectException {
BinaryMetadata meta = new BinaryMetadata(typeId, typeName, fieldTypeIds, affKeyFieldName, null, isEnum,
enumMap);
binaryCtx.updateMetadata(typeId, meta);
}
/** {@inheritDoc} */
@Override public void addMeta(final int typeId, final BinaryType newMeta) throws BinaryObjectException {
assert newMeta != null;
assert newMeta instanceof BinaryTypeImpl;
BinaryMetadata newMeta0 = ((BinaryTypeImpl)newMeta).metadata();
try {
BinaryMetadataHolder metaHolder = metadataLocCache.get(typeId);
BinaryMetadata oldMeta = metaHolder != null ? metaHolder.metadata() : null;
BinaryMetadata mergedMeta = BinaryUtils.mergeMetadata(oldMeta, newMeta0);
MetadataUpdateResult res = transport.requestMetadataUpdate(mergedMeta).get();
assert res != null;
if (res.rejected())
throw res.error();
}
catch (IgniteCheckedException e) {
throw new BinaryObjectException("Failed to update meta data for type: " + newMeta.typeName(), e);
}
}
/** {@inheritDoc} */
@Override public void addMetaLocally(int typeId, BinaryType newMeta) throws BinaryObjectException {
assert newMeta != null;
assert newMeta instanceof BinaryTypeImpl;
BinaryMetadata newMeta0 = ((BinaryTypeImpl)newMeta).metadata();
BinaryMetadataHolder metaHolder = metadataLocCache.get(typeId);
BinaryMetadata oldMeta = metaHolder != null ? metaHolder.metadata() : null;
try {
BinaryMetadata mergedMeta = BinaryUtils.mergeMetadata(oldMeta, newMeta0);
metadataFileStore.mergeAndWriteMetadata(mergedMeta);
metadataLocCache.put(typeId, new BinaryMetadataHolder(mergedMeta, 0, 0));
}
catch (BinaryObjectException e) {
throw new BinaryObjectException("New binary metadata is incompatible with binary metadata" +
" persisted locally." +
" Consider cleaning up persisted metadata from <workDir>/binary_meta directory.", e);
}
}
/** {@inheritDoc} */
@Nullable @Override public BinaryType metadata(final int typeId) {
BinaryMetadata meta = metadata0(typeId);
return meta != null ? meta.wrap(binaryCtx) : null;
}
/**
* @param typeId Type ID.
* @return Meta data.
* @throws IgniteException In case of error.
*/
@Nullable public BinaryMetadata metadata0(final int typeId) {
BinaryMetadataHolder holder = metadataLocCache.get(typeId);
if (holder == null) {
if (ctx.clientNode()) {
try {
transport.requestUpToDateMetadata(typeId).get();
holder = metadataLocCache.get(typeId);
}
catch (IgniteCheckedException ignored) {
// No-op.
}
}
}
if (holder != null) {
if (IgniteThread.current() instanceof IgniteDiscoveryThread)
return holder.metadata();
if (holder.pendingVersion() - holder.acceptedVersion() > 0) {
GridFutureAdapter<MetadataUpdateResult> fut = transport.awaitMetadataUpdate(typeId, holder.pendingVersion());
if (log.isDebugEnabled() && !fut.isDone())
log.debug("Waiting for update for" +
" [typeId=" + typeId +
", pendingVer=" + holder.pendingVersion() +
", acceptedVer=" + holder.acceptedVersion() + "]");
try {
fut.get();
}
catch (IgniteCheckedException ignored) {
// No-op.
}
}
return holder.metadata();
}
else
return null;
}
/** {@inheritDoc} */
@Nullable @Override public BinaryType metadata(final int typeId, final int schemaId) {
BinaryMetadataHolder holder = metadataLocCache.get(typeId);
if (ctx.clientNode()) {
if (holder == null || !holder.metadata().hasSchema(schemaId)) {
try {
transport.requestUpToDateMetadata(typeId).get();
holder = metadataLocCache.get(typeId);
}
catch (IgniteCheckedException ignored) {
// No-op.
}
}
}
else if (holder != null) {
if (IgniteThread.current() instanceof IgniteDiscoveryThread)
return holder.metadata().wrap(binaryCtx);
if (holder.pendingVersion() - holder.acceptedVersion() > 0) {
GridFutureAdapter<MetadataUpdateResult> fut = transport.awaitMetadataUpdate(
typeId,
holder.pendingVersion());
if (log.isDebugEnabled() && !fut.isDone())
log.debug("Waiting for update for" +
" [typeId=" + typeId
+ ", schemaId=" + schemaId
+ ", pendingVer=" + holder.pendingVersion()
+ ", acceptedVer=" + holder.acceptedVersion() + "]");
try {
fut.get();
}
catch (IgniteCheckedException ignored) {
// No-op.
}
holder = metadataLocCache.get(typeId);
}
}
return holder != null ? holder.metadata().wrap(binaryCtx) : null;
}
/** {@inheritDoc} */
@Override public Map<Integer, BinaryType> metadata(Collection<Integer> typeIds)
throws BinaryObjectException {
try {
Map<Integer, BinaryType> res = U.newHashMap(metadataLocCache.size());
for (Map.Entry<Integer, BinaryMetadataHolder> e : metadataLocCache.entrySet())
res.put(e.getKey(), e.getValue().metadata().wrap(binaryCtx));
return res;
}
catch (CacheException e) {
throw new BinaryObjectException(e);
}
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public Collection<BinaryType> metadata() throws BinaryObjectException {
return F.viewReadOnly(metadataLocCache.values(), new IgniteClosure<BinaryMetadataHolder, BinaryType>() {
@Override public BinaryType apply(BinaryMetadataHolder metaHolder) {
return metaHolder.metadata().wrap(binaryCtx);
}
});
}
/** {@inheritDoc} */
@Override public BinaryObject buildEnum(String typeName, int ord) throws BinaryObjectException {
A.notNullOrEmpty(typeName, "enum type name");
int typeId = binaryCtx.typeId(typeName);
typeName = binaryCtx.userTypeName(typeName);
updateMetadata(typeId, typeName, null, null, true, null);
return new BinaryEnumObjectImpl(binaryCtx, typeId, null, ord);
}
/** {@inheritDoc} */
@Override public BinaryObject buildEnum(String typeName, String name) throws BinaryObjectException {
A.notNullOrEmpty(typeName, "enum type name");
A.notNullOrEmpty(name, "enum name");
int typeId = binaryCtx.typeId(typeName);
BinaryMetadata metadata = metadata0(typeId);
if (metadata == null)
throw new BinaryObjectException("Failed to get metadata for type [typeId=" +
typeId + ", typeName='" + typeName + "']");
Integer ordinal = metadata.getEnumOrdinalByName(name);
typeName = binaryCtx.userTypeName(typeName);
if (ordinal == null)
throw new BinaryObjectException("Failed to resolve enum ordinal by name [typeId=" +
typeId + ", typeName='" + typeName + "', name='" + name + "']");
return new BinaryEnumObjectImpl(binaryCtx, typeId, null, ordinal);
}
/** {@inheritDoc} */
@Override public BinaryType registerEnum(String typeName, Map<String, Integer> vals) throws BinaryObjectException {
A.notNullOrEmpty(typeName, "enum type name");
int typeId = binaryCtx.typeId(typeName);
typeName = binaryCtx.userTypeName(typeName);
BinaryUtils.validateEnumValues(typeName, vals);
updateMetadata(typeId, typeName, null, null, true, vals);
return binaryCtx.metadata(typeId);
}
/** {@inheritDoc} */
@Override public IgniteBinary binary() throws IgniteException {
return binaries;
}
/** {@inheritDoc} */
@Override public boolean isBinaryObject(Object obj) {
return obj instanceof BinaryObject;
}
/** {@inheritDoc} */
@Override public boolean isBinaryEnabled(CacheConfiguration<?, ?> ccfg) {
return marsh instanceof BinaryMarshaller;
}
/**
* Get affinity key field.
*
* @param typeId Binary object type ID.
* @return Affinity key.
*/
public BinaryField affinityKeyField(int typeId) {
// Fast path for already cached field.
T1<BinaryField> fieldHolder = affKeyFields.get(typeId);
if (fieldHolder != null)
return fieldHolder.get();
// Slow path if affinity field is not cached yet.
String name = binaryCtx.affinityKeyFieldName(typeId);
if (name != null) {
BinaryField field = binaryCtx.createField(typeId, name);
affKeyFields.putIfAbsent(typeId, new T1<>(field));
return field;
}
else {
affKeyFields.putIfAbsent(typeId, new T1<BinaryField>(null));
return null;
}
}
/** {@inheritDoc} */
@Override public int typeId(Object obj) {
if (obj == null)
return 0;
return isBinaryObject(obj) ? ((BinaryObjectEx)obj).typeId() : typeId(obj.getClass().getSimpleName());
}
/** {@inheritDoc} */
@Override public Object field(Object obj, String fieldName) {
if (obj == null)
return null;
return isBinaryObject(obj) ? ((BinaryObject)obj).field(fieldName) : super.field(obj, fieldName);
}
/** {@inheritDoc} */
@Override public boolean hasField(Object obj, String fieldName) {
return obj != null && ((BinaryObject)obj).hasField(fieldName);
}
/**
* @return Binary context.
*/
public BinaryContext binaryContext() {
return binaryCtx;
}
/** {@inheritDoc} */
@Override public CacheObjectContext contextForCache(CacheConfiguration cfg) throws IgniteCheckedException {
assert cfg != null;
boolean binaryEnabled = marsh instanceof BinaryMarshaller && !GridCacheUtils.isSystemCache(cfg.getName()) &&
!GridCacheUtils.isIgfsCache(ctx.config(), cfg.getName());
CacheObjectContext ctx0 = super.contextForCache(cfg);
CacheObjectContext res = new CacheObjectBinaryContext(ctx,
cfg,
ctx0.copyOnGet(),
ctx0.storeValue(),
binaryEnabled,
ctx0.addDeploymentInfo());
ctx.resource().injectGeneric(res.defaultAffMapper());
return res;
}
/** {@inheritDoc} */
@Override public byte[] marshal(CacheObjectValueContext ctx, Object val) throws IgniteCheckedException {
if (!ctx.binaryEnabled() || binaryMarsh == null)
return super.marshal(ctx, val);
byte[] arr = binaryMarsh.marshal(val);
assert arr.length > 0;
return arr;
}
/** {@inheritDoc} */
@Override public Object unmarshal(CacheObjectValueContext ctx, byte[] bytes, ClassLoader clsLdr)
throws IgniteCheckedException {
if (!ctx.binaryEnabled() || binaryMarsh == null)
return super.unmarshal(ctx, bytes, clsLdr);
return binaryMarsh.unmarshal(bytes, clsLdr);
}
/** {@inheritDoc} */
@Override public KeyCacheObject toCacheKeyObject(CacheObjectContext ctx, @Nullable GridCacheContext cctx,
Object obj, boolean userObj) {
if (!ctx.binaryEnabled())
return super.toCacheKeyObject(ctx, cctx, obj, userObj);
if (obj instanceof KeyCacheObject) {
KeyCacheObject key = (KeyCacheObject)obj;
if (key instanceof BinaryObjectImpl) {
// Need to create a copy because the key can be reused at the application layer after that (IGNITE-3505).
key = key.copy(partition(ctx, cctx, key));
}
else if (key.partition() == -1)
// Assume others KeyCacheObjects can not be reused for another cache.
key.partition(partition(ctx, cctx, key));
return key;
}
obj = toBinary(obj);
if (obj instanceof BinaryObjectImpl) {
((BinaryObjectImpl)obj).partition(partition(ctx, cctx, obj));
return (KeyCacheObject)obj;
}
return toCacheKeyObject0(ctx, cctx, obj, userObj);
}
/** {@inheritDoc} */
@Nullable @Override public CacheObject toCacheObject(CacheObjectContext ctx, @Nullable Object obj,
boolean userObj) {
if (!ctx.binaryEnabled())
return super.toCacheObject(ctx, obj, userObj);
if (obj == null || obj instanceof CacheObject)
return (CacheObject)obj;
obj = toBinary(obj);
if (obj instanceof CacheObject)
return (CacheObject)obj;
return toCacheObject0(obj, userObj);
}
/** {@inheritDoc} */
@Override public CacheObject toCacheObject(CacheObjectContext ctx, byte type, byte[] bytes) {
if (type == BinaryObjectImpl.TYPE_BINARY)
return new BinaryObjectImpl(binaryContext(), bytes, 0);
else if (type == BinaryObjectImpl.TYPE_BINARY_ENUM)
return new BinaryEnumObjectImpl(binaryContext(), bytes);
return super.toCacheObject(ctx, type, bytes);
}
/** {@inheritDoc} */
@Override public KeyCacheObject toKeyCacheObject(CacheObjectContext ctx, byte type, byte[] bytes)
throws IgniteCheckedException {
if (type == BinaryObjectImpl.TYPE_BINARY)
return new BinaryObjectImpl(binaryContext(), bytes, 0);
return super.toKeyCacheObject(ctx, type, bytes);
}
/** {@inheritDoc} */
@Override public Object unwrapTemporary(GridCacheContext ctx, Object obj) throws BinaryObjectException {
if (!ctx.cacheObjectContext().binaryEnabled())
return obj;
if (obj instanceof BinaryObjectOffheapImpl)
return ((BinaryObjectOffheapImpl)obj).heapCopy();
return obj;
}
/**
* @param obj Object.
* @return Binary object.
* @throws IgniteException In case of error.
*/
@Nullable public Object toBinary(@Nullable Object obj) throws IgniteException {
if (obj == null)
return null;
if (isBinaryObject(obj))
return obj;
return marshalToBinary(obj);
}
/** {@inheritDoc} */
@Nullable @Override public IgniteNodeValidationResult validateNode(ClusterNode rmtNode, DiscoveryDataBag.JoiningNodeDiscoveryData discoData) {
IgniteNodeValidationResult res;
if (getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK) || !(marsh instanceof BinaryMarshaller))
return null;
if ((res = validateBinaryConfiguration(rmtNode)) != null)
return res;
return validateBinaryMetadata(rmtNode.id(), (Map<Integer, BinaryMetadataHolder>) discoData.joiningNodeData());
}
/** */
private IgniteNodeValidationResult validateBinaryConfiguration(ClusterNode rmtNode) {
Object rmtBinaryCfg = rmtNode.attribute(IgniteNodeAttributes.ATTR_BINARY_CONFIGURATION);
ClusterNode locNode = ctx.discovery().localNode();
Object locBinaryCfg = locNode.attribute(IgniteNodeAttributes.ATTR_BINARY_CONFIGURATION);
if (!F.eq(locBinaryCfg, rmtBinaryCfg)) {
String msg = "Local node's binary configuration is not equal to remote node's binary configuration " +
"[locNodeId=%s, rmtNodeId=%s, locBinaryCfg=%s, rmtBinaryCfg=%s]";
return new IgniteNodeValidationResult(rmtNode.id(),
String.format(msg, locNode.id(), rmtNode.id(), locBinaryCfg, rmtBinaryCfg),
String.format(msg, rmtNode.id(), locNode.id(), rmtBinaryCfg, locBinaryCfg));
}
return null;
}
/** */
private IgniteNodeValidationResult validateBinaryMetadata(UUID rmtNodeId, Map<Integer, BinaryMetadataHolder> newNodeMeta) {
if (newNodeMeta == null)
return null;
for (Map.Entry<Integer, BinaryMetadataHolder> metaEntry : newNodeMeta.entrySet()) {
if (!metadataLocCache.containsKey(metaEntry.getKey()))
continue;
BinaryMetadata locMeta = metadataLocCache.get(metaEntry.getKey()).metadata();
BinaryMetadata rmtMeta = metaEntry.getValue().metadata();
if (locMeta == null || rmtMeta == null)
continue;
try {
BinaryUtils.mergeMetadata(locMeta, rmtMeta);
}
catch (Exception e) {
String locMsg = "Exception was thrown when merging binary metadata from node %s: %s";
String rmtMsg = "Exception was thrown on coordinator when merging binary metadata from this node: %s";
return new IgniteNodeValidationResult(rmtNodeId,
String.format(locMsg, rmtNodeId.toString(), e.getMessage()),
String.format(rmtMsg, e.getMessage()));
}
}
return null;
}
/** {@inheritDoc} */
@Nullable @Override public DiscoveryDataExchangeType discoveryDataType() {
return BINARY_PROC;
}
/** {@inheritDoc} */
@Override public void collectGridNodeData(DiscoveryDataBag dataBag) {
if (!dataBag.commonDataCollectedFor(BINARY_PROC.ordinal())) {
Map<Integer, BinaryMetadataHolder> res = U.newHashMap(metadataLocCache.size());
for (Map.Entry<Integer,BinaryMetadataHolder> e : metadataLocCache.entrySet())
res.put(e.getKey(), e.getValue());
dataBag.addGridCommonData(BINARY_PROC.ordinal(), (Serializable) res);
}
}
/** {@inheritDoc} */
@Override public void collectJoiningNodeData(DiscoveryDataBag dataBag) {
Map<Integer, BinaryMetadataHolder> res = U.newHashMap(metadataLocCache.size());
for (Map.Entry<Integer,BinaryMetadataHolder> e : metadataLocCache.entrySet())
res.put(e.getKey(), e.getValue());
dataBag.addJoiningNodeData(BINARY_PROC.ordinal(), (Serializable) res);
}
/** {@inheritDoc} */
@Override public void onJoiningNodeDataReceived(DiscoveryDataBag.JoiningNodeDiscoveryData data) {
Map<Integer,BinaryMetadataHolder> newNodeMeta = (Map<Integer, BinaryMetadataHolder>) data.joiningNodeData();
if (newNodeMeta == null)
return;
UUID joiningNode = data.joiningNodeId();
for (Map.Entry<Integer, BinaryMetadataHolder> metaEntry : newNodeMeta.entrySet()) {
if (metadataLocCache.containsKey(metaEntry.getKey())) {
BinaryMetadataHolder localMetaHolder = metadataLocCache.get(metaEntry.getKey());
BinaryMetadata newMeta = metaEntry.getValue().metadata();
BinaryMetadata localMeta = localMetaHolder.metadata();
BinaryMetadata mergedMeta = BinaryUtils.mergeMetadata(localMeta, newMeta);
if (mergedMeta != localMeta) {
//put mergedMeta to local cache and store to disk
U.log(log,
String.format("Newer version of existing BinaryMetadata[typeId=%d, typeName=%s] " +
"is received from node %s; updating it locally",
mergedMeta.typeId(),
mergedMeta.typeName(),
joiningNode));
metadataLocCache.put(metaEntry.getKey(),
new BinaryMetadataHolder(mergedMeta,
localMetaHolder.pendingVersion(),
localMetaHolder.acceptedVersion()));
metadataFileStore.writeMetadata(mergedMeta);
}
}
else {
BinaryMetadataHolder newMetaHolder = metaEntry.getValue();
BinaryMetadata newMeta = newMetaHolder.metadata();
U.log(log,
String.format("New BinaryMetadata[typeId=%d, typeName=%s] " +
"is received from node %s; adding it locally",
newMeta.typeId(),
newMeta.typeName(),
joiningNode));
metadataLocCache.put(metaEntry.getKey(), newMetaHolder);
metadataFileStore.writeMetadata(newMeta);
}
}
}
/** {@inheritDoc} */
@Override public void onGridDataReceived(GridDiscoveryData data) {
Map<Integer, BinaryMetadataHolder> receivedData = (Map<Integer, BinaryMetadataHolder>) data.commonData();
if (receivedData != null) {
for (Map.Entry<Integer, BinaryMetadataHolder> e : receivedData.entrySet()) {
BinaryMetadataHolder holder = e.getValue();
BinaryMetadataHolder localHolder = new BinaryMetadataHolder(holder.metadata(),
holder.pendingVersion(),
holder.pendingVersion());
if (log.isDebugEnabled())
log.debug("Received metadata on join: " + localHolder);
metadataLocCache.put(e.getKey(), localHolder);
if (!ctx.clientNode())
metadataFileStore.writeMetadata(holder.metadata());
}
}
}
/**
* Sets path to binary metadata store configured by user, should include binary_meta and consistentId
* @param binaryMetadataFileStoreDir path to binary_meta
*/
public void setBinaryMetadataFileStoreDir(@Nullable File binaryMetadataFileStoreDir) {
this.binaryMetadataFileStoreDir = binaryMetadataFileStoreDir;
}
}
|
|
// ----------------------------------------------------------------------------
// Copyright 2006-2010, GeoTelematic Solutions, 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.
//
// ----------------------------------------------------------------------------
// Description:
// Outbound SMS Gateway support
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Change History:
// 2010/07/18 Martin D. Flynn
// -Initial release
// 2010/11/29 Martin D. Flynn
// -Added "httpURL" format
// ----------------------------------------------------------------------------
package org.opengts.db;
import java.lang.*;
import java.util.*;
import java.io.*;
import java.net.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.tables.*;
/**
*** Outbound SMS gateway handler
**/
public abstract class SMSOutboundGateway
{
// ------------------------------------------------------------------------
public static final String PROP_SmsGatewayHandler_ = "SmsGatewayHandler.";
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private static Map<String,SMSOutboundGateway> SmsGatewayHandlerMap = null;
/**
*** Add SMS Gateway support provider
**/
public static void AddSMSGateway(String name, SMSOutboundGateway smsGW)
{
/* validate name */
if (StringTools.isBlank(name)) {
Print.logWarn("SMS Gateway name is blank");
return;
} else
if (smsGW == null) {
Print.logWarn("SMS Gateway handler is null");
return;
}
/* initialize map? */
if (SmsGatewayHandlerMap == null) {
SmsGatewayHandlerMap = new HashMap<String,SMSOutboundGateway>();
}
/* save handler */
SmsGatewayHandlerMap.put(name.toLowerCase(), smsGW);
Print.logDebug("Added SMS Gateway Handler: " + name);
}
/**
*** Gets the SMSoutboubdGateway for the specified name
**/
public static SMSOutboundGateway GetSMSGateway(String name)
{
/* get handler */
if (StringTools.isBlank(name)) {
return null;
} else {
return SmsGatewayHandlerMap.get(name.toLowerCase());
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Initialize outbound SMS gateway handlers
**/
public static void _startupInit()
{
Print.logDebug("SMSOutboundGateway initializing ...");
final String SMSKey_ = SMSOutboundGateway.PROP_SmsGatewayHandler_;
/* already initialized? */
if (SmsGatewayHandlerMap != null) {
return;
}
// -----------------------------------------------
// The following shows several example of outbound SMS gateway support.
// The only method that needs to be overridden and implemented is
// public DCServerFactory.ResultCode sendSMSCommand(Device device, String commandStr)
// The "device" is the Device record instance to which the SMS message should be sent,
// and "commandStr" is the SMS text (device command) which is to be sent to the device.
// -----------------------------------------------
/* standard "Body" command */
// Property:
// [email protected]
// Notes:
// This outbound SMS method sends the SMS text in an email message body to the device
// "smsEmailAddress". If the device "smsEmailAddress" is blank, then the "To" email
// address is constructed from the device "simPhoneNumber" and the email address
// specified on the property "SmsGatewayHandler.emailBody.smsEmailAddress".
SMSOutboundGateway.AddSMSGateway("emailBody", new SMSOutboundGateway() {
public DCServerFactory.ResultCode sendSMSCommand(Device device, String commandStr) {
if (device == null) { return DCServerFactory.ResultCode.INVALID_DEVICE; }
String frEmail = this.getFromEmailAddress(device);
String toEmail = this.getSmsEmailAddress(device);
if (StringTools.isBlank(toEmail)) {
String smsEmail = this.getStringProperty(device,SMSKey_+"emailBody.smsEmailAddress","");
toEmail = smsEmail.startsWith("@")? (device.getSimPhoneNumber() + smsEmail) : smsEmail;
}
return this.sendEmail(frEmail, toEmail, "", commandStr);
}
});
/* standard "Subject" command */
// Property:
// SmsGatewayHandler.emailSubject.smsEmailAddress=
// Notes:
// This outbound SMS method sends the SMS text in an email message subject to the device
// "smsEmailAddress". If the device "smsEmailAddress" is blank, then the "To" email
// address is constructed from the device "simPhoneNumber" and the email address
// specified on the property "SmsGatewayHandler.emailSubject.smsEmailAddress".
SMSOutboundGateway.AddSMSGateway("emailSubject", new SMSOutboundGateway() {
public DCServerFactory.ResultCode sendSMSCommand(Device device, String commandStr) {
if (device == null) { return DCServerFactory.ResultCode.INVALID_DEVICE; }
String frEmail = this.getFromEmailAddress(device);
String toEmail = this.getSmsEmailAddress(device);
if (StringTools.isBlank(toEmail)) {
String smsEmail = this.getStringProperty(device,SMSKey_+"emailSubject.smsEmailAddress","");
toEmail = smsEmail.startsWith("@")? (device.getSimPhoneNumber() + smsEmail) : smsEmail;
}
return this.sendEmail(frEmail, toEmail, commandStr, "");
}
});
/* HTTP SMS */
// Property:
// SmsGatewayHandler.httpURL.url=http://localhost:12345/smsredirector/sendsms?flash=0&acctuser=user&tracking_Pwd=pass&source=5551212&destination=${mobile}&message=${message}
// SmsGatewayHandler.httpURL.url=http://localhost:12345/sendsms?user=user&pass=pass&source=5551212&dest=${mobile}&text=${message}
// Notes:
// This outbound SMS method sends the SMS text in an HTTP "GET" request to the URL
// specified on the property "SmsGatewayHandler.httpURL.url". The following replacement
// variables may be specified in the URL string:
// ${mobile} - replaced with the Device "simPhoneNumber" field contents
// ${message} - replaced with the SMS text/command to be sent to the device.
// It is expected that the server handling the request understands how to parse and
// interpret the various fields in the URL.
SMSOutboundGateway.AddSMSGateway("httpURL", new SMSOutboundGateway() {
public DCServerFactory.ResultCode sendSMSCommand(Device device, String commandStr) {
if (device == null) { return DCServerFactory.ResultCode.INVALID_DEVICE; }
String KeyURL = SMSKey_+"httpURL.url";
String mobile = URIArg.encodeArg(device.getSimPhoneNumber());
String message = URIArg.encodeArg(commandStr);
String httpURL = this.getStringProperty(device, KeyURL, "");
if (StringTools.isBlank(httpURL)) {
Print.logWarn("'"+KeyURL+"' not specified");
return DCServerFactory.ResultCode.INVALID_SMS;
}
httpURL = StringTools.replace(httpURL, "${mobile}" , mobile);
httpURL = StringTools.replace(httpURL, "${message}", message);
try {
Print.logDebug("SMS Gateway URL: " + httpURL);
byte response[] = HTMLTools.readPage_GET(httpURL, 10000);
// TODO: check response?
return DCServerFactory.ResultCode.SUCCESS;
} catch (UnsupportedEncodingException uee) {
Print.logError("URL Encoding: " + uee);
return DCServerFactory.ResultCode.TRANSMIT_FAIL;
} catch (NoRouteToHostException nrthe) {
Print.logError("Unreachable Host: " + httpURL);
return DCServerFactory.ResultCode.UNKNOWN_HOST;
} catch (UnknownHostException uhe) {
Print.logError("Unknown Host: " + httpURL);
return DCServerFactory.ResultCode.UNKNOWN_HOST;
} catch (FileNotFoundException fnfe) {
Print.logError("Invalid URL (not found): " + httpURL);
return DCServerFactory.ResultCode.INVALID_SMS;
} catch (MalformedURLException mue) {
Print.logError("Invalid URL (malformed): " + httpURL);
return DCServerFactory.ResultCode.INVALID_SMS;
} catch (Throwable th) {
Print.logError("HTML SMS error: " + th);
return DCServerFactory.ResultCode.TRANSMIT_FAIL;
}
}
});
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public SMSOutboundGateway()
{
// override
}
// ------------------------------------------------------------------------
public abstract DCServerFactory.ResultCode sendSMSCommand(Device device, String command);
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
protected String getFromEmailAddress(Device device)
{
if (device == null) { return null; }
return CommandPacketHandler.getFromEmailCommand(device.getAccount());
}
protected String getSmsEmailAddress(Device device)
{
if (device == null) { return null; }
String toEmail = device.getSmsEmail();
return toEmail;
}
protected String getSmsPhoneNumber(Device device)
{
if (device == null) { return null; }
String smsPhone = device.getSimPhoneNumber();
return smsPhone;
}
protected String getStringProperty(Device device, String key, String dft)
{
DCServerConfig dcs = (device != null)? DCServerFactory.getServerConfig(device.getDeviceCode()) : null;
String prop = null;
if (dcs != null) {
prop = dcs.getStringProperty(key, dft);
Print.logInfo("DCServerConfig property '"+key+"' ==> " + prop);
if (StringTools.isBlank(prop) && RTConfig.hasProperty(key)) {
Print.logInfo("(RTConfig property '"+key+"' ==> " + RTConfig.getString(key,"") + ")");
}
} else {
prop = RTConfig.getString(key, dft);
Print.logInfo("RTConfig property '"+key+"' ==> " + prop);
}
return prop;
}
// ------------------------------------------------------------------------
protected DCServerFactory.ResultCode sendEmail(String frEmail, String toEmail, String subj, String body)
{
if (StringTools.isBlank(frEmail)) {
Print.logError("'From' Email address not specified");
return DCServerFactory.ResultCode.TRANSMIT_FAIL;
} else
if (StringTools.isBlank(toEmail) || !CommandPacketHandler.validateAddress(toEmail)) {
Print.logError("'To' SMS Email address invalid, or not specified");
return DCServerFactory.ResultCode.TRANSMIT_FAIL;
} else
if (StringTools.isBlank(subj) && StringTools.isBlank(body)) {
Print.logError("Command string not specified");
return DCServerFactory.ResultCode.INVALID_ARG;
} else {
try {
Print.logInfo ("SMS email: to <" + toEmail + ">");
Print.logDebug(" From : " + frEmail);
Print.logDebug(" To : " + toEmail);
Print.logDebug(" Subject: " + subj);
Print.logDebug(" Message: " + body);
SendMail.send(frEmail, toEmail, null, null, subj, body, null);
return DCServerFactory.ResultCode.SUCCESS;
} catch (Throwable t) { // NoClassDefFoundException, ClassNotFoundException
// this will fail if JavaMail support for SendMail is not available.
Print.logWarn("SendMail error: " + t);
return DCServerFactory.ResultCode.TRANSMIT_FAIL;
}
}
}
// ------------------------------------------------------------------------
}
|
|
/*
* Copyright (C) 2016 Jorge Ruesga
*
* 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.ruesga.rview.gerrit;
import com.ruesga.rview.gerrit.filter.AccountQuery;
import com.ruesga.rview.gerrit.filter.ChangeQuery;
import com.ruesga.rview.gerrit.filter.GroupQuery;
import com.ruesga.rview.gerrit.filter.Option;
import com.ruesga.rview.gerrit.filter.ProjectQuery;
import com.ruesga.rview.gerrit.model.*;
import java.util.List;
import java.util.Map;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import io.reactivex.Observable;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Gerrit REST api
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
interface GerritRestApi {
// ===============================
// Gerrit access endpoints
// @link "https://gerrit-review.googlesource.com/Documentation/rest-api-access.html"
// ===============================
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-access.html#list-access"
*/
@GET("access/")
Observable<Map<String, ProjectAccessInfo>> getAccessRights(
@NonNull @Query("project") String[] names);
// ===============================
// Gerrit accounts endpoints
// @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html"
// ===============================
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#query-account"
*/
@GET("accounts/")
Observable<List<AccountInfo>> getAccountsSuggestions(
@NonNull @Query("q") String query,
@Nullable @Query("n") Integer count,
@Nullable @Query("suggest") Option suggest);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#query-account"
*/
@GET("accounts/")
Observable<List<AccountInfo>> getAccounts(
@NonNull @Query("q") AccountQuery query,
@Nullable @Query("n") Integer count,
@Nullable @Query("S") Integer start,
@Nullable @Query("o") List<AccountOptions> options);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account"
*/
@GET("accounts/{account-id}/")
Observable<AccountInfo> getAccount(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#create-account"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{username}")
Observable<AccountInfo> createAccount(
@NonNull @Path("username") String username,
@NonNull @Body AccountInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-detail"
*/
@GET("accounts/{account-id}/detail")
Observable<AccountDetailInfo> getAccountDetails(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account-name"
*/
@GET("accounts/{account-id}/name")
Observable<String> getAccountName(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-account-name"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/name")
Observable<String> setAccountName(
@NonNull @Path("account-id") String accountId,
@NonNull @Body AccountNameInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-account-name"
*/
@DELETE("accounts/{account-id}/name")
Observable<Void> deleteAccountName(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account-status"
*/
@GET("accounts/{account-id}/status")
Observable<String> getAccountStatus(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-account-status"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/status")
Observable<String> setAccountStatus(
@NonNull @Path("account-id") String accountId,
@NonNull @Body AccountStatusInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-username"
*/
@GET("accounts/{account-id}/username")
Observable<String> getAccountUsername(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-username"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/username")
Observable<String> setAccountUsername(
@NonNull @Path("account-id") String accountId,
@NonNull @Body UsernameInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-display-name"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/displayname")
Observable<String> setAccountDisplayName(
@NonNull @Path("account-id") String accountId,
@NonNull @Body DisplayNameInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-active"
*/
@GET("accounts/{account-id}/active")
Observable<String> isAccountActive(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-active"
*/
@PUT("accounts/{account-id}/active")
Observable<Void> setAccountAsActive(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-active"
*/
@DELETE("accounts/{account-id}/active")
Observable<Void> setAccountAsInactive(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-http-password"
*/
@GET("accounts/{account-id}/password.http")
Observable<String> getHttpPassword(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-http-password"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/password.http")
Observable<String> setHttpPassword(
@NonNull @Path("account-id") String accountId,
@NonNull @Body HttpPasswordInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-http-password"
*/
@DELETE("accounts/{account-id}/password.http")
Observable<Void> deleteHttpPassword(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-oauth-token"
*/
@GET("accounts/{account-id}/oauthtoken")
Observable<OAuthTokenInfo> getOAuthToken(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-account-emails"
*/
@GET("accounts/{account-id}/emails")
Observable<List<EmailInfo>> getAccountEmails(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-account-email"
*/
@GET("accounts/{account-id}/emails/{email-id}")
Observable<EmailInfo> getAccountEmail(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("email-id") String emailId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#create-account-email"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/emails/{email-id}")
Observable<EmailInfo> createAccountEmail(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("email-id") String emailId,
@NonNull @Body EmailInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-account-email"
*/
@DELETE("accounts/{account-id}/emails/{email-id}")
Observable<Void> deleteAccountEmail(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("email-id") String emailId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-preferred-email"
*/
@PUT("accounts/{account-id}/emails/{email-id}/preferred")
Observable<Void> setAccountPreferredEmail(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("email-id") String emailId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-ssh-keys"
*/
@GET("accounts/{account-id}/sshkeys")
Observable<List<SshKeyInfo>> getAccountSshKeys(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-ssh-key"
*/
@GET("accounts/{account-id}/sshkeys/{ssh-key-id}")
Observable<SshKeyInfo> getAccountSshKey(
@NonNull @Path("account-id") String accountId,
@Path("ssh-key-id") int sshKeyId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#add-ssh-key"
*/
@Headers({"Content-Type: plain/text"})
@POST("accounts/{account-id}/sshkeys")
Observable<SshKeyInfo> addAccountSshKey(
@NonNull @Path("account-id") String accountId,
@NonNull @Body String encodedKey);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-ssh-key"
*/
@DELETE("accounts/{account-id}/sshkeys/{ssh-key-id}")
Observable<Void> deleteAccountSshKey(
@NonNull @Path("account-id") String accountId,
@Path("ssh-key-id") int sshKeyId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-gpg-keys"
*/
@GET("accounts/{account-id}/gpgkeys")
Observable<List<GpgKeyInfo>> getAccountGpgKeys(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-gpg-key"
*/
@GET("accounts/{account-id}/gpgkeys/{gpg-key-id}")
Observable<GpgKeyInfo> getAccountGpgKey(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("gpg-key-id") String gpgKeyId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#add-delete-gpg-keys"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("accounts/{account-id}/gpgkeys")
Observable<Map<String, GpgKeyInfo>> addAccountGpgKeys(
@NonNull @Path("account-id") String accountId,
@NonNull @Body AddGpgKeyInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#add-delete-gpg-keys"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("accounts/{account-id}/gpgkeys")
Observable<Map<String, GpgKeyInfo>> deleteAccountGpgKeys(
@NonNull @Path("account-id") String accountId,
@NonNull @Body DeleteGpgKeyInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-account-capabilities"
*/
@GET("accounts/{account-id}/capabilities")
Observable<AccountCapabilityInfo> getAccountCapabilities(
@NonNull @Path("account-id") String accountId,
@Nullable @Query("q") List<Capability> filter);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#check-account-capabilities"
*/
@GET("accounts/{account-id}/capabilities/{capability-id}")
Observable<String> hasAccountCapability(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("capability-id") Capability capabilityId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-groups"
*/
@GET("accounts/{account-id}/groups")
Observable<List<GroupInfo>> getAccountGroups(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-avatar"
*/
@GET("accounts/{account-id}/avatar")
Observable<ResponseBody> getAccountAvatar(
@NonNull @Path("account-id") String accountId,
@Nullable @Query("s") Integer size);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-avatar-change-url"
*/
@GET("accounts/{account-id}/avatar.change.url")
Observable<String> getAccountAvatarChangeUrl(@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-user-preferences"
*/
@GET("accounts/{account-id}/preferences")
Observable<PreferencesInfo> getAccountPreferences(
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-user-preferences"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/preferences")
Observable<PreferencesInfo> setAccountPreferences(
@NonNull @Path("account-id") String accountId,
@NonNull @Body PreferencesInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-diff-preferences"
*/
@GET("accounts/{account-id}/preferences.diff")
Observable<DiffPreferencesInfo> getAccountDiffPreferences(
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-diff-preferences"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/preferences.diff")
Observable<DiffPreferencesInfo> setAccountDiffPreferences(
@NonNull @Path("account-id") String accountId,
@NonNull @Body DiffPreferencesInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-edit-preferences"
*/
@GET("accounts/{account-id}/preferences.edit")
Observable<EditPreferencesInfo> getAccountEditPreferences(
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-edit-preferences"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/preferences.edit")
Observable<EditPreferencesInfo> setAccountEditPreferences(
@NonNull @Path("account-id") String accountId,
@NonNull @Body EditPreferencesInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-watched-projects"
*/
@GET("accounts/{account-id}/watched.projects")
Observable<List<ProjectWatchInfo>> getAccountWatchedProjects(
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-watched-projects"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("accounts/{account-id}/watched.projects")
Observable<List<ProjectWatchInfo>> addOrUpdateAccountWatchedProjects(
@NonNull @Path("account-id") String accountId,
@NonNull @Body List<ProjectWatchInput> input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#delete-watched-projects"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("accounts/{account-id}/watched.projects")
Observable<Void> deleteAccountWatchedProjects(
@NonNull @Path("account-id") String accountId,
@NonNull @Body List<DeleteProjectWatchInput> input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account-external-ids"
*/
@GET("accounts/{account-id}/external.ids")
Observable<List<AccountExternalIdInfo>> getAccountExternalIds(
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account-external-ids"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("accounts/{account-id}/external.ids:delete")
Observable<Void> deleteAccountExternalIds(
@NonNull @Path("account-id") String accountId,
@NonNull @Body List<String> externalIds);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-contributor-agreements"
*/
@GET("accounts/{account-id}/agreements")
Observable<List<ContributorAgreementInfo>> getContributorAgreements(
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#list-contributor-agreements"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("accounts/{account-id}/agreements")
Observable<String> signContributorAgreement(
@NonNull @Path("account-id") String accountId,
@NonNull @Body ContributorAgreementInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#index-account"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("accounts/{account-id}/index")
Observable<Void> indexAccount(
@NonNull @Path("account-id") String accountId);
/**
* @link "https:/gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#_delete_draft_comments"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("accounts/{account-id}/drafts:delete")
Observable<List<DeletedDraftCommentInfo>> deleteAccountDraftComments(
@NonNull @Path("account-id") String accountId,
@NonNull @Body DeleteDraftCommentsInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-changes-with-default-star"
*/
@GET("accounts/{account-id}/starred.changes")
Observable<List<ChangeInfo>> getDefaultStarredChanges(
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#star-change"
*/
@PUT("accounts/{account-id}/starred.changes/{change-id}")
Observable<Void> putDefaultStarOnChange(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#unstar-change"
*/
@DELETE("accounts/{account-id}/starred.changes/{change-id}")
Observable<Void> deleteDefaultStarFromChange(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-starred-changes"
*/
@GET("accounts/{account-id}/stars.changes")
Observable<List<ChangeInfo>> getStarredChanges(
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-stars"
*/
@GET("accounts/{account-id}/stars.changes/{change-id}")
Observable<List<String>> getStarLabelsFromChange(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#set-stars"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("accounts/{account-id}/stars.changes/{change-id}")
Observable<List<String>> updateStarLabelsFromChange(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("change-id") String changeId,
@NonNull @Body StarInput input);
// ===============================
// Gerrit changes endpoints
// @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html"
// ===============================
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#create-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/")
Observable<ChangeInfo> createChange(@NonNull @Body ChangeInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes"
*/
@GET("changes/")
Observable<List<ChangeInfo>> getChanges(
@NonNull @Query("q") ChangeQuery query,
@Nullable @Query("n") Integer count,
@Nullable @Query("S") Integer start,
@Nullable @Query("o") List<ChangeOptions> options);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-change"
*/
@GET("changes/{change-id}")
Observable<ChangeInfo> getChange(
@NonNull @Path("change-id") String changeId,
@Nullable @Query("o") List<ChangeOptions> options);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#create-merge-patch-set-for-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/merge")
Observable<ChangeInfo> createMergePathSetForChange(
@NonNull @Path("change-id") String changeId,
@NonNull @Body MergePatchSetInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-message"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("changes/{change-id}/message")
Observable<ChangeInfo> setChangeCommitMessage(
@NonNull @Path("change-id") String changeId,
@NonNull @Body CommitMessageInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-change-detail"
*/
@GET("changes/{change-id}/detail")
Observable<ChangeInfo> getChangeDetail(
@NonNull @Path("change-id") String changeId,
@Nullable @Query("o") List<ChangeOptions> options);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-topic"
*/
@GET("changes/{change-id}/topic")
Observable<String> getChangeTopic(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-topic"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("changes/{change-id}/topic")
Observable<String> setChangeTopic(
@NonNull @Path("change-id") String changeId,
@NonNull @Body TopicInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-topic"
*/
@DELETE("changes/{change-id}/topic")
Observable<Void> deleteChangeTopic(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-assignee"
*/
@GET("changes/{change-id}/")
Observable<AccountInfo> getChangeAssignee(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-past-assignees"
*/
@GET("changes/{change-id}/past_assignees")
Observable<List<AccountInfo>> getChangePastAssignees(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-assignee"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("changes/{change-id}/assignee")
Observable<AccountInfo> setChangeAssignee(
@NonNull @Path("change-id") String changeId,
@NonNull @Body AssigneeInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-assignee"
*/
@DELETE("changes/{change-id}/assignee")
Observable<AccountInfo> deleteChangeAssignee(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-pure-revert"
*/
@GET("changes/{change-id}/pure_revert")
Observable<PureRevertInfo> getChangePureRevert(
@NonNull @Path("change-id") String changeId,
@Nullable @Query("o") String commit,
@Nullable @Query("revertOf") String revertOf);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#abandon-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/abandon")
Observable<ChangeInfo> abandonChange(
@NonNull @Path("change-id") String changeId,
@NonNull @Body AbandonInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#restore-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/restore")
Observable<ChangeInfo> restoreChange(
@NonNull @Path("change-id") String changeId,
@NonNull @Body RestoreInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#rebase-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/rebase")
Observable<ChangeInfo> rebaseChange(
@NonNull @Path("change-id") String changeId,
@NonNull @Body RebaseInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#move-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/move")
Observable<ChangeInfo> moveChange(
@NonNull @Path("change-id") String changeId,
@NonNull @Body MoveInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#revert-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/revert")
Observable<ChangeInfo> revertChange(
@NonNull @Path("change-id") String changeId,
@NonNull @Body RevertInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/submit")
Observable<ChangeInfo> submitChange(
@NonNull @Path("change-id") String changeId,
@NonNull @Body SubmitInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submitted-together"
*/
@GET("changes/{change-id}/submitted_together")
Observable<List<ChangeInfo>> getChangesSubmittedTogether(
@NonNull @Path("change-id") String changeId,
@Nullable @Query("o") List<SubmittedTogetherOptions> options);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#publish-draft-change"
* @deprecated since 2.15
*/
@POST("changes/{change-id}/publish")
@Deprecated
Observable<Void> publishDraftChange(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-change"
*/
@DELETE("changes/{change-id}")
Observable<Void> deleteChange(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-included-in"
*/
@GET("changes/{change-id}/in")
Observable<IncludedInInfo> getChangeIncludedIn(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#index-change"
*/
@POST("changes/{change-id}/index")
Observable<Void> indexChange(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-change-comments"
*/
@GET("changes/{change-id}/comments")
Observable<Map<String, List<CommentInfo>>> getChangeComments(
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-change-robot-comments"
*/
@GET("changes/{change-id}/robotcomments")
Observable<Map<String, List<RobotCommentInfo>>> getChangeRobotComments(
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-change-drafts"
*/
@GET("changes/{change-id}/drafts")
Observable<Map<String, List<CommentInfo>>> getChangeDraftComments(
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#check-change"
*/
@GET("changes/{change-id}/check")
Observable<ChangeInfo> checkChange(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#fix-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/check")
Observable<ChangeInfo> fixChange(
@NonNull @Path("change-id") String changeId,
@NonNull @Body FixInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#fix-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/wip")
Observable<Void> setChangeWorkInProgress(
@NonNull @Path("change-id") String changeId,
@NonNull @Body WorkInProgressInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-ready-for-review"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/ready")
Observable<Void> setChangeReadyForReview(
@NonNull @Path("change-id") String changeId,
@NonNull @Body WorkInProgressInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#mark-private"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/private")
Observable<Void> markChangeAsPrivate(
@NonNull @Path("change-id") String changeId,
@NonNull @Body PrivateInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#unmark-private"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/private.delete")
Observable<Void> unmarkChangeAsPrivate(
@NonNull @Path("change-id") String changeId,
@NonNull @Body PrivateInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#ignore"
*/
@PUT("changes/{change-id}/ignore")
Observable<Void> ignoreChange(
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#unignore"
*/
@PUT("changes/{change-id}/unignore")
Observable<Void> unignoreChange(
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#reviewed"
*/
@PUT("changes/{change-id}/reviewed")
Observable<Void> markChangeAsReviewed(
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#unreviewed"
*/
@PUT("changes/{change-id}/unreviewed")
Observable<Void> markChangeAsUnreviewed(
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-hashtags"
*/
@GET("changes/{change-id}/hashtags")
Observable<String[]> getChangeHashtags(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-hashtags"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/hashtags")
Observable<String[]> setChangeHashtags(
@NonNull @Path("change-id") String changeId,
@NonNull @Body HashtagsInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-change-messages"
*/
@GET("changes/{change-id}/messages")
Observable<List<ChangeMessageInfo>> getChangeMessages(
@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-change-message"
*/
@GET("changes/{change-id}/messages/{change-message-id}")
Observable<ChangeMessageInfo> getChangeMessage(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("change-message-id") String messageId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-change-message"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/messages/{change-message-id}")
Observable<ChangeMessageInfo> deleteChangeMessage(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("change-message-id") String messageId,
@NonNull @Body DeleteChangeMessageInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-detail"
*/
@GET("changes/{change-id}/edit")
Observable<EditInfo> getChangeEdit(
@NonNull @Path("change-id") String changeId,
@Nullable @Query("list") Option list,
@Nullable @Query("base") String base,
@Nullable @Query("download-commands") Option downloadCommands);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#put-edit-file"
*/
@Headers({"Content-Type: application/octet-stream"})
@PUT("changes/{change-id}/edit/{file-id}")
Observable<Void> setChangeEditFile(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("file-id") String fileId,
@NonNull @Body RequestBody data);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#post-edit"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/edit")
Observable<Void> restoreChangeEditFile(
@NonNull @Path("change-id") String changeId,
@NonNull @Body RestoreChangeEditInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#post-edit"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/edit")
Observable<Void> renameChangeEditFile(
@NonNull @Path("change-id") String changeId,
@NonNull @Body RenameChangeEditInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#post-edit"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/edit")
Observable<Void> newChangeEditFile(
@NonNull @Path("change-id") String changeId,
@NonNull @Body NewChangeEditInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-edit-file"
*/
@DELETE("changes/{change-id}/edit/{file-id}")
Observable<Void> deleteChangeEditFile(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("file-id") String fileId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-file"
*/
@GET("changes/{change-id}/edit/{file-id}")
Observable<Base64Data> getChangeEditFileContent(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("file-id") String fileId,
@Nullable @Query("base") String base);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-file"
*/
@GET("changes/{change-id}/edit/{file-id}/meta")
Observable<EditFileInfo> getChangeEditFileMetadata(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("file-id") String fileId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-edit-message"
*/
@GET("changes/{change-id}/edit:message")
Observable<String> getChangeEditMessage(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#put-change-edit-message"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("changes/{change-id}/edit:message")
Observable<Void> setChangeEditMessage(
@NonNull @Path("change-id") String changeId,
@NonNull @Body ChangeEditMessageInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#publish-edit"
*/
@POST("changes/{change-id}/edit:publish")
Observable<Void> publishChangeEdit(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#rebase-edit"
*/
@POST("changes/{change-id}/edit:rebase")
Observable<Void> rebaseChangeEdit(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-edit"
*/
@DELETE("changes/{change-id}/edit")
Observable<Void> deleteChangeEdit(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-reviewers"
*/
@GET("changes/{change-id}/reviewers")
Observable<List<ReviewerInfo>> getChangeReviewers(@NonNull @Path("change-id") String changeId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#suggest-reviewers"
*/
@SuppressWarnings("deprecation")
@GET("changes/{change-id}/suggest_reviewers")
Observable<List<SuggestedReviewerInfo>> getChangeSuggestedReviewers(
@NonNull @Path("change-id") String changeId,
@NonNull @Query("q") String query,
@Nullable @Query("n") Integer count,
@Nullable @Query("e") ExcludeGroupsFromSuggestedReviewers excludeGroups);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#suggest-reviewers"
*/
@GET("changes/{change-id}/suggest_reviewers")
Observable<List<SuggestedReviewerInfo>> getChangeSuggestedReviewers(
@NonNull @Path("change-id") String changeId,
@NonNull @Query("q") String query,
@Nullable @Query("n") Integer count,
@Nullable @Query("exclude-groups") Option excludeGroups,
@Nullable @Query("reviewer-state") SuggestedReviewersState reviewersState);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-reviewer"
*/
@GET("changes/{change-id}/reviewers/{account-id}")
Observable<List<ReviewerInfo>> getChangeReviewer(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#add-reviewer"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/reviewers")
Observable<AddReviewerResultInfo> addChangeReviewer(
@NonNull @Path("change-id") String changeId,
@NonNull @Body ReviewerInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-reviewer"
*/
@DELETE("changes/{change-id}/reviewers/{account-id}")
Observable<Void> deleteChangeReviewer(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-votes"
*/
@GET("changes/{change-id}/reviewers/{account-id}/votes/")
Observable<Map<String, Integer>> getChangeReviewerVotes(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-vote"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/reviewers/{account-id}/votes/{label-id}/delete")
Observable<Void> deleteChangeReviewerVote(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("account-id") String accountId,
@NonNull @Path("label-id") String labelId,
@NonNull @Body DeleteVoteInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-commit"
*/
@GET("changes/{change-id}/revisions/{revision-id}/commit")
Observable<CommitInfo> getChangeRevisionCommit(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@Nullable @Query("links") Option links);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-description"
*/
@GET("changes/{change-id}/revisions/{revision-id}/description")
Observable<String> getChangeRevisionDescription(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-description"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("changes/{change-id}/revisions/{revision-id}/description")
Observable<String> setChangeRevisionDescription(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Body DescriptionInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-merge-list"
*/
@GET("changes/{change-id}/revisions/{revision-id}/mergelist")
Observable<List<CommentInfo>> getChangeRevisionMergeList(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-revision-actions"
*/
@GET("changes/{change-id}/revisions/{revision-id}/actions")
Observable<Map<String, ActionInfo>> getChangeRevisionActions(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-review"
*/
@GET("changes/{change-id}/revisions/{revision-id}/review")
Observable<ChangeInfo> getChangeRevisionReview(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-review"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/revisions/{revision-id}/review")
Observable<ReviewResultInfo> setChangeRevisionReview(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Body ReviewInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-related-changes"
*/
@GET("changes/{change-id}/revisions/{revision-id}/related")
Observable<RelatedChangesInfo> getChangeRevisionRelatedChanges(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#rebase-revision"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/revisions/{revision-id}/rebase")
Observable<ChangeInfo> rebaseChangeRevision(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Body RebaseInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-revision"
*/
@POST("changes/{change-id}/revisions/{revision-id}/submit")
Observable<SubmitInfo> submitChangeRevision(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#publish-draft-revision"
* @deprecated since 2.15
*/
@POST("changes/{change-id}/revisions/{revision-id}/publish")
@Deprecated
Observable<Void> publishChangeDraftRevision(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-draft-revision"
* @deprecated since 2.15
*/
@DELETE("changes/{change-id}/revisions/{revision-id}")
@Deprecated
Observable<SubmitInfo> deleteChangeDraftRevision(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-patch"
*/
@GET("changes/{change-id}/revisions/{revision-id}/patch")
Observable<Base64Data> getChangeRevisionPatch(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@Nullable @Query("zip") Option zip,
@Nullable @Query("download") Option download);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#submit-preview"
*/
@GET("changes/{change-id}/revisions/{revision-id}/preview_submit")
Observable<ResponseBody> getChangeRevisionSubmitPreview(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-mergeable"
*/
@GET("changes/{change-id}/revisions/{revision-id}/mergeable")
Observable<MergeableInfo> getChangeRevisionMergeableStatus(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@Nullable @Query("other-branches") Option otherBranches);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-submit-type"
*/
@GET("changes/{change-id}/revisions/{revision-id}/submit_type")
Observable<SubmitType> getChangeRevisionSubmitType(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#test-submit-type"
*/
@POST("changes/{change-id}/revisions/{revision-id}/test.submit_type")
Observable<SubmitType> testChangeRevisionSubmitType(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Body RuleInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#test-submit-rule"
*/
@POST("changes/{change-id}/revisions/{revision-id}/test.submit_rule")
Observable<List<SubmitRecordInfo>> testChangeRevisionSubmitRule(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Body RuleInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-drafts"
*/
@GET("changes/{change-id}/revisions/{revision-id}/drafts/")
Observable<Map<String, List<CommentInfo>>> getChangeRevisionDrafts(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#create-draft"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("changes/{change-id}/revisions/{revision-id}/drafts")
Observable<CommentInfo> createChangeRevisionDraft(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Body CommentInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-draft"
*/
@GET("changes/{change-id}/revisions/{revision-id}/drafts/{draft-id}")
Observable<CommentInfo> getChangeRevisionDraft(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("draft-id") String draftId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#update-draft"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("changes/{change-id}/revisions/{revision-id}/drafts/{draft-id}")
Observable<CommentInfo> updateChangeRevisionDraft(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("draft-id") String draftId,
@NonNull @Body CommentInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-draft"
*/
@DELETE("changes/{change-id}/revisions/{revision-id}/drafts/{draft-id}")
Observable<Void> deleteChangeRevisionDraft(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("draft-id") String draftId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-comments"
*/
@GET("changes/{change-id}/revisions/{revision-id}/comments/")
Observable<Map<String, List<CommentInfo>>> getChangeRevisionComments(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-comment"
*/
@GET("changes/{change-id}/revisions/{revision-id}/comments/{comment-id}")
Observable<CommentInfo> getChangeRevisionComment(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("comment-id") String commentId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-comment"
*/
@DELETE("changes/{change-id}/revisions/{revision-id}/comments/{comment-id}")
Observable<CommentInfo> deleteChangeRevisionComment(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("comment-id") String commentId,
@NonNull @Body DeleteCommentInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-robot-comments"
*/
@GET("changes/{change-id}/revisions/{revision-id}/robotcomments/")
Observable<Map<String, List<RobotCommentInfo>>> getChangeRevisionRobotComments(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-robot-comment"
*/
@GET("changes/{change-id}/revisions/{revision-id}/robotcomments/{comment-id}")
Observable<RobotCommentInfo> getChangeRevisionRobotComment(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("comment-id") String commentId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#apply-fix"
*/
@POST("changes/{change-id}/revisions/{revision-id}/fixes/{fix-id}/apply")
Observable<EditInfo> applyChangeRevisionFix(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("fix-id") String fixId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-files"
*/
@GET("changes/{change-id}/revisions/{revision-id}/files/")
Observable<Map<String, FileInfo>> getChangeRevisionFiles(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@Nullable @Query("base") String base,
@Nullable @Query("reviewed") Option reviewed);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-files"
*/
@GET("changes/{change-id}/revisions/{revision-id}/files/")
Observable<List<String>> getChangeRevisionFilesSuggestion(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@Nullable @Query("base") String base,
@Nullable @Query("reviewed") Option reviewed,
@Nullable @Query("q") String filter);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-content"
*/
@GET("changes/{change-id}/revisions/{revision-id}/files/{file-id}/content")
Observable<ResponseBody> getChangeRevisionFileContent(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("file-id") String fileId,
@Nullable @Query("parent") Integer parent);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-safe-content"
*/
@GET("changes/{change-id}/revisions/{revision-id}/files/{file-id}/safe_content")
Observable<ResponseBody> getChangeRevisionFileDownload(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("file-id") String fileId,
@Nullable @Query("suffix") SuffixMode suffixMode,
@Nullable @Query("parent") Integer parent);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-diff"
*/
@GET("changes/{change-id}/revisions/{revision-id}/files/{file-id}/diff")
Observable<DiffInfo> getChangeRevisionFileDiff(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("file-id") String fileId,
@Nullable @Query("base") Integer base,
@Nullable @Query("intraline") Option intraline,
@Nullable @Query("weblinks-only") Option weblinksOnly,
// Used in 2.13+
@Nullable @Query("whitespace") WhitespaceType whitespace,
// Used in 2.12-
@Nullable @Query("ignore-whitespace") IgnoreWhitespaceType ignoreWhitespace,
@Nullable @Query("context") ContextType context);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-blame"
*/
@GET("changes/{change-id}/revisions/{revision-id}/files/{file-id}/blame")
Observable<List<BlameInfo>> getChangeRevisionFileBlames(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("file-id") String fileId,
@Nullable @Query("base") BlameBaseType base);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-reviewed"
*/
@PUT("changes/{change-id}/revisions/{revision-id}/files/{file-id}/reviewed")
Observable<Void> setChangeRevisionFileAsReviewed(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("file-id") String fileId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-reviewed"
*/
@DELETE("changes/{change-id}/revisions/{revision-id}/files/{file-id}/reviewed")
Observable<Void> setChangeRevisionFileAsNotReviewed(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("file-id") String fileId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#cherry-pick"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("changes/{change-id}/revisions/{revision-id}/cherrypick")
Observable<CherryPickChangeInfo> cherryPickChangeRevision(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Body CherryPickInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-revision-reviewers"
*/
@GET("changes/{change-id}/revisions/{revision-id}/reviewers/")
Observable<List<ReviewerInfo>> getChangeRevisionReviewers(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-revision-votes"
*/
@GET("changes/{change-id}/revisions/{revision-id}/reviewers/{account-id}/votes/")
Observable<List<ReviewerInfo>> getChangeRevisionReviewersVotes(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#delete-revision-vote"
*/
@DELETE("changes/{change-id}/revisions/{revision-id}/reviewers/{account-id}/votes/{label-id}")
Observable<Void> deleteChangeRevisionReviewerVote(
@NonNull @Path("change-id") String changeId,
@NonNull @Path("revision-id") String revisionId,
@NonNull @Path("account-id") String accountId,
@NonNull @Path("label-id") String labelId,
@NonNull @Body DeleteVoteInput input);
// ===============================
// Gerrit configuration endpoints
// @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html"
// ===============================
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-version"
*/
@GET("config/server/version")
Observable<ServerVersion> getServerVersion();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-info"
*/
@GET("config/server/info")
Observable<ServerInfo> getServerInfo();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#check-consistency"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("config/server/check.consistency'")
Observable<ConsistencyCheckInfo> checkConsistency(@NonNull @Body ConsistencyCheckInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#reload-config"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("config/server/reload'")
Observable<ConfigUpdateInfo> reloadServerConfig();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#email-confirmation-input"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("config/server/email.confirm")
Observable<Void> confirmEmail(@NonNull @Body EmailConfirmationInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-caches"
*/
@GET("config/server/caches/")
Observable<Map<String, CacheInfo>> getServerCaches();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#cache-operations"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("config/server/caches/")
Observable<Void> executeServerCachesOperations(CacheOperationInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-cache"
*/
@GET("config/server/caches/{cache-id}")
Observable<CacheInfo> getServerCache(@NonNull @Path("cache-id") String cacheId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#flush-cache"
*/
@POST("config/server/caches/{cache-id}/flush")
Observable<Void> flushServerCache(@NonNull @Path("cache-id") String cacheId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-summary"
*/
@GET("config/server/summary")
Observable<SummaryInfo> getServerSummary(
@Nullable @Query("jvm") Option jvm,
@Nullable @Query("gc") Option gc);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-capabilities"
*/
@GET("config/server/capabilities")
Observable<Map<Capability, ServerCapabilityInfo>> getServerCapabilities();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-tasks"
*/
@GET("config/server/tasks/")
Observable<List<TaskInfo>> getServerTasks();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-task"
*/
@GET("config/server/tasks{task-id}")
Observable<TaskInfo> getServerTask(@NonNull @Path("task-id") String taskId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#delete-task"
*/
@DELETE("config/server/tasks{task-id}")
Observable<Void> deleteServerTask(@NonNull @Path("task-id") String taskId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-top-menus"
*/
@GET("config/server/top-menus")
Observable<List<TopMenuEntryInfo>> getServerTopMenus();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-user-preferences"
*/
@GET("config/server/preferences")
Observable<PreferencesInfo> getServerDefaultPreferences();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#set-user-preferences"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("config/server/preferences")
Observable<PreferencesInfo> setServerDefaultPreferences(@NonNull @Body PreferencesInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-diff-preferences"
*/
@GET("config/server/preferences.diff")
Observable<DiffPreferencesInfo> getServerDefaultDiffPreferences();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#set-diff-preferences"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("config/server/preferences.diff")
Observable<DiffPreferencesInfo> setServerDefaultDiffPreferences(
@NonNull @Body DiffPreferencesInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-edit-preferences"
*/
@GET("config/server/preferences.edit")
Observable<EditPreferencesInfo> getServerDefaultEditPreferences();
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#set-edit-preferences"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("config/server/preferences.edit")
Observable<EditPreferencesInfo> setServerDefaultEditPreferences(
@NonNull @Body EditPreferencesInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#index.changes"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("/config/server/index.changes")
Observable<ResponseBody> indexChanges(
@NonNull @Body IndexChangesInput input);
// ===============================
// Gerrit groups endpoints
// @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html"
// ===============================
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#list-groups"
*/
@GET("groups/")
Observable<List<GroupInfo>> getGroupSuggestions(
@NonNull @Query("q") String query,
@Nullable @Query("n") Integer count);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#list-groups"
*/
@GET("groups/")
Observable<List<GroupInfo>> getGroups(
@Nullable @Query("n") Integer count,
@Nullable @Query("S") Integer start,
@Nullable @Query("p") String project,
@Nullable @Query("u") String user,
@Nullable @Query("owned") Option owned,
@Nullable @Query("visible-to-all") Option visibleToAll,
@Nullable @Query("verbose") Option verbose,
@Nullable @Query("o") List<GroupOptions> options,
@Nullable @Query("s") String suggest,
@Nullable @Query("r") String regexp,
@Nullable @Query("m") String match);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#query-groups"
*/
@GET("groups/")
Observable<List<GroupInfo>> getGroups(
@NonNull @Query("query2") GroupQuery query,
@Nullable @Query("limit") Integer count,
@Nullable @Query("start") Integer start,
@Nullable @Query("ownedBy") String ownedBy,
@Nullable @Query("o") List<GroupOptions> options);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group"
*/
@GET("groups/{group-id}")
Observable<GroupInfo> getGroup(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#create-group"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("groups/{group-name}")
Observable<GroupInfo> createGroup(
@NonNull @Path("group-name") String groupName,
@NonNull @Body GroupInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-detail"
*/
@GET("groups/{group-id}/detail")
Observable<GroupInfo> getGroupDetail(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-name"
*/
@GET("groups/{group-id}/name")
Observable<String> getGroupName(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#rename-group"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("groups/{group-id}/name")
Observable<String> setGroupName(
@NonNull @Path("group-id") String groupId,
@NonNull @Body GroupNameInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-description"
*/
@GET("groups/{group-id}/description")
Observable<String> getGroupDescription(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#set-group-description"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("groups/{group-id}/description")
Observable<String> setGroupDescription(
@NonNull @Path("group-id") String groupId,
@NonNull @Body GroupDescriptionInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#delete-group-description"
*/
@DELETE("groups/{group-id}/description")
Observable<Void> deleteGroupDescription(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-options"
*/
@GET("groups/{group-id}/options")
Observable<GroupOptionsInfo> getGroupOptions(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#set-group-options"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("groups/{group-id}/options")
Observable<GroupOptionsInfo> setGroupOptions(
@NonNull @Path("group-id") String groupId,
@NonNull @Body GroupOptionsInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-owner"
*/
@GET("groups/{group-id}/owner")
Observable<GroupInfo> getGroupOwner(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#set-group-owner"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("groups/{group-id}/owner")
Observable<GroupInfo> setGroupOwner(
@NonNull @Path("group-id") String groupId,
@NonNull @Body GroupOwnerInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-audit-log"
*/
@GET("groups/{group-id}/log.audit")
Observable<List<GroupAuditEventInfo>> getGroupAuditLog(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#index-group"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("groups/{group-id}/index")
Observable<Void> indexGroup(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#group-members"
*/
@GET("groups/{group-id}/members/")
Observable<List<AccountInfo>> getGroupMembers(
@NonNull @Path("group-id") String groupId,
@Nullable @Query("recursive") Option recursive);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-group-member"
*/
@GET("groups/{group-id}/members/{account-id}")
Observable<AccountInfo> getGroupMember(
@NonNull @Path("group-id") String groupId,
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#add-group-member"
*/
@PUT("groups/{group-id}/members/{account-id}")
Observable<AccountInfo> addGroupMember(
@NonNull @Path("group-id") String groupId,
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#_add_group_members"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("groups/{group-id}/members.add")
Observable<List<AccountInfo>> addGroupMembers(
@NonNull @Path("group-id") String groupId,
@NonNull @Body MemberInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#remove-group-member"
*/
@DELETE("groups/{group-id}/members/{account-id}")
Observable<Void> deleteGroupMember(
@NonNull @Path("group-id") String groupId,
@NonNull @Path("account-id") String accountId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#remove-group-members"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("groups/{group-id}/members/members.delete")
Observable<Void> deleteGroupMembers(
@NonNull @Path("group-id") String groupId,
@NonNull @Body MemberInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#list-subgroups"
*/
@GET("groups/{group-id}/groups/")
Observable<List<GroupInfo>> getGroupSubgroups(@NonNull @Path("group-id") String groupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#get-subgroup"
*/
@GET("groups/{group-id}/groups/{subgroup-id}")
Observable<GroupInfo> getGroupSubgroup(
@NonNull @Path("group-id") String groupId,
@NonNull @Path("subgroup-id") String subgroupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#add-subgroup"
*/
@PUT("groups/{group-id}/groups/{subgroup-id}")
Observable<GroupInfo> addGroupSubgroup(
@NonNull @Path("group-id") String groupId,
@NonNull @Path("subgroup-id") String subgroupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#add-subgroups"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("groups/{group-id}/groups.add")
Observable<GroupInfo> addGroupSubgroups(
@NonNull @Path("group-id") String groupId,
@NonNull @Body SubgroupInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#remove-subgroup"
*/
@DELETE("groups/{group-id}/groups/{subgroup-id}")
Observable<Void> deleteGroupSubgroup(
@NonNull @Path("group-id") String groupId,
@NonNull @Path("subgroup-id") String subgroupId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-groups.html#remove-subgroups"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("groups/{group-id}/groups.delete")
Observable<Void> deleteGroupSubgroups(
@NonNull @Path("group-id") String groupId,
@NonNull @Body SubgroupInput input);
// ===============================
// Gerrit plugins endpoints
// @link "https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html"
// ===============================
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#list-plugins"
*/
@GET("plugins/")
Observable<Map<String, PluginInfo>> getPlugins(
@Nullable @Path("all") Option all,
@Nullable @Path("n") Integer count,
@Nullable @Path("S") Integer skip,
@Nullable @Path("p") String prefix,
@Nullable @Path("r") String regexp,
@Nullable @Path("m") String match);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#install-plugin"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("plugins/{plugin-id}")
Observable<PluginInfo> installPlugin(
@NonNull @Path("plugin-id") String pluginId,
@NonNull @Body PluginInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#get-plugin-status"
*/
@GET("plugins/{plugin-id}/gerrit~status")
Observable<PluginInfo> getPluginStatus(@NonNull @Path("plugin-id") String pluginId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#enable-plugin"
*/
@POST("plugins/{plugin-id}/gerrit~enable")
Observable<PluginInfo> enablePlugin(@NonNull @Path("plugin-id") String pluginId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#disable-plugin"
*/
@POST("plugins/{plugin-id}/gerrit~disable")
Observable<PluginInfo> disablePlugin(@NonNull @Path("plugin-id") String pluginId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-plugins.html#reload-plugin"
*/
@POST("plugins/{plugin-id}/gerrit~reload")
Observable<PluginInfo> reloadPlugin(@NonNull @Path("plugin-id") String pluginId);
// ===============================
// Gerrit projects endpoints
// @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html"
// ===============================
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-projects"
*/
@GET("projects/")
Observable<Map<String, ProjectInfo>> getProjects(
@Nullable @Query("n") Integer count,
@Nullable @Query("S") Integer start,
@Nullable @Query("p") String prefix,
@Nullable @Query("r") String regexp,
@Nullable @Query("m") String match,
@Nullable @Query("d") Option showDescription,
@Nullable @Query("t") Option showTree,
@Nullable @Query("b") String branch,
@Nullable @Query("type") ProjectType type,
@Nullable @Query("has-acl-for") String group,
@Nullable @Query("s") ProjectStatus state);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#query-projects"
*/
@GET("projects/")
Observable<List<ProjectInfo>> queryProjects(
@NonNull @Query("query") ProjectQuery query,
@Nullable @Query("n") Integer count,
@Nullable @Query("S") Integer start,
@Nullable @Query("p") String prefix,
@Nullable @Query("r") String regexp,
@Nullable @Query("m") String match,
@Nullable @Query("d") Option showDescription,
@Nullable @Query("t") Option showTree,
@Nullable @Query("b") String branch,
@Nullable @Query("type") ProjectType type,
@Nullable @Query("has-acl-for") String group,
@Nullable @Query("s") ProjectStatus state);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-project"
*/
@GET("projects/{project-name}")
Observable<ProjectInfo> getProject(@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-project"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("projects/{project-name}")
Observable<ProjectInfo> createProject(
@NonNull @Path("project-name") String name,
@NonNull @Body ProjectInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-project-description"
*/
@GET("projects/{project-name}/description")
Observable<String> getProjectDescription(@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-project-description"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("projects/{project-name}/description")
Observable<String> setProjectDescription(
@NonNull @Path("project-name") String name,
@NonNull @Body ProjectDescriptionInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-project-description"
*/
@DELETE("projects/{project-name}/description")
Observable<Void> deleteProjectDescription(@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-project-parent"
*/
@GET("projects/{project-name}/parent")
Observable<String> getProjectParent(@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-project-parent"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("projects/{project-name}/parent")
Observable<String> setProjectParent(
@NonNull @Path("project-name") String projectName,
@NonNull @Body ProjectParentInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head"
*/
@GET("projects/{project-name}/HEAD")
Observable<String> getProjectHead(@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("projects/{project-name}/HEAD")
Observable<String> setProjectHead(
@NonNull @Path("project-name") String projectName,
@NonNull @Body HeadInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-repository-statistics"
*/
@GET("projects/{project-name}/statistics.git")
Observable<RepositoryStatisticsInfo> getProjectStatistics(
@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-config"
*/
@GET("projects/{project-name}/config")
Observable<ConfigInfo> getProjectConfig(@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-config"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("projects/{project-name}/config")
Observable<ConfigInfo> setProjectConfig(
@NonNull @Path("project-name") String projectName,
@NonNull @Body ConfigInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#run-gc"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/gc")
Observable<ResponseBody> runProjectGc(
@NonNull @Path("project-name") String projectName,
@NonNull @Body GcInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#ban-commit"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/ban")
Observable<BanResultInfo> banProject(
@NonNull @Path("project-name") String projectName,
@NonNull @Body BanInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-access"
*/
@GET("projects/{project-name}/access")
Observable<ProjectAccessInfo> getProjectAccessRights(
@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-access"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/access")
Observable<ProjectAccessInfo> setProjectAccessRights(
@NonNull @Path("project-name") String projectName,
@NonNull @Body ProjectAccessInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-access-change"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/access:review")
Observable<ChangeInfo> createProjectAccessRightsChange(
@NonNull @Path("project-name") String projectName,
@NonNull @Body ProjectAccessInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#check-access"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@GET("projects/{project-name}/check.access")
Observable<AccessCheckInfo> getCheckProjectAccessRights(
@NonNull @Path("project-name") String projectName,
@Nullable @Query("account") String account,
@Nullable @Query("ref") String ref);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#check-access-post"
*/
@Deprecated
@SuppressWarnings("deprecation")
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/check.access")
Observable<AccessCheckInfo> postCheckProjectAccessRights(
@NonNull @Path("project-name") String projectName,
@NonNull @Body AccessCheckInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#index"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/index")
Observable<Void> indexProject(
@NonNull @Path("project-name") String projectName,
@NonNull @Body IndexProjectInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#index.changes"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/index.changes")
Observable<Void> indexProjectChanges(
@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#check"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/check")
Observable<CheckProjectResultInfo> checkProjectConsistency(
@NonNull @Path("project-name") String projectName,
@NonNull @Body CheckProjectInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-branches"
*/
@GET("projects/{project-name}/branches/")
Observable<List<BranchInfo>> getProjectBranches(
@NonNull @Path("project-name") String projectName,
@Nullable @Query("n") Integer count,
// Used by 2.14.3+
@Nullable @Query("S") Integer start,
// Used by 2.14.2-
@Nullable @Query("s") Integer _start,
@Nullable @Query("m") String m,
@Nullable @Query("r") String regexp);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch"
*/
@GET("projects/{project-name}/branches/{branch-id}")
Observable<BranchInfo> getProjectBranch(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("branch-id") String branchId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("projects/{project-name}/branches/{branch-id}")
Observable<BranchInfo> createProjectBranch(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("branch-id") String branchId,
@NonNull @Body BranchInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-branch"
*/
@DELETE("projects/{project-name}/branches/{branch-id}")
Observable<Void> deleteProjectBranch(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("branch-id") String branchId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-branches"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/branches/branches:delete")
Observable<Void> deleteProjectBranches(
@NonNull @Path("project-name") String projectName,
@NonNull @Body DeleteBranchesInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content"
*/
@GET("projects/{project-name}/branches/{branch-id}/files/{file-id}/content")
Observable<Base64Data> getProjectBranchFileContent(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("branch-id") String branchId,
@NonNull @Path("file-id") String fileId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-mergeable-info"
*/
@GET("projects/{project-name}/branches/{branch-id}/mergeable")
Observable<MergeableInfo> getProjectBranchMergeableStatus(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("branch-id") String branchId,
@NonNull @Query("source") String sourceBranchId,
@Nullable @Query("strategy") MergeStrategy strategy);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-reflog"
*/
@GET("projects/{project-name}/branches/{branch-id}/reflog")
Observable<List<ReflogEntryInfo>> getProjectBranchReflog(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("branch-id") String branchId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-child-projects"
*/
@GET("projects/{project-name}/children/")
Observable<List<ProjectInfo>> getProjectChildProjects(
@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-child-project"
*/
@GET("projects/{project-name}/children/{child-project-name}")
Observable<ProjectInfo> getProjectChildProject(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("child-project-name") String childProjectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-tags"
*/
@GET("projects/{project-name}/tags/")
Observable<List<TagInfo>> getProjectTags(
@NonNull @Path("project-name") String projectName,
@Nullable @Query("n") Integer count,
// Used by 2.14.3+
@Nullable @Query("S") Integer start,
// Used by 2.14.2-
@Nullable @Query("s") Integer _start,
@Nullable @Query("m") String m,
@Nullable @Query("r") String regexp);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-tag"
*/
@GET("projects/{project-name}/tags/{tag-id}")
Observable<TagInfo> getProjectTag(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("tag-id") String tagId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-tag"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/tags/{tag-id}")
Observable<TagInfo> createProjectTag(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("tag-id") String tagId,
@NonNull @Body TagInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-tag"
*/
@DELETE("projects/{project-name}/tags/{tag-id}")
Observable<Void> deleteProjectTag(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("tag-id") String tagId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-tags"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/tags:delete")
Observable<Void> deleteProjectTags(
@NonNull @Path("project-name") String projectName,
@NonNull @Body DeleteTagsInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-commit"
*/
@GET("projects/{project-name}/commits/{commit-id}")
Observable<CommitInfo> getProjectCommit(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("commit-id") String commitId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content-from-commit"
*/
@GET("projects/{project-name}/commits/{commit-id}/files/{file-id}/content")
Observable<Base64Data> getProjectCommitFileContent(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("commit-id") String commitId,
@NonNull @Path("file-id") String fileId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#cherry-pick-commit"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("projects/{project-name}/commits/{commit-id}/cherrypick")
Observable<CherryPickChangeInfo> cherryPickProjectCommit(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("commit-id") String commitId,
@NonNull @Body CherryPickInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-files"
*/
@GET("projects/{project-name}/commits/{commit-id}/files")
Observable<Map<String, FileInfo>> listProjectCommitFiles(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("commit-id") String commitId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#list-dashboards"
*/
@GET("projects/{project-name}/dashboards/")
Observable<List<DashboardInfo>> getProjectDashboards(
@NonNull @Path("project-name") String projectName);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-dashboard"
*/
@GET("projects/{project-name}/dashboards/{dashboard-id}")
Observable<DashboardInfo> getProjectDashboard(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("dashboard-id") String dashboardId);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-dashboard"
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-dashboard"
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#update-dashboard"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@PUT("projects/{project-name}/dashboards/{dashboard-id}")
Observable<DashboardInfo> createOrUpdateProjectDashboard(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("dashboard-id") String dashboardId,
@NonNull @Body DashboardInput input);
/**
* @link "https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#delete-dashboard"
*/
@DELETE("projects/{project-name}/dashboards/{dashboard-id}")
Observable<Void> deleteProjectDashboard(
@NonNull @Path("project-name") String projectName,
@NonNull @Path("dashboard-id") String dashboardId);
// ===============================
// Gerrit documentation endpoints
// @link "https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html"
// ===============================
/**
* @link "https://review.lineageos.org/Documentation/rest-api-documentation.html#search-documentation"
*/
@Headers({"X-Gerrit-Unauthenticated: true"})
@GET("Documentation/")
Observable<List<DocResult>> findDocumentation(@NonNull @Query("q") String keyword);
// ===============================
// Other endpoints
// ===============================
// -- Cloud Notifications Plugin --
// https://gerrit.googlesource.com/plugins/cloud-notifications/
/**
* @link "https://gerrit.googlesource.com/plugins/cloud-notifications/+/master/src/main/resources/Documentation/api.md#get-cloud-notifications-config"
*/
@GET("config/server/cloud-notifications")
Observable<CloudNotificationsConfigInfo> getCloudNotificationsConfig();
/**
* @link "https://gerrit.googlesource.com/plugins/cloud-notifications/+/master/src/main/resources/Documentation/api.md#list-cloud-notifications"
*/
@GET("accounts/{account-id}/devices/{device-id}/tokens")
Observable<List<CloudNotificationInfo>> listCloudNotifications(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("device-id") String deviceId);
/**
* @link "https://gerrit.googlesource.com/plugins/cloud-notifications/+/master/src/main/resources/Documentation/api.md#get-cloud-notification"
*/
@GET("accounts/{account-id}/devices/{device-id}/tokens/{token}")
Observable<CloudNotificationInfo> getCloudNotification(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("device-id") String deviceId,
@NonNull @Path("token") String token);
/**
* @link "https://gerrit.googlesource.com/plugins/cloud-notifications/+/master/src/main/resources/Documentation/api.md#register-cloud-notification"
*/
@Headers({"Content-Type: application/json; charset=UTF-8"})
@POST("accounts/{account-id}/devices/{device-id}/tokens")
Observable<CloudNotificationInfo> registerCloudNotification(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("device-id") String deviceId,
@NonNull @Body CloudNotificationInput input);
/**
* @link "https://gerrit.googlesource.com/plugins/cloud-notifications/+/master/src/main/resources/Documentation/api.md#unregister-cloud-notification"
*/
@DELETE("accounts/{account-id}/devices/{device-id}/tokens/{token}")
Observable<Void> unregisterCloudNotification(
@NonNull @Path("account-id") String accountId,
@NonNull @Path("device-id") String deviceId,
@NonNull @Path("token") String token);
}
|
|
/*******************************************************************************
* Copyright (c) 2013, SAP AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the SAP AG nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v3.0-03/04/2009 09:20 AM(valikov)-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.11.03 at 09:58:45 AM CET
//
package oasis.names.tc.xacml._2_0.context.schema.os;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.jvnet.jaxb2_commons.lang.HashCode;
import org.jvnet.jaxb2_commons.lang.ToString;
import org.jvnet.jaxb2_commons.lang.builder.JAXBEqualsBuilder;
import org.jvnet.jaxb2_commons.lang.builder.JAXBHashCodeBuilder;
import org.jvnet.jaxb2_commons.lang.builder.JAXBToStringBuilder;
/**
* <p>Java class for SubjectType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SubjectType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{urn:oasis:names:tc:xacml:2.0:context:schema:os}Attribute" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="SubjectCategory" type="{http://www.w3.org/2001/XMLSchema}anyURI" default="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SubjectType", propOrder = {
"attribute"
})
@Entity(name = "oasis.names.tc.xacml._2_0.context.schema.os.SubjectType")
@Table(name = "SUBJECTTYPE_0")
@Inheritance(strategy = InheritanceType.JOINED)
public class SubjectType
implements Serializable, Equals, HashCode, ToString
{
@XmlElement(name = "Attribute")
protected List<AttributeType> attribute;
@XmlAttribute(name = "SubjectCategory")
@XmlSchemaType(name = "anyURI")
protected String subjectCategory;
@XmlAttribute(name = "Hjid")
protected Long hjid;
/**
* Gets the value of the attribute property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the attribute property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAttribute().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AttributeType }
*
*
*/
@OneToMany(targetEntity = AttributeType.class, cascade = {
CascadeType.ALL
})
@JoinColumn(name = "ATTRIBUTE__SUBJECTTYPE_0_HJID")
public List<AttributeType> getAttribute() {
if (attribute == null) {
attribute = new ArrayList<AttributeType>();
}
return this.attribute;
}
/**
*
*
*/
public void setAttribute(List<AttributeType> attribute) {
this.attribute = attribute;
}
/**
* Gets the value of the subjectCategory property.
*
* @return
* possible object is
* {@link String }
*
*/
@Basic
@Column(name = "SUBJECTCATEGORY")
public String getSubjectCategory() {
if (subjectCategory == null) {
return "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject";
} else {
return subjectCategory;
}
}
/**
* Sets the value of the subjectCategory property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubjectCategory(String value) {
this.subjectCategory = value;
}
/**
* Gets the value of the hjid property.
*
* @return
* possible object is
* {@link Long }
*
*/
@Id
@Column(name = "HJID")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getHjid() {
return hjid;
}
/**
* Sets the value of the hjid property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setHjid(Long value) {
this.hjid = value;
}
public void equals(Object object, EqualsBuilder equalsBuilder) {
if (!(object instanceof SubjectType)) {
equalsBuilder.appendSuper(false);
return ;
}
if (this == object) {
return ;
}
final SubjectType that = ((SubjectType) object);
equalsBuilder.append(this.getAttribute(), that.getAttribute());
equalsBuilder.append(this.getSubjectCategory(), that.getSubjectCategory());
}
public boolean equals(Object object) {
if (!(object instanceof SubjectType)) {
return false;
}
if (this == object) {
return true;
}
final EqualsBuilder equalsBuilder = new JAXBEqualsBuilder();
equals(object, equalsBuilder);
return equalsBuilder.isEquals();
}
public void hashCode(HashCodeBuilder hashCodeBuilder) {
hashCodeBuilder.append(this.getAttribute());
hashCodeBuilder.append(this.getSubjectCategory());
}
public int hashCode() {
final HashCodeBuilder hashCodeBuilder = new JAXBHashCodeBuilder();
hashCode(hashCodeBuilder);
return hashCodeBuilder.toHashCode();
}
public void toString(ToStringBuilder toStringBuilder) {
{
List<AttributeType> theAttribute;
theAttribute = this.getAttribute();
toStringBuilder.append("attribute", theAttribute);
}
{
String theSubjectCategory;
theSubjectCategory = this.getSubjectCategory();
toStringBuilder.append("subjectCategory", theSubjectCategory);
}
}
public String toString() {
final ToStringBuilder toStringBuilder = new JAXBToStringBuilder(this);
toString(toStringBuilder);
return toStringBuilder.toString();
}
}
|
|
/*
* Copyright (c) 2012-2015 Andrei Popleteev.
* Licensed under the MIT license.
*/
package com.anmipo.android.trentobus.db;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.anmipo.android.trentobus.R;
public class ScheduleLegend {
// all available legend items
private static HashMap<String, ScheduleLegendItem> sAllItemsMap;
private static ScheduleLegendItem[] sItemsWithDescription;
static {
int index = 0;
sItemsWithDescription = new ScheduleLegendItem[11];
/*
* "Frequenza" items, those that are to be shown
* in the legend description.
*/
sItemsWithDescription[index++] = new ScheduleLegendItem("\u00DC",
R.string.freq_feriale_lunedi_a_venerdi,
R.drawable.freq_square_empty);
sItemsWithDescription[index++] = new ScheduleLegendItem("\u00DD",
R.string.freq_scolastica_lunedi_a_sabato,
R.drawable.freq_star);
sItemsWithDescription[index++] = new ScheduleLegendItem("\u00DE",
R.string.freq_scolastica_lunedi_a_venerdi,
R.drawable.freq_square_star);
sItemsWithDescription[index++] = new ScheduleLegendItem("\u00E1",
R.string.freq_feriale_solo_sabato,
R.drawable.freq_square_filled);
sItemsWithDescription[index++] = new ScheduleLegendItem("\u00E0",
R.string.freq_lun_ven_sospesa_0308_2808,
R.drawable.freq_square_half_filled);
sItemsWithDescription[index++] = new ScheduleLegendItem("X",
R.string.freq_romagnosi_canova_linea_7,
R.drawable.freq_circle_x);
sItemsWithDescription[index++] = new ScheduleLegendItem("W", // an arbitrary one-character replacement for "A" which is taken for bus
R.string.freq_funivia_sospesa_festivi,
R.drawable.freq_circle_a);
// Some special "Linea" items that have a description.
sItemsWithDescription[index++] = new ScheduleLegendItem("o",
R.string.freq_autonoleggiatore_privato,
R.drawable.linea_zero);
sItemsWithDescription[index++] = new ScheduleLegendItem("E",
R.string.freq_mezzo_extraurbano,
R.drawable.linea_extra);
sItemsWithDescription[index++] = new ScheduleLegendItem("fvb",
R.string.freq_funivia_bus,
R.drawable.linea_funivia_bus);
sItemsWithDescription[index++] = new ScheduleLegendItem("fvbc",
R.string.freq_funivia_bici,
R.drawable.linea_bike);
sAllItemsMap = new HashMap<String, ScheduleLegendItem>();
for (ScheduleLegendItem item: sItemsWithDescription) {
sAllItemsMap.put(item.key, item);
}
/*
* "Linea" items, those that are drawn,
* but are not listed in legend description.
*/
sAllItemsMap.put("1", new ScheduleLegendItem("1", R.drawable.linea_1));
sAllItemsMap.put("1/", new ScheduleLegendItem("1/", R.drawable.linea_1b));
sAllItemsMap.put("2", new ScheduleLegendItem("2", R.drawable.linea_2));
sAllItemsMap.put("2/", new ScheduleLegendItem("2/", R.drawable.linea_2b));
sAllItemsMap.put("3", new ScheduleLegendItem("3", R.drawable.linea_3));
sAllItemsMap.put("3/", new ScheduleLegendItem("3/", R.drawable.linea_3b));
sAllItemsMap.put("4", new ScheduleLegendItem("4", R.drawable.linea_4));
sAllItemsMap.put("4/", new ScheduleLegendItem("4/", R.drawable.linea_4b));
sAllItemsMap.put("5", new ScheduleLegendItem("5", R.drawable.linea_5));
sAllItemsMap.put("5/", new ScheduleLegendItem("5/", R.drawable.linea_5b));
sAllItemsMap.put("6", new ScheduleLegendItem("6", R.drawable.linea_6));
sAllItemsMap.put("6/", new ScheduleLegendItem("6/", R.drawable.linea_6b));
sAllItemsMap.put("7", new ScheduleLegendItem("7", R.drawable.linea_7));
sAllItemsMap.put("7/", new ScheduleLegendItem("7/", R.drawable.linea_7b));
sAllItemsMap.put("8", new ScheduleLegendItem("8", R.drawable.linea_8));
sAllItemsMap.put("8/", new ScheduleLegendItem("8/", R.drawable.linea_8b));
sAllItemsMap.put("9", new ScheduleLegendItem("9", R.drawable.linea_9));
sAllItemsMap.put("9/", new ScheduleLegendItem("9/", R.drawable.linea_9b));
sAllItemsMap.put("10", new ScheduleLegendItem("10", R.drawable.linea_10));
sAllItemsMap.put("10/", new ScheduleLegendItem("10/", R.drawable.linea_10b));
sAllItemsMap.put("11", new ScheduleLegendItem("11", R.drawable.linea_11));
sAllItemsMap.put("12", new ScheduleLegendItem("12", R.drawable.linea_12));
sAllItemsMap.put("13", new ScheduleLegendItem("13", R.drawable.linea_13));
sAllItemsMap.put("14", new ScheduleLegendItem("14", R.drawable.linea_14));
sAllItemsMap.put("15", new ScheduleLegendItem("15", R.drawable.linea_15));
sAllItemsMap.put("16", new ScheduleLegendItem("16", R.drawable.linea_16));
sAllItemsMap.put("17", new ScheduleLegendItem("17", R.drawable.linea_17));
sAllItemsMap.put("17/", new ScheduleLegendItem("17/", R.drawable.linea_17b));
sAllItemsMap.put("A", new ScheduleLegendItem("A", R.drawable.linea_a));
sAllItemsMap.put("A/", new ScheduleLegendItem("A/", R.drawable.linea_ab));
sAllItemsMap.put("B", new ScheduleLegendItem("B", R.drawable.linea_b));
sAllItemsMap.put("C", new ScheduleLegendItem("C", R.drawable.linea_c));
sAllItemsMap.put("D", new ScheduleLegendItem("D", R.drawable.linea_d));
sAllItemsMap.put("NP", new ScheduleLegendItem("NP", R.drawable.linea_np));
}
// items of this specific legend
private ScheduleLegendItem[] items;
protected ScheduleLegend(int size) {
items = new ScheduleLegendItem[size];
}
public static ScheduleLegend getInstance(String frequenza, String linea) {
int length = frequenza.length() +
((linea.length() > 0) ? 1 : 0);
ScheduleLegend legend = new ScheduleLegend(length);
// in "Frequenza" there can be several entries,
// each represented by one character
int index = 0;
for (int i = 0; i < frequenza.length(); i++) {
legend.setEntry(index, String.valueOf(frequenza.charAt(i)));
index++;
}
// in "Linea" there can be at most one entry,
// but a multicharacter one (like bus number 17 or NP)
if (linea.length() > 0) {
legend.setEntry(index, linea);
}
return legend;
}
private void setEntry(int index, String key) {
if (sAllItemsMap.containsKey(key)) {
items[index] = sAllItemsMap.get(key);
} else {
items[index] = ScheduleLegendItem.UNKNOWN;
}
}
public int getLength() {
return items.length;
}
public ScheduleLegendItem getItem(int index) {
return items[index];
}
/**
* Returns dimensions of the legend icons
* @return
*/
public static int getIconSize(Resources res) {
int result;
Drawable d = res.getDrawable(R.drawable.freq_unknown);
result = d.getIntrinsicHeight();
d = null;
return result;
}
/**
* Returns an adapter with the items of this legend which have description.
* @param context
* @return
*/
public Adapter getDescriptionsAdapter(Context context) {
ArrayList<ScheduleLegendItem> itemsWithDescription =
new ArrayList<ScheduleLegendItem>(items.length);
for (ScheduleLegendItem item: items) {
if (item.hasText()) {
itemsWithDescription.add(item);
}
}
return new Adapter(context, itemsWithDescription);
};
public static class Adapter extends ArrayAdapter<ScheduleLegendItem> {
int iconPadding;
public Adapter(Context context) {
super(context, R.layout.item_legend_item, R.id.text,
sItemsWithDescription);
setupLayout();
}
public Adapter(Context context, List<ScheduleLegendItem> items) {
super(context, R.layout.item_legend_item, R.id.text, items);
setupLayout();
}
private void setupLayout() {
DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
iconPadding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 10, dm);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Use super class to create the View
View v = super.getView(position, convertView, parent);
v.setClickable(false);
TextView textView = (TextView) v.findViewById(R.id.text);
ScheduleLegendItem legendItem = getItem(position);
textView.setText(legendItem.textId);
textView.setCompoundDrawablesWithIntrinsicBounds(
legendItem.iconId, 0, 0, 0);
textView.setCompoundDrawablePadding(iconPadding);
return v;
}
}
}
|
|
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1.stub;
import static com.google.cloud.compute.v1.GlobalOrganizationOperationsClient.ListPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.HttpJsonTransportChannel;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.PagedListDescriptor;
import com.google.api.gax.rpc.PagedListResponseFactory;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.compute.v1.DeleteGlobalOrganizationOperationRequest;
import com.google.cloud.compute.v1.DeleteGlobalOrganizationOperationResponse;
import com.google.cloud.compute.v1.GetGlobalOrganizationOperationRequest;
import com.google.cloud.compute.v1.ListGlobalOrganizationOperationsRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.OperationList;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
import org.threeten.bp.Duration;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link GlobalOrganizationOperationsStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (compute.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the total timeout of delete to 30 seconds:
*
* <pre>{@code
* GlobalOrganizationOperationsStubSettings.Builder globalOrganizationOperationsSettingsBuilder =
* GlobalOrganizationOperationsStubSettings.newBuilder();
* globalOrganizationOperationsSettingsBuilder
* .deleteSettings()
* .setRetrySettings(
* globalOrganizationOperationsSettingsBuilder
* .deleteSettings()
* .getRetrySettings()
* .toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30))
* .build());
* GlobalOrganizationOperationsStubSettings globalOrganizationOperationsSettings =
* globalOrganizationOperationsSettingsBuilder.build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class GlobalOrganizationOperationsStubSettings
extends StubSettings<GlobalOrganizationOperationsStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder()
.add("https://www.googleapis.com/auth/compute")
.add("https://www.googleapis.com/auth/cloud-platform")
.build();
private final UnaryCallSettings<
DeleteGlobalOrganizationOperationRequest, DeleteGlobalOrganizationOperationResponse>
deleteSettings;
private final UnaryCallSettings<GetGlobalOrganizationOperationRequest, Operation> getSettings;
private final PagedCallSettings<
ListGlobalOrganizationOperationsRequest, OperationList, ListPagedResponse>
listSettings;
private static final PagedListDescriptor<
ListGlobalOrganizationOperationsRequest, OperationList, Operation>
LIST_PAGE_STR_DESC =
new PagedListDescriptor<
ListGlobalOrganizationOperationsRequest, OperationList, Operation>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListGlobalOrganizationOperationsRequest injectToken(
ListGlobalOrganizationOperationsRequest payload, String token) {
return ListGlobalOrganizationOperationsRequest.newBuilder(payload)
.setPageToken(token)
.build();
}
@Override
public ListGlobalOrganizationOperationsRequest injectPageSize(
ListGlobalOrganizationOperationsRequest payload, int pageSize) {
return ListGlobalOrganizationOperationsRequest.newBuilder(payload)
.setMaxResults(pageSize)
.build();
}
@Override
public Integer extractPageSize(ListGlobalOrganizationOperationsRequest payload) {
return payload.getMaxResults();
}
@Override
public String extractNextToken(OperationList payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Operation> extractResources(OperationList payload) {
return payload.getItemsList() == null
? ImmutableList.<Operation>of()
: payload.getItemsList();
}
};
private static final PagedListResponseFactory<
ListGlobalOrganizationOperationsRequest, OperationList, ListPagedResponse>
LIST_PAGE_STR_FACT =
new PagedListResponseFactory<
ListGlobalOrganizationOperationsRequest, OperationList, ListPagedResponse>() {
@Override
public ApiFuture<ListPagedResponse> getFuturePagedResponse(
UnaryCallable<ListGlobalOrganizationOperationsRequest, OperationList> callable,
ListGlobalOrganizationOperationsRequest request,
ApiCallContext context,
ApiFuture<OperationList> futureResponse) {
PageContext<ListGlobalOrganizationOperationsRequest, OperationList, Operation>
pageContext = PageContext.create(callable, LIST_PAGE_STR_DESC, request, context);
return ListPagedResponse.createAsync(pageContext, futureResponse);
}
};
/** Returns the object with the settings used for calls to delete. */
public UnaryCallSettings<
DeleteGlobalOrganizationOperationRequest, DeleteGlobalOrganizationOperationResponse>
deleteSettings() {
return deleteSettings;
}
/** Returns the object with the settings used for calls to get. */
public UnaryCallSettings<GetGlobalOrganizationOperationRequest, Operation> getSettings() {
return getSettings;
}
/** Returns the object with the settings used for calls to list. */
public PagedCallSettings<
ListGlobalOrganizationOperationsRequest, OperationList, ListPagedResponse>
listSettings() {
return listSettings;
}
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public GlobalOrganizationOperationsStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonGlobalOrganizationOperationsStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return "compute.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "compute.mtls.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder()
.setScopesToApply(DEFAULT_SERVICE_SCOPES)
.setUseJwtAccessWithScope(true);
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingHttpJsonChannelProvider.Builder
defaultHttpJsonTransportProviderBuilder() {
return InstantiatingHttpJsonChannelProvider.newBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultHttpJsonTransportProviderBuilder().build();
}
@BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic",
GaxProperties.getLibraryVersion(GlobalOrganizationOperationsStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected GlobalOrganizationOperationsStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
deleteSettings = settingsBuilder.deleteSettings().build();
getSettings = settingsBuilder.getSettings().build();
listSettings = settingsBuilder.listSettings().build();
}
/** Builder for GlobalOrganizationOperationsStubSettings. */
public static class Builder
extends StubSettings.Builder<GlobalOrganizationOperationsStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final UnaryCallSettings.Builder<
DeleteGlobalOrganizationOperationRequest, DeleteGlobalOrganizationOperationResponse>
deleteSettings;
private final UnaryCallSettings.Builder<GetGlobalOrganizationOperationRequest, Operation>
getSettings;
private final PagedCallSettings.Builder<
ListGlobalOrganizationOperationsRequest, OperationList, ListPagedResponse>
listSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"no_retry_1_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
definitions.put(
"retry_policy_0_codes",
ImmutableSet.copyOf(
Lists.<StatusCode.Code>newArrayList(
StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE)));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRpcTimeout(Duration.ofMillis(600000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ofMillis(600000L))
.setTotalTimeout(Duration.ofMillis(600000L))
.build();
definitions.put("no_retry_1_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelay(Duration.ofMillis(60000L))
.setInitialRpcTimeout(Duration.ofMillis(600000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ofMillis(600000L))
.setTotalTimeout(Duration.ofMillis(600000L))
.build();
definitions.put("retry_policy_0_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
deleteSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
getSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
listSettings = PagedCallSettings.newBuilder(LIST_PAGE_STR_FACT);
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
deleteSettings, getSettings, listSettings);
initDefaults(this);
}
protected Builder(GlobalOrganizationOperationsStubSettings settings) {
super(settings);
deleteSettings = settings.deleteSettings.toBuilder();
getSettings = settings.getSettings.toBuilder();
listSettings = settings.listSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
deleteSettings, getSettings, listSettings);
}
private static Builder createDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setEndpoint(getDefaultEndpoint());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.deleteSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.getSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.listSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
return builder;
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to delete. */
public UnaryCallSettings.Builder<
DeleteGlobalOrganizationOperationRequest, DeleteGlobalOrganizationOperationResponse>
deleteSettings() {
return deleteSettings;
}
/** Returns the builder for the settings used for calls to get. */
public UnaryCallSettings.Builder<GetGlobalOrganizationOperationRequest, Operation>
getSettings() {
return getSettings;
}
/** Returns the builder for the settings used for calls to list. */
public PagedCallSettings.Builder<
ListGlobalOrganizationOperationsRequest, OperationList, ListPagedResponse>
listSettings() {
return listSettings;
}
@Override
public GlobalOrganizationOperationsStubSettings build() throws IOException {
return new GlobalOrganizationOperationsStubSettings(this);
}
}
}
|
|
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* 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.connectbot;
import java.lang.ref.WeakReference;
import java.util.List;
import org.connectbot.bean.SelectionArea;
import org.connectbot.service.PromptHelper;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalKeyListener;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.PreferenceConstants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import de.mud.terminal.vt320;
public class ConsoleActivity extends Activity {
public final static String TAG = "ConnectBot.ConsoleActivity";
protected static final int REQUEST_EDIT = 1;
private static final int CLICK_TIME = 400;
private static final float MAX_CLICK_DISTANCE = 25f;
private static final int KEYBOARD_DISPLAY_TIME = 1500;
// Direction to shift the ViewFlipper
private static final int SHIFT_LEFT = 0;
private static final int SHIFT_RIGHT = 1;
protected ViewFlipper flip = null;
protected TerminalManager bound = null;
protected LayoutInflater inflater = null;
private SharedPreferences prefs = null;
// determines whether or not menuitem accelerators are bound
// otherwise they collide with an external keyboard's CTRL-char
private boolean hardKeyboard = false;
protected Uri requested;
protected ClipboardManager clipboard;
private RelativeLayout stringPromptGroup;
protected EditText stringPrompt;
private TextView stringPromptInstructions;
private RelativeLayout booleanPromptGroup;
private TextView booleanPrompt;
private Button booleanYes, booleanNo;
private TextView empty;
private Animation slide_left_in, slide_left_out, slide_right_in, slide_right_out, fade_stay_hidden, fade_out_delayed;
private Animation keyboard_fade_in, keyboard_fade_out;
private float lastX, lastY;
private InputMethodManager inputManager;
private MenuItem disconnect, copy, paste, portForward, resize, urlscan, back;
protected TerminalBridge copySource = null;
private int lastTouchRow, lastTouchCol;
private boolean forcedOrientation;
private Handler handler = new Handler();
private ImageView mKeyboardButton;
private ActionBarWrapper actionBar;
private boolean inActionBarMenu = false;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// let manager know about our event handling services
bound.disconnectHandler = disconnectHandler;
Log.d(TAG, String.format("Connected to TerminalManager and found bridges.size=%d", bound.bridges.size()));
bound.setResizeAllowed(true);
// clear out any existing bridges and record requested index
flip.removeAllViews();
final String requestedNickname = (requested != null) ? requested.getFragment() : null;
int requestedIndex = 0;
TerminalBridge requestedBridge = bound.getConnectedBridge(requestedNickname);
// If we didn't find the requested connection, try opening it
if (requestedNickname != null && requestedBridge == null) {
try {
Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s), so creating one now", requested.toString(), requestedNickname));
requestedBridge = bound.openConnection(requested);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
}
}
// create views for all bridges on this service
for (TerminalBridge bridge : bound.bridges) {
final int currentIndex = addNewTerminalView(bridge);
// check to see if this bridge was requested
if (bridge == requestedBridge)
requestedIndex = currentIndex;
}
setDisplayedTerminal(requestedIndex);
}
public void onServiceDisconnected(ComponentName className) {
// tell each bridge to forget about our prompt handler
synchronized (bound.bridges) {
for(TerminalBridge bridge : bound.bridges)
bridge.promptHelper.setHandler(null);
}
flip.removeAllViews();
updateEmptyVisible();
bound = null;
}
};
protected Handler promptHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// someone below us requested to display a prompt
updatePromptVisible();
}
};
protected Handler disconnectHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "Someone sending HANDLE_DISCONNECT to parentHandler");
// someone below us requested to display a password dialog
// they are sending nickname and requested
TerminalBridge bridge = (TerminalBridge)msg.obj;
if (bridge.isAwaitingClose())
closeBridge(bridge);
}
};
/**
* @param bridge
*/
private void closeBridge(final TerminalBridge bridge) {
synchronized (flip) {
final int flipIndex = getFlipIndex(bridge);
if (flipIndex >= 0) {
if (flip.getDisplayedChild() == flipIndex) {
shiftCurrentTerminal(SHIFT_LEFT);
}
flip.removeViewAt(flipIndex);
/* TODO Remove this workaround when ViewFlipper is fixed to listen
* to view removals. Android Issue 1784
*/
final int numChildren = flip.getChildCount();
if (flip.getDisplayedChild() >= numChildren &&
numChildren > 0) {
flip.setDisplayedChild(numChildren - 1);
}
updateEmptyVisible();
}
// If we just closed the last bridge, go back to the previous activity.
if (flip.getChildCount() == 0) {
finish();
}
}
}
protected View findCurrentView(int id) {
View view = flip.getCurrentView();
if(view == null) return null;
return view.findViewById(id);
}
protected PromptHelper getCurrentPromptHelper() {
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return null;
return ((TerminalView)view).bridge.promptHelper;
}
protected void hideAllPrompts() {
stringPromptGroup.setVisibility(View.GONE);
booleanPromptGroup.setVisibility(View.GONE);
}
// more like configureLaxMode -- enable network IO on UI thread
private void configureStrictMode() {
try {
Class.forName("android.os.StrictMode");
StrictModeSetup.run();
} catch (ClassNotFoundException e) {
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
configureStrictMode();
hardKeyboard = getResources().getConfiguration().keyboard ==
Configuration.KEYBOARD_QWERTY;
hardKeyboard = hardKeyboard && !Build.MODEL.startsWith("Transformer ");
this.setContentView(R.layout.act_console);
clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// hide status bar if requested by user
if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false)) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
// TODO find proper way to disable volume key beep if it exists.
setVolumeControlStream(AudioManager.STREAM_MUSIC);
// handle requested console from incoming intent
requested = getIntent().getData();
inflater = LayoutInflater.from(this);
flip = (ViewFlipper)findViewById(R.id.console_flip);
empty = (TextView)findViewById(android.R.id.empty);
stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group);
stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions);
stringPrompt = (EditText)findViewById(R.id.console_password);
stringPrompt.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_UP) return false;
if(keyCode != KeyEvent.KEYCODE_ENTER) return false;
// pass collected password down to current terminal
String value = stringPrompt.getText().toString();
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return false;
helper.setResponse(value);
// finally clear password for next user
stringPrompt.setText("");
updatePromptVisible();
return true;
}
});
booleanPromptGroup = (RelativeLayout) findViewById(R.id.console_boolean_group);
booleanPrompt = (TextView)findViewById(R.id.console_prompt);
booleanYes = (Button)findViewById(R.id.console_prompt_yes);
booleanYes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return;
helper.setResponse(Boolean.TRUE);
updatePromptVisible();
}
});
booleanNo = (Button)findViewById(R.id.console_prompt_no);
booleanNo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PromptHelper helper = getCurrentPromptHelper();
if(helper == null) return;
helper.setResponse(Boolean.FALSE);
updatePromptVisible();
}
});
// preload animations for terminal switching
slide_left_in = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
slide_left_out = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
slide_right_in = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
slide_right_out = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed);
fade_stay_hidden = AnimationUtils.loadAnimation(this, R.anim.fade_stay_hidden);
// Preload animation for keyboard button
keyboard_fade_in = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_in);
keyboard_fade_out = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_out);
inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
final RelativeLayout keyboardGroup = (RelativeLayout) findViewById(R.id.keyboard_group);
mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard);
mKeyboardButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null)
return;
inputManager.showSoftInput(flip, InputMethodManager.SHOW_FORCED);
keyboardGroup.setVisibility(View.GONE);
actionBar.hide();
}
});
final ImageView ctrlButton = (ImageView) findViewById(R.id.button_ctrl);
ctrlButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.metaPress(TerminalKeyListener.META_CTRL_ON);
keyboardGroup.setVisibility(View.GONE);
actionBar.hide();
}
});
final ImageView escButton = (ImageView) findViewById(R.id.button_esc);
escButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.sendEscape();
keyboardGroup.setVisibility(View.GONE);
actionBar.hide();
}
});
actionBar = ActionBarWrapper.getActionBar(this);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.hide();
actionBar.addOnMenuVisibilityListener(new ActionBarWrapper.OnMenuVisibilityListener() {
public void onMenuVisibilityChanged(boolean isVisible) {
inActionBarMenu = isVisible;
if (isVisible == false) {
keyboardGroup.setVisibility(View.GONE);
actionBar.hide();
}
}
});
// detect fling gestures to switch between terminals
final GestureDetector detect = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
private float totalY = 0;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
final float distx = e2.getRawX() - e1.getRawX();
final float disty = e2.getRawY() - e1.getRawY();
final int goalwidth = flip.getWidth() / 2;
// need to slide across half of display to trigger console change
// make sure user kept a steady hand horizontally
if (Math.abs(disty) < (flip.getHeight() / 4)) {
if (distx > goalwidth) {
shiftCurrentTerminal(SHIFT_RIGHT);
return true;
}
if (distx < -goalwidth) {
shiftCurrentTerminal(SHIFT_LEFT);
return true;
}
}
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// if copying, then ignore
if (copySource != null && copySource.isSelectingForCopy())
return false;
if (e1 == null || e2 == null)
return false;
// if releasing then reset total scroll
if (e2.getAction() == MotionEvent.ACTION_UP) {
totalY = 0;
}
// activate consider if within x tolerance
if (Math.abs(e1.getX() - e2.getX()) < ViewConfiguration.getTouchSlop() * 4) {
View flip = findCurrentView(R.id.console_flip);
if(flip == null) return false;
TerminalView terminal = (TerminalView)flip;
// estimate how many rows we have scrolled through
// accumulate distance that doesn't trigger immediate scroll
totalY += distanceY;
final int moved = (int)(totalY / terminal.bridge.charHeight);
// consume as scrollback only if towards right half of screen
if (e2.getX() > flip.getWidth() / 2) {
if (moved != 0) {
int base = terminal.bridge.buffer.getWindowBase();
terminal.bridge.buffer.setWindowBase(base + moved);
totalY = 0;
return true;
}
} else {
// otherwise consume as pgup/pgdown for every 5 lines
if (moved > 5) {
((vt320)terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_DOWN, ' ', 0);
terminal.bridge.tryKeyVibrate();
totalY = 0;
return true;
} else if (moved < -5) {
((vt320)terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_UP, ' ', 0);
terminal.bridge.tryKeyVibrate();
totalY = 0;
return true;
}
}
}
return false;
}
});
flip.setLongClickable(true);
flip.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// when copying, highlight the area
if (copySource != null && copySource.isSelectingForCopy()) {
int row = (int)Math.floor(event.getY() / copySource.charHeight);
int col = (int)Math.floor(event.getX() / copySource.charWidth);
SelectionArea area = copySource.getSelectionArea();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
// recording starting area
if (area.isSelectingOrigin()) {
area.setRow(row);
area.setColumn(col);
lastTouchRow = row;
lastTouchCol = col;
copySource.redraw();
}
return true;
case MotionEvent.ACTION_MOVE:
/* ignore when user hasn't moved since last time so
* we can fine-tune with directional pad
*/
if (row == lastTouchRow && col == lastTouchCol)
return true;
// if the user moves, start the selection for other corner
area.finishSelectingOrigin();
// update selected area
area.setRow(row);
area.setColumn(col);
lastTouchRow = row;
lastTouchCol = col;
copySource.redraw();
return true;
case MotionEvent.ACTION_UP:
/* If they didn't move their finger, maybe they meant to
* select the rest of the text with the directional pad.
*/
if (area.getLeft() == area.getRight() &&
area.getTop() == area.getBottom()) {
return true;
}
// copy selected area to clipboard
String copiedText = area.copyFrom(copySource.buffer);
clipboard.setText(copiedText);
Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_done, copiedText.length()), Toast.LENGTH_LONG).show();
// fall through to clear state
case MotionEvent.ACTION_CANCEL:
// make sure we clear any highlighted area
area.reset();
copySource.setSelectingForCopy(false);
copySource.redraw();
return true;
}
}
Configuration config = getResources().getConfiguration();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
lastX = event.getX();
lastY = event.getY();
} else if (event.getAction() == MotionEvent.ACTION_UP
&& keyboardGroup.getVisibility() == View.GONE
&& event.getEventTime() - event.getDownTime() < CLICK_TIME
&& Math.abs(event.getX() - lastX) < MAX_CLICK_DISTANCE
&& Math.abs(event.getY() - lastY) < MAX_CLICK_DISTANCE) {
keyboardGroup.startAnimation(keyboard_fade_in);
keyboardGroup.setVisibility(View.VISIBLE);
actionBar.show();
handler.postDelayed(new Runnable() {
public void run() {
if (keyboardGroup.getVisibility() == View.GONE || inActionBarMenu)
return;
keyboardGroup.startAnimation(keyboard_fade_out);
keyboardGroup.setVisibility(View.GONE);
actionBar.hide();
}
}, KEYBOARD_DISPLAY_TIME);
}
// pass any touch events back to detector
return detect.onTouchEvent(event);
}
});
}
@Override
public void onBackPressed() {
// See if the user wants to make the back button send an Esc
if (prefs.getBoolean(PreferenceConstants.BACKBTN, false)) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.sendEscape();
} else {
super.onBackPressed();
}
}
/**
*
*/
private void configureOrientation() {
String rotateDefault;
if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_NOKEYS)
rotateDefault = PreferenceConstants.ROTATION_PORTRAIT;
else
rotateDefault = PreferenceConstants.ROTATION_LANDSCAPE;
String rotate = prefs.getString(PreferenceConstants.ROTATION, rotateDefault);
if (PreferenceConstants.ROTATION_DEFAULT.equals(rotate))
rotate = rotateDefault;
// request a forced orientation if requested by user
if (PreferenceConstants.ROTATION_LANDSCAPE.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
forcedOrientation = true;
} else if (PreferenceConstants.ROTATION_PORTRAIT.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
forcedOrientation = true;
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
forcedOrientation = false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
View view = findCurrentView(R.id.console_flip);
final boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
}
menu.setQwertyMode(true);
back = menu.add(R.string.list_host_back);
if (hardKeyboard)
back.setAlphabeticShortcut('b');
back.setEnabled(activeTerminal);
back.setIcon(android.R.drawable.ic_menu_revert);
back.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// back
finish();
return true;
}
});
disconnect = menu.add(R.string.list_host_disconnect);
if (hardKeyboard)
disconnect.setAlphabeticShortcut('w');
if (!sessionOpen && disconnected)
disconnect.setTitle(R.string.console_menu_close);
disconnect.setEnabled(activeTerminal);
disconnect.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
disconnect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// disconnect or close the currently visible session
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
bridge.dispatchDisconnect(true);
return true;
}
});
copy = menu.add(R.string.console_menu_copy);
if (hardKeyboard)
copy.setAlphabeticShortcut('c');
copy.setIcon(android.R.drawable.ic_menu_set_as);
copy.setEnabled(activeTerminal);
copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// mark as copying and reset any previous bounds
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
copySource = terminalView.bridge;
SelectionArea area = copySource.getSelectionArea();
area.reset();
area.setBounds(copySource.buffer.getColumns(), copySource.buffer.getRows());
copySource.setSelectingForCopy(true);
// Make sure we show the initial selection
copySource.redraw();
Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_start), Toast.LENGTH_LONG).show();
return true;
}
});
paste = menu.add(R.string.console_menu_paste);
if (hardKeyboard)
paste.setAlphabeticShortcut('v');
paste.setIcon(android.R.drawable.ic_menu_edit);
paste.setEnabled(clipboard.hasText() && sessionOpen);
paste.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// force insert of clipboard text into current console
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
// pull string from clipboard and generate all events to force down
String clip = clipboard.getText().toString();
bridge.injectString(clip);
return true;
}
});
portForward = menu.add(R.string.console_menu_portforwards);
if (hardKeyboard)
portForward.setAlphabeticShortcut('f');
portForward.setIcon(android.R.drawable.ic_menu_manage);
portForward.setEnabled(sessionOpen && canForwardPorts);
portForward.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
Intent intent = new Intent(ConsoleActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, bridge.host.getId());
ConsoleActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
urlscan = menu.add(R.string.console_menu_urlscan);
if (hardKeyboard)
urlscan.setAlphabeticShortcut('u');
urlscan.setIcon(android.R.drawable.ic_menu_search);
urlscan.setEnabled(activeTerminal);
urlscan.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
List<String> urls = terminalView.bridge.scanForURLs();
Dialog urlDialog = new Dialog(ConsoleActivity.this);
urlDialog.setTitle(R.string.console_menu_urlscan);
ListView urlListView = new ListView(ConsoleActivity.this);
URLItemListener urlListener = new URLItemListener(ConsoleActivity.this);
urlListView.setOnItemClickListener(urlListener);
urlListView.setAdapter(new ArrayAdapter<String>(ConsoleActivity.this, android.R.layout.simple_list_item_1, urls));
urlDialog.setContentView(urlListView);
urlDialog.show();
return true;
}
});
resize = menu.add(R.string.console_menu_resize);
if (hardKeyboard)
resize.setAlphabeticShortcut('s');
resize.setIcon(android.R.drawable.ic_menu_crop);
resize.setEnabled(sessionOpen);
resize.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
final View resizeView = inflater.inflate(R.layout.dia_resize, null, false);
new AlertDialog.Builder(ConsoleActivity.this)
.setView(resizeView)
.setPositiveButton(R.string.button_resize, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
int width, height;
try {
width = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.width))
.getText().toString());
height = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.height))
.getText().toString());
} catch (NumberFormatException nfe) {
// TODO change this to a real dialog where we can
// make the input boxes turn red to indicate an error.
return;
}
terminalView.forceSize(width, height);
}
}).setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);
final View view = findCurrentView(R.id.console_flip);
boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
}
disconnect.setEnabled(activeTerminal);
if (sessionOpen || !disconnected)
disconnect.setTitle(R.string.list_host_disconnect);
else
disconnect.setTitle(R.string.console_menu_close);
copy.setEnabled(activeTerminal);
paste.setEnabled(clipboard.hasText() && sessionOpen);
portForward.setEnabled(sessionOpen && canForwardPorts);
urlscan.setEnabled(activeTerminal);
resize.setEnabled(sessionOpen);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, HostListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onOptionsMenuClosed(Menu menu) {
super.onOptionsMenuClosed(menu);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
@Override
public void onStart() {
super.onStart();
// connect with manager service to find all bridges
// when connected it will insert all views
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause called");
if (forcedOrientation && bound != null)
bound.setResizeAllowed(false);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume called");
// Make sure we don't let the screen fall asleep.
// This also keeps the Wi-Fi chipset from disconnecting us.
if (prefs.getBoolean(PreferenceConstants.KEEP_ALIVE, true)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
configureOrientation();
if (forcedOrientation && bound != null)
bound.setResizeAllowed(true);
}
/* (non-Javadoc)
* @see android.app.Activity#onNewIntent(android.content.Intent)
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "onNewIntent called");
requested = intent.getData();
if (requested == null) {
Log.e(TAG, "Got null intent data in onNewIntent()");
return;
}
if (bound == null) {
Log.e(TAG, "We're not bound in onNewIntent()");
return;
}
TerminalBridge requestedBridge = bound.getConnectedBridge(requested.getFragment());
int requestedIndex = 0;
synchronized (flip) {
if (requestedBridge == null) {
// If we didn't find the requested connection, try opening it
try {
Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s),"+
"so creating one now", requested.toString(), requested.getFragment()));
requestedBridge = bound.openConnection(requested);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
// TODO: We should display an error dialog here.
return;
}
requestedIndex = addNewTerminalView(requestedBridge);
} else {
final int flipIndex = getFlipIndex(requestedBridge);
if (flipIndex > requestedIndex) {
requestedIndex = flipIndex;
}
}
setDisplayedTerminal(requestedIndex);
}
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
}
protected void shiftCurrentTerminal(final int direction) {
View overlay;
synchronized (flip) {
boolean shouldAnimate = flip.getChildCount() > 1;
// Only show animation if there is something else to go to.
if (shouldAnimate) {
// keep current overlay from popping up again
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_stay_hidden);
if (direction == SHIFT_LEFT) {
flip.setInAnimation(slide_left_in);
flip.setOutAnimation(slide_left_out);
flip.showNext();
} else if (direction == SHIFT_RIGHT) {
flip.setInAnimation(slide_right_in);
flip.setOutAnimation(slide_right_out);
flip.showPrevious();
}
}
ConsoleActivity.this.updateDefault();
if (shouldAnimate) {
// show overlay on new slide and start fade
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_out_delayed);
}
updatePromptVisible();
}
}
/**
* Save the currently shown {@link TerminalView} as the default. This is
* saved back down into {@link TerminalManager} where we can read it again
* later.
*/
private void updateDefault() {
// update the current default terminal
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return;
TerminalView terminal = (TerminalView)view;
if(bound == null) return;
bound.defaultBridge = terminal.bridge;
}
protected void updateEmptyVisible() {
// update visibility of empty status message
empty.setVisibility((flip.getChildCount() == 0) ? View.VISIBLE : View.GONE);
}
/**
* Show any prompts requested by the currently visible {@link TerminalView}.
*/
protected void updatePromptVisible() {
// check if our currently-visible terminalbridge is requesting any prompt services
View view = findCurrentView(R.id.console_flip);
// Hide all the prompts in case a prompt request was canceled
hideAllPrompts();
if(!(view instanceof TerminalView)) {
// we dont have an active view, so hide any prompts
return;
}
PromptHelper prompt = ((TerminalView)view).bridge.promptHelper;
if(String.class.equals(prompt.promptRequested)) {
stringPromptGroup.setVisibility(View.VISIBLE);
String instructions = prompt.promptInstructions;
if (instructions != null && instructions.length() > 0) {
stringPromptInstructions.setVisibility(View.VISIBLE);
stringPromptInstructions.setText(instructions);
} else
stringPromptInstructions.setVisibility(View.GONE);
stringPrompt.setText("");
stringPrompt.setHint(prompt.promptHint);
stringPrompt.requestFocus();
} else if(Boolean.class.equals(prompt.promptRequested)) {
booleanPromptGroup.setVisibility(View.VISIBLE);
booleanPrompt.setText(prompt.promptHint);
booleanYes.requestFocus();
} else {
hideAllPrompts();
view.requestFocus();
}
}
private class URLItemListener implements OnItemClickListener {
private WeakReference<Context> contextRef;
URLItemListener(Context context) {
this.contextRef = new WeakReference<Context>(context);
}
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Context context = contextRef.get();
if (context == null)
return;
try {
TextView urlView = (TextView) view;
String url = urlView.getText().toString();
if (url.indexOf("://") < 0)
url = "http://" + url;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "couldn't open URL", e);
// We should probably tell the user that we couldn't find a handler...
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, String.format("onConfigurationChanged; requestedOrientation=%d, newConfig.orientation=%d", getRequestedOrientation(), newConfig.orientation));
if (bound != null) {
if (forcedOrientation &&
(newConfig.orientation != Configuration.ORIENTATION_LANDSCAPE &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) ||
(newConfig.orientation != Configuration.ORIENTATION_PORTRAIT &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT))
bound.setResizeAllowed(false);
else
bound.setResizeAllowed(true);
bound.hardKeyboardHidden = (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES);
mKeyboardButton.setVisibility(bound.hardKeyboardHidden ? View.VISIBLE : View.GONE);
}
}
/**
* Adds a new TerminalBridge to the current set of views in our ViewFlipper.
*
* @param bridge TerminalBridge to add to our ViewFlipper
* @return the child index of the new view in the ViewFlipper
*/
private int addNewTerminalView(TerminalBridge bridge) {
// let them know about our prompt handler services
bridge.promptHelper.setHandler(promptHandler);
// inflate each terminal view
RelativeLayout view = (RelativeLayout)inflater.inflate(R.layout.item_terminal, flip, false);
// set the terminal overlay text
TextView overlay = (TextView)view.findViewById(R.id.terminal_overlay);
overlay.setText(bridge.host.getNickname());
// and add our terminal view control, using index to place behind overlay
TerminalView terminal = new TerminalView(ConsoleActivity.this, bridge);
terminal.setId(R.id.console_flip);
view.addView(terminal, 0);
synchronized (flip) {
// finally attach to the flipper
flip.addView(view);
return flip.getChildCount() - 1;
}
}
private int getFlipIndex(TerminalBridge bridge) {
synchronized (flip) {
final int children = flip.getChildCount();
for (int i = 0; i < children; i++) {
final View view = flip.getChildAt(i).findViewById(R.id.console_flip);
if (view == null || !(view instanceof TerminalView)) {
// How did that happen?
continue;
}
final TerminalView tv = (TerminalView) view;
if (tv.bridge == bridge) {
return i;
}
}
}
return -1;
}
/**
* Displays the child in the ViewFlipper at the requestedIndex and updates the prompts.
*
* @param requestedIndex the index of the terminal view to display
*/
private void setDisplayedTerminal(int requestedIndex) {
synchronized (flip) {
try {
// show the requested bridge if found, also fade out overlay
flip.setDisplayedChild(requestedIndex);
flip.getCurrentView().findViewById(R.id.terminal_overlay)
.startAnimation(fade_out_delayed);
} catch (NullPointerException npe) {
Log.d(TAG, "View went away when we were about to display it", npe);
}
updatePromptVisible();
updateEmptyVisible();
}
}
}
|
|
package com.khmelenko.lab.varis.viewmodel;
import com.khmelenko.lab.varis.BuildConfig;
import com.khmelenko.lab.varis.RxJavaRules;
import com.khmelenko.lab.varis.auth.AuthPresenter;
import com.khmelenko.lab.varis.dagger.DaggerTestComponent;
import com.khmelenko.lab.varis.dagger.TestComponent;
import com.khmelenko.lab.varis.network.request.AccessTokenRequest;
import com.khmelenko.lab.varis.network.request.AuthorizationRequest;
import com.khmelenko.lab.varis.network.response.AccessToken;
import com.khmelenko.lab.varis.network.response.Authorization;
import com.khmelenko.lab.varis.network.retrofit.github.GitHubRestClient;
import com.khmelenko.lab.varis.network.retrofit.github.GithubApiService;
import com.khmelenko.lab.varis.network.retrofit.travis.TravisRestClient;
import com.khmelenko.lab.varis.storage.AppSettings;
import com.khmelenko.lab.varis.util.EncryptionUtils;
import com.khmelenko.lab.varis.auth.AuthView;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import javax.inject.Inject;
import io.reactivex.Single;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
import retrofit2.Response;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Testing {@link AuthPresenter}
*
* @author Dmytro Khmelenko ([email protected])
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class TestAuthPresenter {
@Rule
public RxJavaRules mRxJavaRules = new RxJavaRules();
@Inject
TravisRestClient mTravisRestClient;
@Inject
GitHubRestClient mGitHubRestClient;
@Inject
AppSettings mAppSettings;
private AuthPresenter mAuthPresenter;
private AuthView mAuthView;
@Before
public void setup() {
TestComponent component = DaggerTestComponent.builder().build();
component.inject(this);
mAuthPresenter = spy(new AuthPresenter(mTravisRestClient, mGitHubRestClient, mAppSettings));
mAuthView = mock(AuthView.class);
mAuthPresenter.attach(mAuthView);
}
@Test
public void testUpdateServer() {
final String newEndpoint = "newEndpoint";
mAuthPresenter.updateServer(newEndpoint);
verify(mTravisRestClient).updateTravisEndpoint(newEndpoint);
}
@Test
public void testLoginSuccess() {
final String login = "login";
final String password = "password";
String auth = EncryptionUtils.generateBasicAuthorization(login, password);
final String gitHubToken = "gitHubToken";
Authorization authorization = new Authorization();
authorization.setToken(gitHubToken);
authorization.setId(1L);
when(mGitHubRestClient.getApiService().createNewAuthorization(eq(auth), any(AuthorizationRequest.class)))
.thenReturn(Single.just(authorization));
final String accessToken = "token";
AccessTokenRequest request = new AccessTokenRequest();
request.setGithubToken(gitHubToken);
AccessToken token = new AccessToken();
token.setAccessToken(accessToken);
when(mTravisRestClient.getApiService().auth(request)).thenReturn(Single.just(token));
when(mGitHubRestClient.getApiService().deleteAuthorization(auth, String.valueOf(authorization.getId())))
.thenReturn(null);
mAuthPresenter.login(login, password);
verify(mAuthView).hideProgress();
verify(mAuthView).finishView();
}
@Test
public void testLoginGitHubAuthFailed() {
final String login = "login";
final String password = "password";
String auth = EncryptionUtils.generateBasicAuthorization(login, password);
final String errorMsg = "error";
Exception exception = new Exception(errorMsg);
when(mGitHubRestClient.getApiService().createNewAuthorization(eq(auth), any(AuthorizationRequest.class)))
.thenReturn(Single.error(exception));
mAuthPresenter.login(login, password);
verify(mAuthView).hideProgress();
verify(mAuthView).showErrorMessage(errorMsg);
}
@Test
public void testLoginAuthFailed() {
final String login = "login";
final String password = "password";
String auth = EncryptionUtils.generateBasicAuthorization(login, password);
final String gitHubToken = "gitHubToken";
Authorization authorization = new Authorization();
authorization.setToken(gitHubToken);
authorization.setId(1L);
when(mGitHubRestClient.getApiService().createNewAuthorization(eq(auth), any(AuthorizationRequest.class)))
.thenReturn(Single.just(authorization));
AccessTokenRequest request = new AccessTokenRequest();
request.setGithubToken(gitHubToken);
final String errorMsg = "error";
Exception exception = new Exception(errorMsg);
when(mTravisRestClient.getApiService().auth(request)).thenReturn(Single.error(exception));
mAuthPresenter.login(login, password);
verify(mAuthView).hideProgress();
verify(mAuthView).showErrorMessage(errorMsg);
}
@Test
public void testTwoFactorAuth() {
final String login = "login";
final String password = "password";
String auth = EncryptionUtils.generateBasicAuthorization(login, password);
// rules for throwing a request for 2-factor auth
final String expectedUrl = "https://sample.org";
Request rawRequest = new Request.Builder()
.url(expectedUrl)
.build();
okhttp3.Response rawResponse = new okhttp3.Response.Builder()
.request(rawRequest)
.message("no body")
.protocol(Protocol.HTTP_1_1)
.code(401)
.header(GithubApiService.TWO_FACTOR_HEADER, "required")
.build();
Response response = Response.error(ResponseBody.create(null, ""), rawResponse);
HttpException exception = new HttpException(response);
when(mGitHubRestClient.getApiService().createNewAuthorization(eq(auth), any(AuthorizationRequest.class)))
.thenReturn(Single.error(exception));
mAuthPresenter.login(login, password);
verify(mAuthView).showTwoFactorAuth();
// rules for handling 2-factor auth continuation
final String securityCode = "123456";
final String gitHubToken = "gitHubToken";
Authorization authorization = new Authorization();
authorization.setToken(gitHubToken);
authorization.setId(1L);
when(mGitHubRestClient.getApiService().createNewAuthorization(eq(auth), eq(securityCode), any(AuthorizationRequest.class)))
.thenReturn(Single.just(authorization));
final String accessToken = "token";
AccessTokenRequest request = new AccessTokenRequest();
request.setGithubToken(gitHubToken);
AccessToken token = new AccessToken();
token.setAccessToken(accessToken);
when(mTravisRestClient.getApiService().auth(request)).thenReturn(Single.just(token));
when(mGitHubRestClient.getApiService().deleteAuthorization(auth, String.valueOf(authorization.getId())))
.thenReturn(null);
mAuthPresenter.twoFactorAuth(securityCode);
verify(mAuthView, times(2)).hideProgress();
verify(mAuthView).finishView();
}
}
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import android.os.ConditionVariable;
import android.os.ParcelFileDescriptor;
import android.os.StrictMode;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.base.test.util.Feature;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
/** Test the default provided implementations of {@link UploadDataProvider} */
public class UploadDataProvidersTest extends CronetTestBase {
private static final String LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+ "Proin elementum, libero laoreet fringilla faucibus, metus tortor vehicula ante, "
+ "lacinia lorem eros vel sapien.";
private CronetTestFramework mTestFramework;
private File mFile;
private StrictMode.VmPolicy mOldVmPolicy;
@Override
protected void setUp() throws Exception {
super.setUp();
mOldVmPolicy = StrictMode.getVmPolicy();
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
mTestFramework = startCronetTestFramework();
assertTrue(NativeTestServer.startNativeTestServer(getContext()));
// Add url interceptors after native application context is initialized.
MockUrlRequestJobFactory.setUp();
mFile = new File(getContext().getCacheDir().getPath() + "/tmpfile");
FileOutputStream fileOutputStream = new FileOutputStream(mFile);
try {
fileOutputStream.write(LOREM.getBytes("UTF-8"));
} finally {
fileOutputStream.close();
}
}
@SuppressFBWarnings("DM_GC") // Used to trigger strictmode detecting leaked closeables
@Override
protected void tearDown() throws Exception {
try {
NativeTestServer.shutdownNativeTestServer();
mTestFramework.mCronetEngine.shutdown();
assertTrue(mFile.delete());
// Run GC and finalizers a few times to pick up leaked closeables
for (int i = 0; i < 10; i++) {
System.gc();
System.runFinalization();
}
System.gc();
System.runFinalization();
super.tearDown();
} finally {
StrictMode.setVmPolicy(mOldVmPolicy);
}
}
@SmallTest
@Feature({"Cronet"})
public void testFileProvider() throws Exception {
TestUrlRequestCallback callback = new TestUrlRequestCallback();
UrlRequest.Builder builder =
new UrlRequest.Builder(NativeTestServer.getRedirectToEchoBody(), callback,
callback.getExecutor(), mTestFramework.mCronetEngine);
UploadDataProvider dataProvider = UploadDataProviders.create(mFile);
builder.setUploadDataProvider(dataProvider, callback.getExecutor());
builder.addHeader("Content-Type", "useless/string");
builder.build().start();
callback.blockForDone();
assertEquals(200, callback.mResponseInfo.getHttpStatusCode());
assertEquals(LOREM, callback.mResponseAsString);
}
@SmallTest
@Feature({"Cronet"})
public void testFileDescriptorProvider() throws Exception {
ParcelFileDescriptor descriptor =
ParcelFileDescriptor.open(mFile, ParcelFileDescriptor.MODE_READ_ONLY);
assertTrue(descriptor.getFileDescriptor().valid());
TestUrlRequestCallback callback = new TestUrlRequestCallback();
UrlRequest.Builder builder =
new UrlRequest.Builder(NativeTestServer.getRedirectToEchoBody(), callback,
callback.getExecutor(), mTestFramework.mCronetEngine);
UploadDataProvider dataProvider = UploadDataProviders.create(descriptor);
builder.setUploadDataProvider(dataProvider, callback.getExecutor());
builder.addHeader("Content-Type", "useless/string");
builder.build().start();
callback.blockForDone();
assertEquals(200, callback.mResponseInfo.getHttpStatusCode());
assertEquals(LOREM, callback.mResponseAsString);
}
@SmallTest
@Feature({"Cronet"})
public void testBadFileDescriptorProvider() throws Exception {
TestUrlRequestCallback callback = new TestUrlRequestCallback();
UrlRequest.Builder builder =
new UrlRequest.Builder(NativeTestServer.getRedirectToEchoBody(), callback,
callback.getExecutor(), mTestFramework.mCronetEngine);
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
try {
UploadDataProvider dataProvider = UploadDataProviders.create(pipe[0]);
builder.setUploadDataProvider(dataProvider, callback.getExecutor());
builder.addHeader("Content-Type", "useless/string");
builder.build().start();
callback.blockForDone();
assertTrue(callback.mError.getCause() instanceof IllegalArgumentException);
} finally {
pipe[1].close();
}
}
@SmallTest
@Feature({"Cronet"})
public void testBufferProvider() throws Exception {
TestUrlRequestCallback callback = new TestUrlRequestCallback();
UrlRequest.Builder builder =
new UrlRequest.Builder(NativeTestServer.getRedirectToEchoBody(), callback,
callback.getExecutor(), mTestFramework.mCronetEngine);
UploadDataProvider dataProvider = UploadDataProviders.create(LOREM.getBytes("UTF-8"));
builder.setUploadDataProvider(dataProvider, callback.getExecutor());
builder.addHeader("Content-Type", "useless/string");
builder.build().start();
callback.blockForDone();
assertEquals(200, callback.mResponseInfo.getHttpStatusCode());
assertEquals(LOREM, callback.mResponseAsString);
}
@SmallTest
@Feature({"Cronet"})
public void testNoErrorWhenCanceledDuringStart() throws Exception {
TestUrlRequestCallback callback = new TestUrlRequestCallback();
UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getEchoBodyURL(),
callback, callback.getExecutor(), mTestFramework.mCronetEngine);
final ConditionVariable first = new ConditionVariable();
final ConditionVariable second = new ConditionVariable();
builder.addHeader("Content-Type", "useless/string");
builder.setUploadDataProvider(new UploadDataProvider() {
@Override
public long getLength() throws IOException {
first.open();
second.block();
return 0;
}
@Override
public void read(UploadDataSink uploadDataSink, ByteBuffer byteBuffer)
throws IOException {}
@Override
public void rewind(UploadDataSink uploadDataSink) throws IOException {}
}, callback.getExecutor());
UrlRequest urlRequest = builder.build();
urlRequest.start();
first.block();
urlRequest.cancel();
second.open();
callback.blockForDone();
assertTrue(callback.mOnCanceledCalled);
}
@SmallTest
@Feature({"Cronet"})
public void testNoErrorWhenExceptionDuringStart() throws Exception {
TestUrlRequestCallback callback = new TestUrlRequestCallback();
UrlRequest.Builder builder = new UrlRequest.Builder(NativeTestServer.getEchoBodyURL(),
callback, callback.getExecutor(), mTestFramework.mCronetEngine);
final ConditionVariable first = new ConditionVariable();
final String exceptionMessage = "Bad Length";
builder.addHeader("Content-Type", "useless/string");
builder.setUploadDataProvider(new UploadDataProvider() {
@Override
public long getLength() throws IOException {
first.open();
throw new IOException(exceptionMessage);
}
@Override
public void read(UploadDataSink uploadDataSink, ByteBuffer byteBuffer)
throws IOException {}
@Override
public void rewind(UploadDataSink uploadDataSink) throws IOException {}
}, callback.getExecutor());
UrlRequest urlRequest = builder.build();
urlRequest.start();
first.block();
callback.blockForDone();
assertFalse(callback.mOnCanceledCalled);
assertEquals(UrlRequestError.LISTENER_EXCEPTION_THROWN, callback.mError.getErrorCode());
assertEquals("Exception received from UploadDataProvider", callback.mError.getMessage());
assertEquals(exceptionMessage, callback.mError.getCause().getMessage());
}
}
|
|
/*
* 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.test;
import com.carrotsearch.randomizedtesting.SeedUtils;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.Version;
import org.elasticsearch.cache.recycler.CacheRecycler;
import org.elasticsearch.cache.recycler.PageCacheRecyclerModule;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.io.FileSystemUtils;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.network.NetworkUtils;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.ImmutableSettings.Builder;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.BigArraysModule;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.index.engine.IndexEngineModule;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.internal.InternalNode;
import org.elasticsearch.search.SearchService;
import org.elasticsearch.test.cache.recycler.MockBigArraysModule;
import org.elasticsearch.test.cache.recycler.MockPageCacheRecyclerModule;
import org.elasticsearch.test.engine.MockEngineModule;
import org.elasticsearch.test.store.MockFSIndexStoreModule;
import org.elasticsearch.test.transport.AssertingLocalTransportModule;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportModule;
import org.elasticsearch.transport.TransportService;
import org.junit.Assert;
import java.io.Closeable;
import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.carrotsearch.randomizedtesting.RandomizedTest.systemPropertyAsBoolean;
import static com.google.common.collect.Maps.newTreeMap;
import static org.apache.lucene.util.LuceneTestCase.rarely;
import static org.apache.lucene.util.LuceneTestCase.usually;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
/**
* TestCluster manages a set of JVM private nodes and allows convenient access to them.
* The cluster supports randomized configuration such that nodes started in the cluster will
* automatically load asserting services tracking resources like file handles or open searchers.
* <p>
* The Cluster is bound to a test lifecycle where tests must call {@link #beforeTest(java.util.Random, double)} and
* {@link #afterTest()} to initialize and reset the cluster in order to be more reproducible. The term "more" relates
* to the async nature of Elasticsearch in combination with randomized testing. Once Threads and asynchronous calls
* are involved reproducibility is very limited. This class should only be used through {@link ElasticsearchIntegrationTest}.
* </p>
*/
public final class TestCluster implements Iterable<Client> {
private final ESLogger logger = Loggers.getLogger(getClass());
/**
* A boolean value to enable or disable mock modules. This is useful to test the
* system without asserting modules that to make sure they don't hide any bugs in
* production.
*
* @see ElasticsearchIntegrationTest
*/
public static final String TESTS_ENABLE_MOCK_MODULES = "tests.enable_mock_modules";
/**
* A node level setting that holds a per node random seed that is consistent across node restarts
*/
public static final String SETTING_CLUSTER_NODE_SEED = "test.cluster.node.seed";
private static final String CLUSTER_NAME_KEY = "cluster.name";
private static final boolean ENABLE_MOCK_MODULES = systemPropertyAsBoolean(TESTS_ENABLE_MOCK_MODULES, true);
static final int DEFAULT_MIN_NUM_NODES = 2;
static final int DEFAULT_MAX_NUM_NODES = 6;
/* sorted map to make traverse order reproducible */
private final TreeMap<String, NodeAndClient> nodes = newTreeMap();
private final Set<File> dataDirToClean = new HashSet<File>();
private final String clusterName;
private final AtomicBoolean open = new AtomicBoolean(true);
private final Settings defaultSettings;
private Random random;
private AtomicInteger nextNodeId = new AtomicInteger(0);
/* Each shared node has a node seed that is used to start up the node and get default settings
* this is important if a node is randomly shut down in a test since the next test relies on a
* fully shared cluster to be more reproducible */
private final long[] sharedNodesSeeds;
private double transportClientRatio = 0.0;
private final NodeSettingsSource nodeSettingsSource;
public TestCluster(long clusterSeed, String clusterName) {
this(clusterSeed, DEFAULT_MIN_NUM_NODES, DEFAULT_MAX_NUM_NODES, clusterName, NodeSettingsSource.EMPTY);
}
public TestCluster(long clusterSeed, int minNumNodes, int maxNumNodes, String clusterName) {
this(clusterSeed, minNumNodes, maxNumNodes, clusterName, NodeSettingsSource.EMPTY);
}
public TestCluster(long clusterSeed, int minNumNodes, int maxNumNodes, String clusterName, NodeSettingsSource nodeSettingsSource) {
this.clusterName = clusterName;
if (minNumNodes < 0 || maxNumNodes < 0) {
throw new IllegalArgumentException("minimum and maximum number of nodes must be >= 0");
}
if (maxNumNodes < minNumNodes) {
throw new IllegalArgumentException("maximum number of nodes must be >= minimum number of nodes");
}
Random random = new Random(clusterSeed);
int numSharedNodes;
if (minNumNodes == maxNumNodes) {
numSharedNodes = minNumNodes;
} else {
numSharedNodes = minNumNodes + random.nextInt(maxNumNodes - minNumNodes);
}
assert numSharedNodes >= 0;
/*
* TODO
* - we might want start some master only nodes?
* - we could add a flag that returns a client to the master all the time?
* - we could add a flag that never returns a client to the master
* - along those lines use a dedicated node that is master eligible and let all other nodes be only data nodes
*/
sharedNodesSeeds = new long[numSharedNodes];
for (int i = 0; i < sharedNodesSeeds.length; i++) {
sharedNodesSeeds[i] = random.nextLong();
}
logger.info("Setup TestCluster [{}] with seed [{}] using [{}] nodes", clusterName, SeedUtils.formatSeed(clusterSeed), numSharedNodes);
this.nodeSettingsSource = nodeSettingsSource;
Builder builder = ImmutableSettings.settingsBuilder();
if (random.nextInt(5) == 0) { // sometimes set this
// randomize (multi/single) data path, special case for 0, don't set it at all...
final int numOfDataPaths = random.nextInt(5);
if (numOfDataPaths > 0) {
StringBuilder dataPath = new StringBuilder();
for (int i = 0; i < numOfDataPaths; i++) {
dataPath.append("data/d").append(i).append(',');
}
builder.put("path.data", dataPath.toString());
}
}
defaultSettings = builder.build();
}
public String getClusterName() {
return clusterName;
}
private static boolean isLocalTransportConfigured() {
if ("local".equals(System.getProperty("es.node.mode", "network"))) {
return true;
}
return Boolean.parseBoolean(System.getProperty("es.node.local", "false"));
}
private Settings getSettings(int nodeOrdinal, long nodeSeed, Settings others) {
Builder builder = ImmutableSettings.settingsBuilder().put(defaultSettings)
.put(getRandomNodeSettings(nodeSeed));
Settings settings = nodeSettingsSource.settings(nodeOrdinal);
if (settings != null) {
if (settings.get(CLUSTER_NAME_KEY) != null) {
throw new ElasticsearchIllegalStateException("Tests must not set a '" + CLUSTER_NAME_KEY + "' as a node setting set '" + CLUSTER_NAME_KEY + "': [" + settings.get(CLUSTER_NAME_KEY) + "]");
}
builder.put(settings);
}
if (others != null) {
builder.put(others);
}
builder.put(CLUSTER_NAME_KEY, clusterName);
return builder.build();
}
private static Settings getRandomNodeSettings(long seed) {
Random random = new Random(seed);
Builder builder = ImmutableSettings.settingsBuilder()
/* use RAM directories in 10% of the runs */
//.put("index.store.type", random.nextInt(10) == 0 ? MockRamIndexStoreModule.class.getName() : MockFSIndexStoreModule.class.getName())
// decrease the routing schedule so new nodes will be added quickly - some random value between 30 and 80 ms
.put("cluster.routing.schedule", (30 + random.nextInt(50)) + "ms")
// default to non gateway
.put("gateway.type", "none")
.put(SETTING_CLUSTER_NODE_SEED, seed);
if (ENABLE_MOCK_MODULES && usually(random)) {
builder.put("index.store.type", MockFSIndexStoreModule.class.getName()); // no RAM dir for now!
builder.put(IndexEngineModule.EngineSettings.ENGINE_TYPE, MockEngineModule.class.getName());
builder.put(PageCacheRecyclerModule.CACHE_IMPL, MockPageCacheRecyclerModule.class.getName());
builder.put(BigArraysModule.IMPL, MockBigArraysModule.class.getName());
}
if (isLocalTransportConfigured()) {
builder.put(TransportModule.TRANSPORT_TYPE_KEY, AssertingLocalTransportModule.class.getName());
} else {
builder.put(Transport.TransportSettings.TRANSPORT_TCP_COMPRESS, rarely(random));
}
builder.put("type", RandomPicks.randomFrom(random, CacheRecycler.Type.values()));
if (random.nextBoolean()) {
builder.put("cache.recycler.page.type", RandomPicks.randomFrom(random, CacheRecycler.Type.values()));
}
if (random.nextInt(10) == 0) { // 10% of the nodes have a very frequent check interval
builder.put(SearchService.KEEPALIVE_INTERVAL_KEY, TimeValue.timeValueMillis(10 + random.nextInt(2000)));
} else if (random.nextInt(10) != 0) { // 90% of the time - 10% of the time we don't set anything
builder.put(SearchService.KEEPALIVE_INTERVAL_KEY, TimeValue.timeValueSeconds(10 + random.nextInt(5 * 60)));
}
if (random.nextBoolean()) { // sometimes set a
builder.put(SearchService.DEFAUTL_KEEPALIVE_KEY, TimeValue.timeValueSeconds(100 + random.nextInt(5*60)));
}
if (random.nextBoolean()) {
// change threadpool types to make sure we don't have components that rely on the type of thread pools
for (String name : Arrays.asList(ThreadPool.Names.BULK, ThreadPool.Names.FLUSH, ThreadPool.Names.GET,
ThreadPool.Names.INDEX, ThreadPool.Names.MANAGEMENT, ThreadPool.Names.MERGE, ThreadPool.Names.OPTIMIZE,
ThreadPool.Names.PERCOLATE, ThreadPool.Names.REFRESH, ThreadPool.Names.SEARCH, ThreadPool.Names.SNAPSHOT,
ThreadPool.Names.SUGGEST, ThreadPool.Names.WARMER)) {
if (random.nextBoolean()) {
final String type = RandomPicks.randomFrom(random, Arrays.asList("fixed", "cached", "scaling"));
builder.put(ThreadPool.THREADPOOL_GROUP + name + ".type", type);
}
}
}
builder.put("plugins.isolation", random.nextBoolean());
return builder.build();
}
public static String clusterName(String prefix, String childVMId, long clusterSeed) {
StringBuilder builder = new StringBuilder(prefix);
builder.append('-').append(NetworkUtils.getLocalAddress().getHostName());
builder.append("-CHILD_VM=[").append(childVMId).append(']');
builder.append("-CLUSTER_SEED=[").append(clusterSeed).append(']');
// if multiple maven task run on a single host we better have an identifier that doesn't rely on input params
builder.append("-HASH=[").append(SeedUtils.formatSeed(System.nanoTime())).append(']');
return builder.toString();
}
private void ensureOpen() {
if (!open.get()) {
throw new RuntimeException("Cluster is already closed");
}
}
private synchronized NodeAndClient getOrBuildRandomNode() {
ensureOpen();
NodeAndClient randomNodeAndClient = getRandomNodeAndClient();
if (randomNodeAndClient != null) {
return randomNodeAndClient;
}
NodeAndClient buildNode = buildNode();
buildNode.node().start();
publishNode(buildNode);
return buildNode;
}
private synchronized NodeAndClient getRandomNodeAndClient() {
Predicate<NodeAndClient> all = Predicates.alwaysTrue();
return getRandomNodeAndClient(all);
}
private synchronized NodeAndClient getRandomNodeAndClient(Predicate<NodeAndClient> predicate) {
ensureOpen();
Collection<NodeAndClient> values = Collections2.filter(nodes.values(), predicate);
if (!values.isEmpty()) {
int whichOne = random.nextInt(values.size());
for (NodeAndClient nodeAndClient : values) {
if (whichOne-- == 0) {
return nodeAndClient;
}
}
}
return null;
}
/**
* Ensures that at least <code>n</code> nodes are present in the cluster.
* if more nodes than <code>n</code> are present this method will not
* stop any of the running nodes.
*/
public synchronized void ensureAtLeastNumNodes(int n) {
int size = nodes.size();
for (int i = size; i < n; i++) {
logger.info("increasing cluster size from {} to {}", size, n);
NodeAndClient buildNode = buildNode();
buildNode.node().start();
publishNode(buildNode);
}
}
/**
* Ensures that at most <code>n</code> are up and running.
* If less nodes that <code>n</code> are running this method
* will not start any additional nodes.
*/
public synchronized void ensureAtMostNumNodes(int n) {
if (nodes.size() <= n) {
return;
}
// prevent killing the master if possible
final Iterator<NodeAndClient> values = n == 0 ? nodes.values().iterator() : Iterators.filter(nodes.values().iterator(), Predicates.not(new MasterNodePredicate(getMasterName())));
final Iterator<NodeAndClient> limit = Iterators.limit(values, nodes.size() - n);
logger.info("changing cluster size from {} to {}", nodes.size() - n, n);
Set<NodeAndClient> nodesToRemove = new HashSet<NodeAndClient>();
while (limit.hasNext()) {
NodeAndClient next = limit.next();
nodesToRemove.add(next);
next.close();
}
for (NodeAndClient toRemove : nodesToRemove) {
nodes.remove(toRemove.name);
}
}
private NodeAndClient buildNode(Settings settings, Version version) {
int ord = nextNodeId.getAndIncrement();
return buildNode(ord, random.nextLong(), settings, version);
}
private NodeAndClient buildNode() {
int ord = nextNodeId.getAndIncrement();
return buildNode(ord, random.nextLong(), null, Version.CURRENT);
}
private NodeAndClient buildNode(int nodeId, long seed, Settings settings, Version version) {
ensureOpen();
settings = getSettings(nodeId, seed, settings);
String name = buildNodeName(nodeId);
assert !nodes.containsKey(name);
Settings finalSettings = settingsBuilder()
.put(settings)
.put("name", name)
.put("discovery.id.seed", seed)
.put("tests.mock.version", version)
.build();
Node node = nodeBuilder().settings(finalSettings).build();
return new NodeAndClient(name, node, new RandomClientFactory());
}
private String buildNodeName(int id) {
return "node_" + id;
}
public synchronized Client client() {
ensureOpen();
/* Randomly return a client to one of the nodes in the cluster */
return getOrBuildRandomNode().client(random);
}
/**
* Returns a node client to the current master node.
* Note: use this with care tests should not rely on a certain nodes client.
*/
public synchronized Client masterClient() {
ensureOpen();
NodeAndClient randomNodeAndClient = getRandomNodeAndClient(new MasterNodePredicate(getMasterName()));
if (randomNodeAndClient != null) {
return randomNodeAndClient.nodeClient(); // ensure node client master is requested
}
Assert.fail("No master client found");
return null; // can't happen
}
/**
* Returns a node client to random node but not the master. This method will fail if no non-master client is available.
*/
public synchronized Client nonMasterClient() {
ensureOpen();
NodeAndClient randomNodeAndClient = getRandomNodeAndClient(Predicates.not(new MasterNodePredicate(getMasterName())));
if (randomNodeAndClient != null) {
return randomNodeAndClient.nodeClient(); // ensure node client non-master is requested
}
Assert.fail("No non-master client found");
return null; // can't happen
}
/**
* Returns a client to a node started with "node.client: true"
*/
public synchronized Client clientNodeClient() {
ensureOpen();
NodeAndClient randomNodeAndClient = getRandomNodeAndClient(new ClientNodePredicate());
if (randomNodeAndClient != null) {
return randomNodeAndClient.client(random);
}
startNodeClient(ImmutableSettings.EMPTY);
return getRandomNodeAndClient(new ClientNodePredicate()).client(random);
}
/**
* Returns a transport client
*/
public synchronized Client transportClient() {
ensureOpen();
// randomly return a transport client going to one of the nodes in the cluster
return getOrBuildRandomNode().transportClient();
}
/**
* Returns a node client to a given node.
*/
public synchronized Client client(String nodeName) {
ensureOpen();
NodeAndClient nodeAndClient = nodes.get(nodeName);
if (nodeAndClient != null) {
return nodeAndClient.client(random);
}
Assert.fail("No node found with name: [" + nodeName + "]");
return null; // can't happen
}
/**
* Returns a "smart" node client to a random node in the cluster
*/
public synchronized Client smartClient() {
NodeAndClient randomNodeAndClient = getRandomNodeAndClient();
if (randomNodeAndClient != null) {
return randomNodeAndClient.nodeClient();
}
Assert.fail("No smart client found");
return null; // can't happen
}
/**
* Returns a random node that applies to the given predicate.
* The predicate can filter nodes based on the nodes settings.
* If all nodes are filtered out this method will return <code>null</code>
*/
public synchronized Client client(final Predicate<Settings> filterPredicate) {
ensureOpen();
final NodeAndClient randomNodeAndClient = getRandomNodeAndClient(new Predicate<NodeAndClient>() {
@Override
public boolean apply(NodeAndClient nodeAndClient) {
return filterPredicate.apply(nodeAndClient.node.settings());
}
});
if (randomNodeAndClient != null) {
return randomNodeAndClient.client(random);
}
return null;
}
public void close() {
ensureOpen();
if (this.open.compareAndSet(true, false)) {
IOUtils.closeWhileHandlingException(nodes.values());
nodes.clear();
}
}
private final class NodeAndClient implements Closeable {
private InternalNode node;
private Client client;
private Client nodeClient;
private Client transportClient;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final ClientFactory clientFactory;
private final String name;
NodeAndClient(String name, Node node, ClientFactory factory) {
this.node = (InternalNode) node;
this.name = name;
this.clientFactory = factory;
}
Node node() {
if (closed.get()) {
throw new RuntimeException("already closed");
}
return node;
}
Client client(Random random) {
if (closed.get()) {
throw new RuntimeException("already closed");
}
if (client != null) {
return client;
}
return client = clientFactory.client(node, clusterName, random);
}
Client nodeClient() {
if (closed.get()) {
throw new RuntimeException("already closed");
}
if (nodeClient == null) {
Client maybeNodeClient = client(random);
if (client instanceof NodeClient) {
nodeClient = maybeNodeClient;
} else {
nodeClient = node.client();
}
}
return nodeClient;
}
Client transportClient() {
if (closed.get()) {
throw new RuntimeException("already closed");
}
if (transportClient == null) {
Client maybeTransportClient = client(random);
if (maybeTransportClient instanceof TransportClient) {
transportClient = maybeTransportClient;
} else {
transportClient = TransportClientFactory.NO_SNIFF_CLIENT_FACTORY.client(node, clusterName, random);
}
}
return transportClient;
}
void resetClient() {
if (closed.get()) {
throw new RuntimeException("already closed");
}
if (client != null) {
client.close();
client = null;
}
if (nodeClient != null) {
nodeClient.close();
nodeClient = null;
}
if (transportClient != null) {
transportClient.close();
transportClient = null;
}
}
void restart(RestartCallback callback) throws Exception {
assert callback != null;
if (!node.isClosed()) {
node.close();
}
Settings newSettings = callback.onNodeStopped(name);
if (newSettings == null) {
newSettings = ImmutableSettings.EMPTY;
}
if (callback.clearData(name)) {
NodeEnvironment nodeEnv = getInstanceFromNode(NodeEnvironment.class, node);
if (nodeEnv.hasNodeFile()) {
FileSystemUtils.deleteRecursively(nodeEnv.nodeDataLocations());
}
}
node = (InternalNode) nodeBuilder().settings(node.settings()).settings(newSettings).node();
resetClient();
}
@Override
public void close() {
closed.set(true);
if (client != null) {
client.close();
client = null;
}
if (nodeClient != null) {
nodeClient.close();
nodeClient = null;
}
node.close();
}
}
static class ClientFactory {
public Client client(Node node, String clusterName, Random random) {
return node.client();
}
}
static class TransportClientFactory extends ClientFactory {
private boolean sniff;
public static TransportClientFactory NO_SNIFF_CLIENT_FACTORY = new TransportClientFactory(false);
public static TransportClientFactory SNIFF_CLIENT_FACTORY = new TransportClientFactory(true);
public TransportClientFactory(boolean sniff) {
this.sniff = sniff;
}
@Override
public Client client(Node node, String clusterName, Random random) {
TransportAddress addr = ((InternalNode) node).injector().getInstance(TransportService.class).boundAddress().publishAddress();
TransportClient client = new TransportClient(settingsBuilder().put("client.transport.nodes_sampler_interval", "1s")
.put("name", "transport_client_" + node.settings().get("name"))
.put(CLUSTER_NAME_KEY, clusterName).put("client.transport.sniff", sniff).build());
client.addTransportAddress(addr);
return client;
}
}
class RandomClientFactory extends ClientFactory {
@Override
public Client client(Node node, String clusterName, Random random) {
double nextDouble = random.nextDouble();
if (nextDouble < transportClientRatio) {
if (logger.isDebugEnabled()) {
logger.debug("Using transport client for node [{}] sniff: [{}]", node.settings().get("name"), false);
}
/* no sniff client for now - doesn't work will all tests since it might throw NoNodeAvailableException if nodes are shut down.
* we first need support of transportClientRatio as annotations or so
*/
return TransportClientFactory.NO_SNIFF_CLIENT_FACTORY.client(node, clusterName, random);
} else {
return node.client();
}
}
}
/**
* This method should be executed before each test to reset the cluster to it's initial state.
*/
public synchronized void beforeTest(Random random, double transportClientRatio) {
reset(random, true, transportClientRatio);
}
private synchronized void reset(Random random, boolean wipeData, double transportClientRatio) {
assert transportClientRatio >= 0.0 && transportClientRatio <= 1.0;
logger.debug("Reset test cluster with transport client ratio: [{}]", transportClientRatio);
this.transportClientRatio = transportClientRatio;
this.random = new Random(random.nextLong());
resetClients(); /* reset all clients - each test gets its own client based on the Random instance created above. */
if (wipeData) {
wipeDataDirectories();
}
if (nextNodeId.get() == sharedNodesSeeds.length && nodes.size() == sharedNodesSeeds.length) {
logger.debug("Cluster hasn't changed - moving out - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), sharedNodesSeeds.length);
return;
}
logger.debug("Cluster is NOT consistent - restarting shared nodes - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), sharedNodesSeeds.length);
Set<NodeAndClient> sharedNodes = new HashSet<NodeAndClient>();
boolean changed = false;
for (int i = 0; i < sharedNodesSeeds.length; i++) {
String buildNodeName = buildNodeName(i);
NodeAndClient nodeAndClient = nodes.get(buildNodeName);
if (nodeAndClient == null) {
changed = true;
nodeAndClient = buildNode(i, sharedNodesSeeds[i], null, Version.CURRENT);
nodeAndClient.node.start();
logger.info("Start Shared Node [{}] not shared", nodeAndClient.name);
}
sharedNodes.add(nodeAndClient);
}
if (!changed && sharedNodes.size() == nodes.size()) {
logger.debug("Cluster is consistent - moving out - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), sharedNodesSeeds.length);
if (size() > 0) {
client().admin().cluster().prepareHealth().setWaitForNodes(Integer.toString(sharedNodesSeeds.length)).get();
}
return; // we are consistent - return
}
for (NodeAndClient nodeAndClient : sharedNodes) {
nodes.remove(nodeAndClient.name);
}
// trash the remaining nodes
final Collection<NodeAndClient> toShutDown = nodes.values();
for (NodeAndClient nodeAndClient : toShutDown) {
logger.debug("Close Node [{}] not shared", nodeAndClient.name);
nodeAndClient.close();
}
nodes.clear();
for (NodeAndClient nodeAndClient : sharedNodes) {
publishNode(nodeAndClient);
}
nextNodeId.set(sharedNodesSeeds.length);
assert size() == sharedNodesSeeds.length;
if (size() > 0) {
client().admin().cluster().prepareHealth().setWaitForNodes(Integer.toString(sharedNodesSeeds.length)).get();
}
logger.debug("Cluster is consistent again - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), sharedNodesSeeds.length);
}
/**
* This method should be executed during tearDown
*/
public synchronized void afterTest() {
wipeDataDirectories();
resetClients(); /* reset all clients - each test gets its own client based on the Random instance created above. */
}
private void resetClients() {
final Collection<NodeAndClient> nodesAndClients = nodes.values();
for (NodeAndClient nodeAndClient : nodesAndClients) {
nodeAndClient.resetClient();
}
}
private void wipeDataDirectories() {
if (!dataDirToClean.isEmpty()) {
logger.info("Wipe data directory for all nodes locations: {}", this.dataDirToClean);
try {
FileSystemUtils.deleteRecursively(dataDirToClean.toArray(new File[dataDirToClean.size()]));
} finally {
this.dataDirToClean.clear();
}
}
}
/**
* Returns a reference to a random nodes {@link ClusterService}
*/
public synchronized ClusterService clusterService() {
return getInstance(ClusterService.class);
}
/**
* Returns an Iterabel to all instances for the given class >T< across all nodes in the cluster.
*/
public synchronized <T> Iterable<T> getInstances(Class<T> clazz) {
List<T> instances = new ArrayList<T>(nodes.size());
for (NodeAndClient nodeAndClient : nodes.values()) {
instances.add(getInstanceFromNode(clazz, nodeAndClient.node));
}
return instances;
}
/**
* Returns a reference to the given nodes instances of the given class >T<
*/
public synchronized <T> T getInstance(Class<T> clazz, final String node) {
final Predicate<TestCluster.NodeAndClient> predicate;
if (node != null) {
predicate = new Predicate<TestCluster.NodeAndClient>() {
public boolean apply(NodeAndClient nodeAndClient) {
return node.equals(nodeAndClient.name);
}
};
} else {
predicate = Predicates.alwaysTrue();
}
NodeAndClient randomNodeAndClient = getRandomNodeAndClient(predicate);
assert randomNodeAndClient != null;
return getInstanceFromNode(clazz, randomNodeAndClient.node);
}
/**
* Returns a reference to a random nodes instances of the given class >T<
*/
public synchronized <T> T getInstance(Class<T> clazz) {
return getInstance(clazz, null);
}
private synchronized <T> T getInstanceFromNode(Class<T> clazz, InternalNode node) {
return node.injector().getInstance(clazz);
}
/**
* Returns the number of nodes in the cluster.
*/
public synchronized int size() {
return this.nodes.size();
}
/**
* Stops a random node in the cluster.
*/
public synchronized void stopRandomNode() {
ensureOpen();
NodeAndClient nodeAndClient = getRandomNodeAndClient();
if (nodeAndClient != null) {
logger.info("Closing random node [{}] ", nodeAndClient.name);
nodes.remove(nodeAndClient.name);
nodeAndClient.close();
}
}
/**
* Stops a random node in the cluster that applies to the given filter or non if the non of the nodes applies to the
* filter.
*/
public synchronized void stopRandomNode(final Predicate<Settings> filter) {
ensureOpen();
NodeAndClient nodeAndClient = getRandomNodeAndClient(new Predicate<TestCluster.NodeAndClient>() {
@Override
public boolean apply(NodeAndClient nodeAndClient) {
return filter.apply(nodeAndClient.node.settings());
}
});
if (nodeAndClient != null) {
logger.info("Closing filtered random node [{}] ", nodeAndClient.name);
nodes.remove(nodeAndClient.name);
nodeAndClient.close();
}
}
/**
* Stops the current master node forcefully
*/
public synchronized void stopCurrentMasterNode() {
ensureOpen();
assert size() > 0;
String masterNodeName = getMasterName();
assert nodes.containsKey(masterNodeName);
logger.info("Closing master node [{}] ", masterNodeName);
NodeAndClient remove = nodes.remove(masterNodeName);
remove.close();
}
/**
* Stops the any of the current nodes but not the master node.
*/
public void stopRandomNonMasterNode() {
NodeAndClient nodeAndClient = getRandomNodeAndClient(Predicates.not(new MasterNodePredicate(getMasterName())));
if (nodeAndClient != null) {
logger.info("Closing random non master node [{}] current master [{}] ", nodeAndClient.name, getMasterName());
nodes.remove(nodeAndClient.name);
nodeAndClient.close();
}
}
/**
* Restarts a random node in the cluster
*/
public void restartRandomNode() throws Exception {
restartRandomNode(EMPTY_CALLBACK);
}
/**
* Restarts a random node in the cluster and calls the callback during restart.
*/
public void restartRandomNode(RestartCallback callback) throws Exception {
ensureOpen();
NodeAndClient nodeAndClient = getRandomNodeAndClient();
if (nodeAndClient != null) {
logger.info("Restarting random node [{}] ", nodeAndClient.name);
nodeAndClient.restart(callback);
}
}
private void restartAllNodes(boolean rollingRestart, RestartCallback callback) throws Exception {
ensureOpen();
List<NodeAndClient> toRemove = new ArrayList<TestCluster.NodeAndClient>();
try {
for (NodeAndClient nodeAndClient : nodes.values()) {
if (!callback.doRestart(nodeAndClient.name)) {
logger.info("Closing node [{}] during restart", nodeAndClient.name);
toRemove.add(nodeAndClient);
nodeAndClient.close();
}
}
} finally {
for (NodeAndClient nodeAndClient : toRemove) {
nodes.remove(nodeAndClient.name);
}
}
logger.info("Restarting remaining nodes rollingRestart [{}]", rollingRestart);
if (rollingRestart) {
int numNodesRestarted = 0;
for (NodeAndClient nodeAndClient : nodes.values()) {
callback.doAfterNodes(numNodesRestarted++, nodeAndClient.nodeClient());
logger.info("Restarting node [{}] ", nodeAndClient.name);
nodeAndClient.restart(callback);
}
} else {
int numNodesRestarted = 0;
for (NodeAndClient nodeAndClient : nodes.values()) {
callback.doAfterNodes(numNodesRestarted++, nodeAndClient.nodeClient());
logger.info("Stopping node [{}] ", nodeAndClient.name);
nodeAndClient.node.close();
}
for (NodeAndClient nodeAndClient : nodes.values()) {
logger.info("Starting node [{}] ", nodeAndClient.name);
nodeAndClient.restart(callback);
}
}
}
private static final RestartCallback EMPTY_CALLBACK = new RestartCallback() {
public Settings onNodeStopped(String node) {
return null;
}
};
/**
* Restarts all nodes in the cluster. It first stops all nodes and then restarts all the nodes again.
*/
public void fullRestart() throws Exception {
fullRestart(EMPTY_CALLBACK);
}
/**
* Restarts all nodes in a rolling restart fashion ie. only restarts on node a time.
*/
public void rollingRestart() throws Exception {
rollingRestart(EMPTY_CALLBACK);
}
/**
* Restarts all nodes in a rolling restart fashion ie. only restarts on node a time.
*/
public void rollingRestart(RestartCallback function) throws Exception {
restartAllNodes(true, function);
}
/**
* Restarts all nodes in the cluster. It first stops all nodes and then restarts all the nodes again.
*/
public void fullRestart(RestartCallback function) throws Exception {
restartAllNodes(false, function);
}
private String getMasterName() {
try {
ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState();
return state.nodes().masterNode().name();
} catch (Throwable e) {
logger.warn("Can't fetch cluster state", e);
throw new RuntimeException("Can't get master node " + e.getMessage(), e);
}
}
synchronized Set<String> allButN(int numNodes) {
return nRandomNodes(size() - numNodes);
}
private synchronized Set<String> nRandomNodes(int numNodes) {
assert size() >= numNodes;
return Sets.newHashSet(Iterators.limit(this.nodes.keySet().iterator(), numNodes));
}
public synchronized void startNodeClient(Settings settings) {
ensureOpen(); // currently unused
startNode(settingsBuilder().put(settings).put("node.client", true));
}
/**
* Returns a set of nodes that have at least one shard of the given index.
*/
public synchronized Set<String> nodesInclude(String index) {
if (clusterService().state().routingTable().hasIndex(index)) {
List<ShardRouting> allShards = clusterService().state().routingTable().allShards(index);
DiscoveryNodes discoveryNodes = clusterService().state().getNodes();
Set<String> nodes = new HashSet<String>();
for (ShardRouting shardRouting : allShards) {
if (shardRouting.assignedToNode()) {
DiscoveryNode discoveryNode = discoveryNodes.get(shardRouting.currentNodeId());
nodes.add(discoveryNode.getName());
}
}
return nodes;
}
return Collections.emptySet();
}
/**
* Starts a node with default settings and returns it's name.
*/
public String startNode() {
return startNode(ImmutableSettings.EMPTY, Version.CURRENT);
}
/**
* Starts a node with default settings ad the specified version and returns it's name.
*/
public String startNode(Version version) {
return startNode(ImmutableSettings.EMPTY, version);
}
/**
* Starts a node with the given settings builder and returns it's name.
*/
public String startNode(Settings.Builder settings) {
return startNode(settings.build(), Version.CURRENT);
}
/**
* Starts a node with the given settings and returns it's name.
*/
public String startNode(Settings settings) {
return startNode(settings, Version.CURRENT);
}
public String startNode(Settings settings, Version version) {
NodeAndClient buildNode = buildNode(settings, version);
buildNode.node().start();
publishNode(buildNode);
return buildNode.name;
}
private void publishNode(NodeAndClient nodeAndClient) {
assert !nodeAndClient.node().isClosed();
NodeEnvironment nodeEnv = getInstanceFromNode(NodeEnvironment.class, nodeAndClient.node);
if (nodeEnv.hasNodeFile()) {
dataDirToClean.addAll(Arrays.asList(nodeEnv.nodeDataLocations()));
}
nodes.put(nodeAndClient.name, nodeAndClient);
}
public void closeNonSharedNodes(boolean wipeData) {
reset(random, wipeData, transportClientRatio);
}
public int dataNodes() {
return dataNodeAndClients().size();
}
private Collection<NodeAndClient> dataNodeAndClients() {
return Collections2.filter(nodes.values(), new DataNodePredicate());
}
private static final class DataNodePredicate implements Predicate<NodeAndClient> {
@Override
public boolean apply(NodeAndClient nodeAndClient) {
return nodeAndClient.node.settings().getAsBoolean("node.data", true);
}
}
private static final class MasterNodePredicate implements Predicate<NodeAndClient> {
private final String masterNodeName;
public MasterNodePredicate(String masterNodeName) {
this.masterNodeName = masterNodeName;
}
@Override
public boolean apply(NodeAndClient nodeAndClient) {
return masterNodeName.equals(nodeAndClient.name);
}
}
private static final class ClientNodePredicate implements Predicate<NodeAndClient> {
@Override
public boolean apply(NodeAndClient nodeAndClient) {
return nodeAndClient.node.settings().getAsBoolean("node.client", false);
}
}
@Override
public synchronized Iterator<Client> iterator() {
ensureOpen();
final Iterator<NodeAndClient> iterator = nodes.values().iterator();
return new Iterator<Client>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Client next() {
return iterator.next().client(random);
}
@Override
public void remove() {
throw new UnsupportedOperationException("");
}
};
}
/**
* Returns a predicate that only accepts settings of nodes with one of the given names.
*/
public static Predicate<Settings> nameFilter(String... nodeName) {
return new NodeNamePredicate(new HashSet<String>(Arrays.asList(nodeName)));
}
private static final class NodeNamePredicate implements Predicate<Settings> {
private final HashSet<String> nodeNames;
public NodeNamePredicate(HashSet<String> nodeNames) {
this.nodeNames = nodeNames;
}
@Override
public boolean apply(Settings settings) {
return nodeNames.contains(settings.get("name"));
}
}
/**
* An abstract class that is called during {@link #rollingRestart(org.elasticsearch.test.TestCluster.RestartCallback)}
* and / or {@link #fullRestart(org.elasticsearch.test.TestCluster.RestartCallback)} to execute actions at certain
* stages of the restart.
*/
public static abstract class RestartCallback {
/**
* Executed once the give node name has been stopped.
*/
public Settings onNodeStopped(String nodeName) throws Exception {
return ImmutableSettings.EMPTY;
}
/**
* Executed for each node before the <tt>n+1</tt> node is restarted. The given client is
* an active client to the node that will be restarted next.
*/
public void doAfterNodes(int n, Client client) throws Exception {
}
/**
* If this returns <code>true</code> all data for the node with the given node name will be cleared including
* gateways and all index data. Returns <code>false</code> by default.
*/
public boolean clearData(String nodeName) {
return false;
}
/**
* If this returns <code>false</code> the node with the given node name will not be restarted. It will be
* closed and removed from the cluster. Returns <code>true</code> by default.
*/
public boolean doRestart(String nodeName) {
return true;
}
}
}
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.compositor.layouts;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.ViewGroup;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.compositor.LayerTitleCache;
import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.AreaGestureEventFilter;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.EdgeSwipeEventFilter.ScrollDirection;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.EventFilterHost;
import org.chromium.chrome.browser.compositor.layouts.eventfilter.GestureHandler;
import org.chromium.chrome.browser.compositor.overlays.strip.StripLayoutHelperManager;
import org.chromium.chrome.browser.compositor.scene_layer.SceneLayer;
import org.chromium.chrome.browser.contextualsearch.ContextualSearchManagementDelegate;
import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tabmodel.TabCreatorManager;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelSelectorTabObserver;
import org.chromium.ui.resources.ResourceManager;
import org.chromium.ui.resources.dynamics.DynamicResourceLoader;
import java.util.List;
/**
* {@link LayoutManagerChromeTablet} is the specialization of {@link LayoutManagerChrome} for
* the tablet.
*/
public class LayoutManagerChromeTablet extends LayoutManagerChrome {
// Event Filters
private final TabStripEventFilter mTabStripFilter;
// Internal State
private final String mDefaultTitle;
private StripLayoutHelperManager mTabStripLayoutHelperManager;
private TabModelSelectorTabObserver mTabObserver;
/**
* Creates an instance of a {@link LayoutManagerChromePhone}.
* @param host A {@link LayoutManagerHost} instance.
* @param overviewLayoutFactoryDelegate A {@link OverviewLayoutFactoryDelegate} instance.
*/
public LayoutManagerChromeTablet(
LayoutManagerHost host, OverviewLayoutFactoryDelegate overviewLayoutFactoryDelegate) {
super(host, overviewLayoutFactoryDelegate);
Context context = host.getContext();
// Build Event Filters
mTabStripFilter = new TabStripEventFilter(
context, this, new TabStripEventHandler(), null, false, false);
mTabStripLayoutHelperManager = new StripLayoutHelperManager(
context, this, mHost.getLayoutRenderHost(), mTabStripFilter);
// Set up state
mDefaultTitle = context.getString(R.string.tab_loading_default_title);
addGlobalSceneOverlay(mTabStripLayoutHelperManager);
setNextLayout(null);
}
@Override
public void destroy() {
super.destroy();
if (mTabStripLayoutHelperManager != null) {
mTabStripLayoutHelperManager.destroy();
mTabStripLayoutHelperManager = null;
}
if (mTabObserver != null) {
mTabObserver.destroy();
mTabObserver = null;
}
}
@Override
protected ToolbarSwipeHandler createToolbarSwipeHandler(LayoutProvider provider) {
return new TabletToolbarSwipeHandler(provider);
}
@Override
public void tabSelected(int tabId, int prevId, boolean incognito) {
if (getActiveLayout() == mStaticLayout || getActiveLayout() == mOverviewListLayout) {
super.tabSelected(tabId, prevId, incognito);
} else {
startShowing(mStaticLayout, false);
// TODO(dtrainor, jscholler): This is hacky because we're relying on it to set the
// internal tab to show and not start hiding until we're done calling finalizeShowing().
// This prevents a flicker because we properly build and set the internal
// {@link LayoutTab} before actually showing the {@link TabView}.
if (getActiveLayout() != null) {
getActiveLayout().onTabSelected(time(), tabId, prevId, incognito);
}
if (getActiveLayout() != null) getActiveLayout().onTabSelecting(time(), tabId);
}
}
@Override
protected void tabCreated(int id, int sourceId, TabLaunchType launchType, boolean incognito,
boolean willBeSelected, float originX, float originY) {
if (getFullscreenManager() != null) getFullscreenManager().showControlsTransient();
super.tabCreated(id, sourceId, launchType, incognito, willBeSelected, originX, originY);
}
@Override
protected void tabClosed(int id, int nextId, boolean incognito) {
super.tabClosed(id, nextId, incognito);
}
@Override
protected void tabClosureCommitted(int id, boolean incognito) {
super.tabClosureCommitted(id, incognito);
if (mTitleCache != null) mTitleCache.remove(id);
}
@Override
public void init(TabModelSelector selector, TabCreatorManager creator,
TabContentManager content, ViewGroup androidContentContainer,
ContextualSearchManagementDelegate contextualSearchDelegate,
DynamicResourceLoader dynamicResourceLoader) {
if (mTabStripLayoutHelperManager != null) {
mTabStripLayoutHelperManager.setTabModelSelector(selector, creator, content);
}
super.init(selector, creator, content, androidContentContainer, contextualSearchDelegate,
dynamicResourceLoader);
mTabObserver = new TabModelSelectorTabObserver(selector) {
@Override
public void onFaviconUpdated(Tab tab) {
updateTitle(tab);
}
@Override
public void onTitleUpdated(Tab tab) {
updateTitle(tab);
}
};
// Make sure any tabs already restored get loaded into the title cache.
List<TabModel> models = selector.getModels();
for (int i = 0; i < models.size(); i++) {
TabModel model = models.get(i);
for (int j = 0; j < model.getCount(); j++) {
Tab tab = model.getTabAt(j);
if (tab != null && mTitleCache != null) {
mTitleCache.put(tab.getId(), getTitleBitmap(tab), getFaviconBitmap(tab),
tab.isIncognito(), tab.isTitleDirectionRtl());
}
}
}
}
@Override
protected LayoutManagerTabModelObserver createTabModelObserver() {
return new LayoutManagerTabModelObserver() {
@Override
public void didAddTab(Tab tab, TabLaunchType launchType) {
super.didAddTab(tab, launchType);
updateTitle(getTabById(tab.getId()));
}
};
}
@Override
protected String getTitleForTab(Tab tab) {
String title = super.getTitleForTab(tab);
if (TextUtils.isEmpty(title)) title = mDefaultTitle;
return title;
}
@Override
public StripLayoutHelperManager getStripLayoutHelperManager() {
return mTabStripLayoutHelperManager;
}
@Override
public SceneLayer getUpdatedActiveSceneLayer(Rect viewport, Rect contentViewport,
LayerTitleCache layerTitleCache, TabContentManager tabContentManager,
ResourceManager resourceManager, ChromeFullscreenManager fullscreenManager) {
mTabStripLayoutHelperManager.setBrightness(getActiveLayout().getToolbarBrightness());
return super.getUpdatedActiveSceneLayer(viewport, contentViewport, layerTitleCache,
tabContentManager, resourceManager, fullscreenManager);
}
private void updateTitle(Tab tab) {
if (tab != null && mTitleCache != null) {
mTitleCache.put(tab.getId(), getTitleBitmap(tab), getFaviconBitmap(tab),
tab.isIncognito(), tab.isTitleDirectionRtl());
getActiveLayout().tabTitleChanged(tab.getId(), getTitleForTab(tab));
}
}
private class TabletToolbarSwipeHandler extends ToolbarSwipeHandler {
public TabletToolbarSwipeHandler(LayoutProvider provider) {
super(provider);
}
@Override
public boolean isSwipeEnabled(ScrollDirection direction) {
if ((direction == ScrollDirection.LEFT || direction == ScrollDirection.RIGHT)
&& (getTabModelSelector() == null
|| getTabModelSelector().getCurrentModel().getCount() <= 1)) {
return false;
}
return super.isSwipeEnabled(direction);
}
}
private class TabStripEventHandler implements GestureHandler {
@Override
public void onDown(float x, float y, boolean fromMouse, int buttons) {
mTabStripLayoutHelperManager.onDown(time(), x, y, fromMouse, buttons);
}
@Override
public void onUpOrCancel() {
mTabStripLayoutHelperManager.onUpOrCancel(time());
}
@Override
public void drag(float x, float y, float dx, float dy, float tx, float ty) {
mTabStripLayoutHelperManager.drag(time(), x, y, dx, dy, tx, ty);
}
@Override
public void click(float x, float y, boolean fromMouse, int buttons) {
mTabStripLayoutHelperManager.click(time(), x, y, fromMouse, buttons);
}
@Override
public void fling(float x, float y, float velocityX, float velocityY) {
mTabStripLayoutHelperManager.fling(time(), x, y, velocityX, velocityY);
}
@Override
public void onLongPress(float x, float y) {
mTabStripLayoutHelperManager.onLongPress(time(), x, y);
}
@Override
public void onPinch(float x0, float y0, float x1, float y1, boolean firstEvent) {
// Not implemented.
}
}
private class TabStripEventFilter extends AreaGestureEventFilter {
public TabStripEventFilter(Context context, EventFilterHost host, GestureHandler handler,
RectF triggerRect, boolean autoOffset, boolean useDefaultLongPress) {
super(context, host, handler, triggerRect, autoOffset, useDefaultLongPress);
}
@Override
public boolean onInterceptTouchEventInternal(MotionEvent e, boolean isKeyboardShowing) {
if (getActiveLayout().isTabStripEventFilterEnabled()) {
return super.onInterceptTouchEventInternal(e, isKeyboardShowing);
}
return false;
}
}
}
|
|
package de.gurkenlabs.litiengine.environment.tilemap.xml;
import java.awt.Color;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.gurkenlabs.litiengine.environment.tilemap.ICustomProperty;
import de.gurkenlabs.litiengine.environment.tilemap.ICustomPropertyProvider;
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomPropertyProvider implements ICustomPropertyProvider {
@XmlElement
@XmlJavaTypeAdapter(CustomPropertyAdapter.class)
private Map<String, ICustomProperty> properties;
public CustomPropertyProvider() {
this.properties = new Hashtable<>(); // use Hashtable because it rejects null keys and null values
}
/**
* Copy Constructor for copying instances of CustomPropertyProviders.
*
* @param propertyProviderToBeCopied
* the PropertyProvider we want to copy
*/
public CustomPropertyProvider(ICustomPropertyProvider propertyProviderToBeCopied) {
this.properties = propertyProviderToBeCopied.getProperties().entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, e -> new CustomProperty((e.getValue()))));
}
@Override
public Map<String, ICustomProperty> getProperties() {
return this.properties;
}
@Override
public boolean hasCustomProperty(String propertyName) {
return this.getProperties().containsKey(propertyName);
}
@Override
public String getTypeOfProperty(String propertyName) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return null;
}
return property.getType();
}
@Override
public void setTypeOfProperty(String propertyName, String type) {
this.getProperty(propertyName).setType(type);
}
@Override
public ICustomProperty getProperty(String propertyName) {
return this.getProperties().get(propertyName);
}
@Override
public void setValue(String propertyName, ICustomProperty value) {
if (value != null) {
this.getProperties().put(propertyName, value);
}
}
@Override
public String getStringValue(String propertyName) {
return this.getStringValue(propertyName, null);
}
@Override
public String getStringValue(String propertyName, String defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
return property.getAsString();
}
@Override
public int getIntValue(String propertyName) {
return this.getIntValue(propertyName, 0);
}
@Override
public int getIntValue(String propertyName, int defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
return property.getAsInt();
}
@Override
public long getLongValue(String propertyName, long defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
return property.getAsLong();
}
@Override
public short getShortValue(String propertyName) {
return this.getShortValue(propertyName, (short) 0);
}
@Override
public short getShortValue(String propertyName, short defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
return property.getAsShort();
}
@Override
public byte getByteValue(String propertyName) {
return this.getByteValue(propertyName, (byte) 0);
}
@Override
public byte getByteValue(String propertyName, byte defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
return property.getAsByte();
}
@Override
public boolean getBoolValue(String propertyName) {
return this.getBoolValue(propertyName, false);
}
@Override
public boolean getBoolValue(String propertyName, boolean defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
return property.getAsBool();
}
@Override
public float getFloatValue(String propertyName) {
return this.getFloatValue(propertyName, 0f);
}
@Override
public float getFloatValue(String propertyName, float defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
return property.getAsFloat();
}
@Override
public double getDoubleValue(String propertyName) {
return this.getDoubleValue(propertyName, 0.0);
}
@Override
public double getDoubleValue(String propertyName, double defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
return property.getAsDouble();
}
@Override
public Color getColorValue(String propertyName) {
return this.getColorValue(propertyName, null);
}
@Override
public Color getColorValue(String propertyName, Color defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
Color value = property.getAsColor();
if (value == null) {
return defaultValue;
}
return value;
}
@Override
public <T extends Enum<T>> T getEnumValue(String propertyName, Class<T> enumType) {
return this.getEnumValue(propertyName, enumType, null);
}
@Override
public <T extends Enum<T>> T getEnumValue(String propertyName, Class<T> enumType, T defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
T value = property.getAsEnum(enumType);
if (value == null) {
return defaultValue;
}
return value;
}
@Override
public URL getFileValue(String propertyName) {
return this.getFileValue(propertyName, null);
}
@Override
public URL getFileValue(String propertyName, URL defaultValue) {
ICustomProperty property = this.getProperty(propertyName);
if (property == null) {
return defaultValue;
}
URL value = property.getAsFile();
if (value == null) {
return defaultValue;
}
return value;
}
private ICustomProperty createPropertyIfAbsent(String propertyName) {
return this.getProperties().computeIfAbsent(propertyName, n -> new CustomProperty());
}
@Override
public void setValue(String propertyName, URL value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("file");
property.setValue(value);
}
@Override
public void setValue(String propertyName, String value) {
if (value != null) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("string");
property.setValue(value);
} else {
this.getProperties().remove(propertyName);
}
}
@Override
public void setValue(String propertyName, boolean value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("bool");
property.setValue(value);
}
@Override
public void setValue(String propertyName, byte value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("int");
property.setValue(value);
}
@Override
public void setValue(String propertyName, short value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("int");
property.setValue(value);
}
@Override
public void setValue(String propertyName, int value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("int");
property.setValue(value);
}
@Override
public void setValue(String propertyName, long value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("int");
property.setValue(value);
}
@Override
public void setValue(String propertyName, float value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("float");
property.setValue(value);
}
@Override
public void setValue(String propertyName, double value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("float");
property.setValue(value);
}
@Override
public void setValue(String propertyName, Color value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("color");
property.setValue(value);
}
@Override
public void setValue(String propertyName, Enum<?> value) {
ICustomProperty property = createPropertyIfAbsent(propertyName);
property.setType("string");
property.setValue(value);
}
@Override
public void setProperties(Map<String, ICustomProperty> props) {
this.getProperties().clear();
if (props != null) {
this.getProperties().putAll(props);
}
}
@Override
public void removeProperty(String propertyName) {
this.getProperties().remove(propertyName);
}
@SuppressWarnings("unused")
private void afterUnmarshal(Unmarshaller u, Object parent) {
if (this.properties == null) {
this.properties = new Hashtable<>();
}
}
void finish(URL location) throws TmxException {
// blank base case
}
@Override
public List<String> getCommaSeparatedStringValues(String propertyName, String defaultValue) {
List<String> values = new ArrayList<>();
String valuesStr = this.getStringValue(propertyName, defaultValue);
if (valuesStr != null && !valuesStr.isEmpty()) {
for (String value : valuesStr.split(","))
if (value != null) {
values.add(value);
}
}
return values;
}
}
|
|
package com.bazaarvoice.emodb.auth.permissions;
import com.bazaarvoice.emodb.auth.permissions.matching.AnyPart;
import com.bazaarvoice.emodb.auth.permissions.matching.ConstantPart;
import com.bazaarvoice.emodb.auth.permissions.matching.MatchingPart;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.InvalidPermissionStringException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Similar to {@link org.apache.shiro.authz.permission.WildcardPermission} with the following differences:
* <ol>
* <li>Parts are separated by "|" instead of ":", since ":" occurs commonly in emo table names</li>
* <li>Provides basic wildcard support, although the implementation is extensible to provide further wildcard capabilities.</li>
* <li>Provides methods for escaping separators and wildcards.</li>
* </ol>
*/
public class MatchingPermission implements Permission, Serializable {
private final static String SEPARATOR = "|";
private final static String UNESCAPED_SEPARATOR_REGEX = "\\|";
private final static String SEPARATOR_ESCAPE = "\\\\|";
private final static String ESCAPED_SEPARATOR_REGEX = "\\\\\\|";
private final static Pattern SEPARATOR_SPLIT_PATTERN = Pattern.compile("(?<!\\\\)\\|");
private final static String UNESCAPED_WILDCARD_REGEX = "\\*";
private final static String WILDCARD_ESCAPE = "\\\\\\*";
private final static String ANY_INDICATOR = "*";
private final String _permission;
private List<MatchingPart> _parts;
public MatchingPermission(String permission) {
this(permission, true);
}
protected MatchingPermission(String permission, boolean initializePermission) {
_permission = checkNotNull(permission, "permission");
if ("".equals(permission.trim())) {
throw new InvalidPermissionStringException("Permission must be a non-null, non-empty string", permission);
}
if (initializePermission) {
initializePermission();
}
}
/**
* Parses and initializes the permission's parts. By default this is performed by the constructor. If a subclass
* needs to perform its own initialization prior to initializing the permissions then it should call the constructor
* with the initialization parameter set to false and then call this method when ready.
*/
protected void initializePermission() {
try {
List<MatchingPart> parts = Lists.newArrayList();
for (String partString : split(_permission)) {
partString = partString.trim();
checkArgument(!"".equals(partString), "Permission cannot contain empty parts");
MatchingPart part = toPart(Collections.unmodifiableList(parts), partString);
parts.add(part);
}
_parts = ImmutableList.copyOf(parts);
} catch (InvalidPermissionStringException e) {
throw e;
} catch (Exception e) {
// Rethrow any uncaught exception as being caused by an invalid permission string
throw new InvalidPermissionStringException(e.getMessage(), _permission);
}
}
public MatchingPermission(String... parts) {
this(Joiner.on(SEPARATOR).join(parts));
}
private Iterable<String> split(String permission) {
// Use the split pattern to avoid splitting on escaped separators.
return Arrays.asList(SEPARATOR_SPLIT_PATTERN.split(permission));
}
/**
* Converts a String part into the corresponding {@link MatchingPart}.
*/
protected MatchingPart toPart(List<MatchingPart> leadingParts, String part) {
if (ANY_INDICATOR.equals(part)) {
return getAnyPart();
}
// This part is a constant string
return createConstantPart(part);
}
@Override
public boolean implies(Permission p) {
if (!(p instanceof MatchingPermission)) {
return false;
}
MatchingPermission other = (MatchingPermission) p;
int commonLength = Math.min(_parts.size(), other._parts.size());
for (int i=0; i < commonLength; i++) {
if (!_parts.get(i).implies(other._parts.get(i), other._parts.subList(0, i))) {
return false;
}
}
// If this had more parts than the other permission then only pass if all remaining parts are wildcards
while (commonLength < _parts.size()) {
if (!_parts.get(commonLength++).impliesAny()) {
return false;
}
}
// It's possible the other also has more parts, but in this case it's narrower than this permission and
// hence is still implied by it.
return true;
}
/**
* Some permissions fall into one of the following categories:
*
* <ol>
* <li>The permission is intended for validation purposes only, such as for creating a table.</li>
* <li>The permission format is deprecated and no new permissions of the format are allowed.</li>
* </ol>
*
* This method returns true if the permission should be assignable to a user/role, false otherwise.
*/
public boolean isAssignable() {
for (MatchingPart part : _parts) {
if (!part.isAssignable()) {
return false;
}
}
return true;
}
/**
* Returns a string escaped so it will be interpreted literally by the matcher. Specifically it converts all
* '|' and '*' characters to "\|" and "\*" respectively.
*/
public static String escape(String raw) {
checkNotNull(raw, "raw");
String escaped = raw;
escaped = escaped.replaceAll(UNESCAPED_WILDCARD_REGEX, WILDCARD_ESCAPE);
escaped = escapeSeparators(escaped);
return escaped;
}
/**
* Returns a string with only the separators escaped, unlike {@link #escape(String)} which also protects
* wildcards. This is useful for subclasses which have their own formatting that needs to be protected from being split.
*/
public static String escapeSeparators(String raw) {
return raw.replaceAll(UNESCAPED_SEPARATOR_REGEX, SEPARATOR_ESCAPE);
}
/**
* Returns a string with the modifications made by {@link #escapeSeparators(String)} reversed.
*/
public static String unescapeSeparators(String escaped) {
return escaped.replaceAll(ESCAPED_SEPARATOR_REGEX, SEPARATOR);
}
protected final List<MatchingPart> getParts() {
return _parts;
}
protected ConstantPart createConstantPart(String value) {
return new ConstantPart(value);
}
protected AnyPart getAnyPart() {
return AnyPart.instance();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MatchingPermission that = (MatchingPermission) o;
return _permission.equals(that._permission);
}
@Override
public int hashCode() {
return _permission.hashCode();
}
@Override
public String toString() {
return _permission;
}
}
|
|
/*******************************************************************************
* Copyright (c) 2015-2019 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.autodiff.opvalidation;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.layers.recurrent.config.LSTMConfiguration;
import org.nd4j.linalg.api.ops.impl.layers.recurrent.outputs.LSTMCellOutputs;
import org.nd4j.linalg.api.ops.impl.layers.recurrent.weights.GRUWeights;
import org.nd4j.linalg.api.ops.impl.layers.recurrent.weights.LSTMWeights;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.linalg.indexing.NDArrayIndex;
import org.nd4j.linalg.ops.transforms.Transforms;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
@Slf4j
public class RnnOpValidation extends BaseOpValidation {
public RnnOpValidation(Nd4jBackend backend) {
super(backend);
}
@Test
public void testRnnBlockCell(){
Nd4j.getRandom().setSeed(12345);
int mb = 2;
int nIn = 3;
int nOut = 4;
SameDiff sd = SameDiff.create();
SDVariable x = sd.constant(Nd4j.rand(DataType.FLOAT, mb, nIn));
SDVariable cLast = sd.constant(Nd4j.rand(DataType.FLOAT, mb, nOut));
SDVariable yLast = sd.constant(Nd4j.rand(DataType.FLOAT, mb, nOut));
SDVariable W = sd.constant(Nd4j.rand(DataType.FLOAT, (nIn+nOut), 4*nOut));
SDVariable Wci = sd.constant(Nd4j.rand(DataType.FLOAT, nOut));
SDVariable Wcf = sd.constant(Nd4j.rand(DataType.FLOAT, nOut));
SDVariable Wco = sd.constant(Nd4j.rand(DataType.FLOAT, nOut));
SDVariable b = sd.constant(Nd4j.rand(DataType.FLOAT, 4*nOut));
double fb = 1.0;
LSTMConfiguration conf = LSTMConfiguration.builder()
.peepHole(true)
.forgetBias(fb)
.clippingCellValue(0.0)
.build();
LSTMWeights weights = LSTMWeights.builder().weights(W).bias(b)
.inputPeepholeWeights(Wci).forgetPeepholeWeights(Wcf).outputPeepholeWeights(Wco).build();
LSTMCellOutputs v = sd.rnn().lstmCell(x, cLast, yLast, weights, conf); //Output order: i, c, f, o, z, h, y
List<String> toExec = new ArrayList<>();
for(SDVariable sdv : v.getAllOutputs()){
toExec.add(sdv.name());
}
//Test forward pass:
Map<String,INDArray> m = sd.output(null, toExec);
//Weights and bias order: [i, f, z, o]
//Block input (z) - post tanh:
INDArray wz_x = W.getArr().get(NDArrayIndex.interval(0,nIn), NDArrayIndex.interval(nOut, 2*nOut)); //Input weights
INDArray wz_r = W.getArr().get(NDArrayIndex.interval(nIn,nIn+nOut), NDArrayIndex.interval(nOut, 2*nOut)); //Recurrent weights
INDArray bz = b.getArr().get(NDArrayIndex.interval(nOut, 2*nOut));
INDArray zExp = x.getArr().mmul(wz_x).addiRowVector(bz); //[mb,nIn]*[nIn, nOut] + [nOut]
zExp.addi(yLast.getArr().mmul(wz_r)); //[mb,nOut]*[nOut,nOut]
Transforms.tanh(zExp, false);
INDArray zAct = m.get(toExec.get(4));
assertEquals(zExp, zAct);
//Input modulation gate (post sigmoid) - i: (note: peephole input - last time step)
INDArray wi_x = W.getArr().get(NDArrayIndex.interval(0,nIn), NDArrayIndex.interval(0, nOut)); //Input weights
INDArray wi_r = W.getArr().get(NDArrayIndex.interval(nIn,nIn+nOut), NDArrayIndex.interval(0, nOut)); //Recurrent weights
INDArray bi = b.getArr().get(NDArrayIndex.interval(0, nOut));
INDArray iExp = x.getArr().mmul(wi_x).addiRowVector(bi); //[mb,nIn]*[nIn, nOut] + [nOut]
iExp.addi(yLast.getArr().mmul(wi_r)); //[mb,nOut]*[nOut,nOut]
iExp.addi(cLast.getArr().mulRowVector(Wci.getArr())); //Peephole
Transforms.sigmoid(iExp, false);
assertEquals(iExp, m.get(toExec.get(0)));
//Forget gate (post sigmoid): (note: peephole input - last time step)
INDArray wf_x = W.getArr().get(NDArrayIndex.interval(0,nIn), NDArrayIndex.interval(2*nOut, 3*nOut)); //Input weights
INDArray wf_r = W.getArr().get(NDArrayIndex.interval(nIn,nIn+nOut), NDArrayIndex.interval(2*nOut, 3*nOut)); //Recurrent weights
INDArray bf = b.getArr().get(NDArrayIndex.interval(2*nOut, 3*nOut));
INDArray fExp = x.getArr().mmul(wf_x).addiRowVector(bf); //[mb,nIn]*[nIn, nOut] + [nOut]
fExp.addi(yLast.getArr().mmul(wf_r)); //[mb,nOut]*[nOut,nOut]
fExp.addi(cLast.getArr().mulRowVector(Wcf.getArr())); //Peephole
fExp.addi(fb);
Transforms.sigmoid(fExp, false);
assertEquals(fExp, m.get(toExec.get(2)));
//Cell state (pre tanh): tanh(z) .* sigmoid(i) + sigmoid(f) .* cLast
INDArray cExp = zExp.mul(iExp).add(fExp.mul(cLast.getArr()));
INDArray cAct = m.get(toExec.get(1));
assertEquals(cExp, cAct);
//Output gate (post sigmoid): (note: peephole input: current time step)
INDArray wo_x = W.getArr().get(NDArrayIndex.interval(0,nIn), NDArrayIndex.interval(3*nOut, 4*nOut)); //Input weights
INDArray wo_r = W.getArr().get(NDArrayIndex.interval(nIn,nIn+nOut), NDArrayIndex.interval(3*nOut, 4*nOut)); //Recurrent weights
INDArray bo = b.getArr().get(NDArrayIndex.interval(3*nOut, 4*nOut));
INDArray oExp = x.getArr().mmul(wo_x).addiRowVector(bo); //[mb,nIn]*[nIn, nOut] + [nOut]
oExp.addi(yLast.getArr().mmul(wo_r)); //[mb,nOut]*[nOut,nOut]
oExp.addi(cExp.mulRowVector(Wco.getArr())); //Peephole
Transforms.sigmoid(oExp, false);
assertEquals(oExp, m.get(toExec.get(3)));
//Cell state, post tanh
INDArray hExp = Transforms.tanh(cExp, true);
assertEquals(hExp, m.get(toExec.get(5)));
//Final output
INDArray yExp = hExp.mul(oExp);
assertEquals(yExp, m.get(toExec.get(6)));
}
@Test
public void testRnnBlockCellManualTFCompare() {
//Test case: "rnn/lstmblockcell/static_batch1_n3-2_tsLength1_noPH_noClip_fBias1_noIS"
SameDiff sd = SameDiff.create();
INDArray zero2d = Nd4j.createFromArray(new float[][]{{0,0}});
INDArray zero1d = Nd4j.createFromArray(new float[]{0,0});
SDVariable x = sd.constant(Nd4j.createFromArray(new float[][]{{0.7787856f,0.80119777f,0.72437465f}}));
SDVariable cLast = sd.constant(zero2d);
SDVariable yLast = sd.constant(zero2d);
//Weights shape: [(nIn+nOut), 4*nOut]
SDVariable W = sd.constant(Nd4j.createFromArray(-0.61977,-0.5708851,-0.38089648,-0.07994056,-0.31706482,0.21500933,-0.35454142,-0.3239095,-0.3177906,
0.39918554,-0.3115911,0.540841,0.38552666,0.34270835,-0.63456273,-0.13917702,-0.2985368,0.343238,
-0.3178353,0.017154932,-0.060259163,0.28841054,-0.6257687,0.65097713,0.24375653,-0.22315514,0.2033832,
0.24894875,-0.2062299,-0.2242794,-0.3809483,-0.023048997,-0.036284804,-0.46398938,-0.33979666,0.67012596,
-0.42168984,0.34208286,-0.0456419,0.39803517).castTo(DataType.FLOAT).reshape(5,8));
SDVariable Wci = sd.constant(zero1d);
SDVariable Wcf = sd.constant(zero1d);
SDVariable Wco = sd.constant(zero1d);
SDVariable b = sd.constant(Nd4j.zeros(DataType.FLOAT, 8));
double fb = 1.0;
LSTMConfiguration conf = LSTMConfiguration.builder()
.peepHole(false)
.forgetBias(fb)
.clippingCellValue(0.0)
.build();
LSTMWeights weights = LSTMWeights.builder().weights(W).bias(b)
.inputPeepholeWeights(Wci).forgetPeepholeWeights(Wcf).outputPeepholeWeights(Wco).build();
LSTMCellOutputs v = sd.rnn().lstmCell(x, cLast, yLast, weights, conf); //Output order: i, c, f, o, z, h, y
List<String> toExec = new ArrayList<>();
for(SDVariable sdv : v.getAllOutputs()){
toExec.add(sdv.name());
}
//Test forward pass:
Map<String,INDArray> m = sd.output(null, toExec);
INDArray out0 = Nd4j.create(new float[]{0.27817473f, 0.53092605f}, new int[]{1,2}); //Input mod gate
INDArray out1 = Nd4j.create(new float[]{-0.18100877f, 0.19417824f}, new int[]{1,2}); //CS (pre tanh)
INDArray out2 = Nd4j.create(new float[]{0.73464274f, 0.83901811f}, new int[]{1,2}); //Forget gate
INDArray out3 = Nd4j.create(new float[]{0.22481689f, 0.52692068f}, new int[]{1,2}); //Output gate
INDArray out4 = Nd4j.create(new float[]{-0.65070170f, 0.36573499f}, new int[]{1,2}); //block input
INDArray out5 = Nd4j.create(new float[]{-0.17905743f, 0.19177397f}, new int[]{1,2}); //Cell state
INDArray out6 = Nd4j.create(new float[]{-0.04025514f, 0.10104967f}, new int[]{1,2}); //Output
// for(int i=0; i<toExec.size(); i++ ){
// System.out.println(i + "\t" + m.get(toExec.get(i)));
// }
assertEquals(out0, m.get(toExec.get(0))); //Input modulation gate
assertEquals(out1, m.get(toExec.get(1))); //Cell state (pre tanh)
assertEquals(out2, m.get(toExec.get(2))); //Forget gate
assertEquals(out3, m.get(toExec.get(3))); //Output gate
assertEquals(out4, m.get(toExec.get(4))); //block input
assertEquals(out5, m.get(toExec.get(5))); //Cell state
assertEquals(out6, m.get(toExec.get(6))); //Output
}
@Test
public void testGRUCell(){
Nd4j.getRandom().setSeed(12345);
int mb = 2;
int nIn = 3;
int nOut = 4;
SameDiff sd = SameDiff.create();
SDVariable x = sd.constant(Nd4j.rand(DataType.FLOAT, mb, nIn));
SDVariable hLast = sd.constant(Nd4j.rand(DataType.FLOAT, mb, nOut));
SDVariable Wru = sd.constant(Nd4j.rand(DataType.FLOAT, (nIn+nOut), 2*nOut));
SDVariable Wc = sd.constant(Nd4j.rand(DataType.FLOAT, (nIn+nOut), nOut));
SDVariable bru = sd.constant(Nd4j.rand(DataType.FLOAT, 2*nOut));
SDVariable bc = sd.constant(Nd4j.rand(DataType.FLOAT, nOut));
double fb = 1.0;
GRUWeights weights = GRUWeights.builder()
.ruWeight(Wru)
.cWeight(Wc)
.ruBias(bru)
.cBias(bc)
.build();
List<SDVariable> v = sd.rnn().gru("gru", x, hLast, weights).getAllOutputs();
List<String> toExec = new ArrayList<>();
for(SDVariable sdv : v){
toExec.add(sdv.name());
}
//Test forward pass:
Map<String,INDArray> m = sd.output(null, toExec);
//Weights and bias order: [r, u], [c]
//Reset gate:
INDArray wr_x = Wru.getArr().get(NDArrayIndex.interval(0,nIn), NDArrayIndex.interval(0, nOut)); //Input weights
INDArray wr_r = Wru.getArr().get(NDArrayIndex.interval(nIn,nIn+nOut), NDArrayIndex.interval(0, nOut)); //Recurrent weights
INDArray br = bru.getArr().get(NDArrayIndex.interval(0, nOut));
INDArray rExp = x.getArr().mmul(wr_x).addiRowVector(br); //[mb,nIn]*[nIn, nOut] + [nOut]
rExp.addi(hLast.getArr().mmul(wr_r)); //[mb,nOut]*[nOut,nOut]
Transforms.sigmoid(rExp,false);
INDArray rAct = m.get(toExec.get(0));
assertEquals(rExp, rAct);
//Update gate:
INDArray wu_x = Wru.getArr().get(NDArrayIndex.interval(0,nIn), NDArrayIndex.interval(nOut, 2*nOut)); //Input weights
INDArray wu_r = Wru.getArr().get(NDArrayIndex.interval(nIn,nIn+nOut), NDArrayIndex.interval(nOut, 2*nOut)); //Recurrent weights
INDArray bu = bru.getArr().get(NDArrayIndex.interval(nOut, 2*nOut));
INDArray uExp = x.getArr().mmul(wu_x).addiRowVector(bu); //[mb,nIn]*[nIn, nOut] + [nOut]
uExp.addi(hLast.getArr().mmul(wu_r)); //[mb,nOut]*[nOut,nOut]
Transforms.sigmoid(uExp,false);
INDArray uAct = m.get(toExec.get(1));
assertEquals(uExp, uAct);
//c = tanh(x * Wcx + Wcr * (hLast .* r))
INDArray Wcx = Wc.getArr().get(NDArrayIndex.interval(0,nIn), NDArrayIndex.all());
INDArray Wcr = Wc.getArr().get(NDArrayIndex.interval(nIn, nIn+nOut), NDArrayIndex.all());
INDArray cExp = x.getArr().mmul(Wcx);
cExp.addi(hLast.getArr().mul(rExp).mmul(Wcr));
cExp.addiRowVector(bc.getArr());
Transforms.tanh(cExp, false);
assertEquals(cExp, m.get(toExec.get(2)));
//h = u * hLast + (1-u) * c
INDArray hExp = uExp.mul(hLast.getArr()).add(uExp.rsub(1.0).mul(cExp));
assertEquals(hExp, m.get(toExec.get(3)));
}
}
|
|
package org.drip.sample.funding;
import java.util.List;
import org.drip.analytics.date.*;
import org.drip.analytics.support.*;
import org.drip.function.r1tor1.QuadraticRationalShapeControl;
import org.drip.param.creator.*;
import org.drip.param.market.CurveSurfaceQuoteContainer;
import org.drip.param.period.*;
import org.drip.param.valuation.*;
import org.drip.product.creator.*;
import org.drip.product.rates.*;
import org.drip.quant.common.FormatUtil;
import org.drip.service.env.EnvManager;
import org.drip.spline.basis.PolynomialFunctionSetParams;
import org.drip.spline.params.*;
import org.drip.spline.stretch.*;
import org.drip.state.creator.ScenarioDiscountCurveBuilder;
import org.drip.state.discount.*;
import org.drip.state.estimator.LatentStateStretchBuilder;
import org.drip.state.identifier.*;
import org.drip.state.inference.*;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*!
* Copyright (C) 2017 Lakshmi Krishnamurthy
* Copyright (C) 2016 Lakshmi Krishnamurthy
* Copyright (C) 2015 Lakshmi Krishnamurthy
* Copyright (C) 2014 Lakshmi Krishnamurthy
*
* This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
* libraries targeting analysts and developers
* https://lakshmidrip.github.io/DRIP/
*
* DRIP is composed of four main libraries:
*
* - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
* - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
* - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
* - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
*
* - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
* Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
* Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
* Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
* Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
*
* - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
* Incorporator, Holdings Constraint, and Transaction Costs.
*
* - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
*
* - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
*
* 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.
*/
/**
* CustomFundingCurveBuilder funding curve calibration and input instrument calibration quote recovery. It
* shows the following:
* - Construct the Array of Deposit/Swap Instruments and their Quotes from the given set of parameters.
* - Construct the Deposit/Swap Instrument Set Stretch Builder.
* - Set up the Linear Curve Calibrator using the following parameters:
* - Cubic Exponential Mixture Basis Spline Set
* - Ck = 2, Segment Curvature Penalty = 2
* - Quadratic Rational Shape Controller
* - Natural Boundary Setting
* - Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array
* of Cash and Swap Stretches.
* - Cross-Comparison of the Cash/Swap Calibration Instrument "Rate" metric across the different curve
* construction methodologies.
*
* @author Lakshmi Krishnamurthy
*/
public class CustomFundingCurveBuilder {
/*
* Construct the Array of Deposit Instruments from the given set of parameters
*
* USE WITH CARE: This sample ignores errors and does not handle exceptions.
*/
private static final SingleStreamComponent[] DepositInstrumentsFromMaturityDays (
final JulianDate dtEffective,
final String strCurrency,
final int[] aiDay)
throws Exception
{
SingleStreamComponent[] aDeposit = new SingleStreamComponent[aiDay.length];
ComposableFloatingUnitSetting cfus = new ComposableFloatingUnitSetting (
"3M",
CompositePeriodBuilder.EDGE_DATE_SEQUENCE_SINGLE,
null,
ForwardLabel.Create (
strCurrency,
"3M"
),
CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE,
0.
);
CompositePeriodSetting cps = new CompositePeriodSetting (
4,
"3M",
strCurrency,
null,
1.,
null,
null,
null,
null
);
CashSettleParams csp = new CashSettleParams (
0,
strCurrency,
0
);
for (int i = 0; i < aiDay.length; ++i) {
aDeposit[i] = new SingleStreamComponent (
"DEPOSIT_" + aiDay[i],
new Stream (
CompositePeriodBuilder.FloatingCompositeUnit (
CompositePeriodBuilder.EdgePair (
dtEffective,
dtEffective.addBusDays (
aiDay[i],
strCurrency
)
),
cps,
cfus
)
),
csp
);
aDeposit[i].setPrimaryCode (aiDay[i] + "D");
}
return aDeposit;
}
/*
* Construct the Array of Swap Instruments from the given set of parameters
*
* USE WITH CARE: This sample ignores errors and does not handle exceptions.
*/
private static final FixFloatComponent[] SwapInstrumentsFromMaturityTenor (
final JulianDate dtEffective,
final String strCurrency,
final String[] astrMaturityTenor)
throws Exception
{
FixFloatComponent[] aIRS = new FixFloatComponent[astrMaturityTenor.length];
UnitCouponAccrualSetting ucasFixed = new UnitCouponAccrualSetting (
2,
"Act/360",
false,
"Act/360",
false,
strCurrency,
true,
CompositePeriodBuilder.ACCRUAL_COMPOUNDING_RULE_GEOMETRIC
);
ComposableFloatingUnitSetting cfusFloating = new ComposableFloatingUnitSetting (
"6M",
CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR,
null,
ForwardLabel.Create (
strCurrency,
"6M"
),
CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE,
0.
);
ComposableFixedUnitSetting cfusFixed = new ComposableFixedUnitSetting (
"6M",
CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR,
null,
0.,
0.,
strCurrency
);
CompositePeriodSetting cpsFloating = new CompositePeriodSetting (
2,
"6M",
strCurrency,
null,
-1.,
null,
null,
null,
null
);
CompositePeriodSetting cpsFixed = new CompositePeriodSetting (
2,
"6M",
strCurrency,
null,
1.,
null,
null,
null,
null
);
CashSettleParams csp = new CashSettleParams (
0,
strCurrency,
0
);
for (int i = 0; i < astrMaturityTenor.length; ++i) {
List<Integer> lsFixedStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
dtEffective,
"6M",
astrMaturityTenor[i],
null
);
List<Integer> lsFloatingStreamEdgeDate = CompositePeriodBuilder.RegularEdgeDates (
dtEffective,
"6M",
astrMaturityTenor[i],
null
);
Stream floatingStream = new Stream (
CompositePeriodBuilder.FloatingCompositeUnit (
lsFloatingStreamEdgeDate,
cpsFloating,
cfusFloating
)
);
Stream fixedStream = new Stream (
CompositePeriodBuilder.FixedCompositeUnit (
lsFixedStreamEdgeDate,
cpsFixed,
ucasFixed,
cfusFixed
)
);
FixFloatComponent irs = new FixFloatComponent (
fixedStream,
floatingStream,
csp
);
irs.setPrimaryCode ("IRS." + astrMaturityTenor[i] + "." + strCurrency);
aIRS[i] = irs;
}
return aIRS;
}
/*
* This sample demonstrates discount curve calibration and input instrument calibration quote recovery.
* It shows the following:
* - Construct the Array of Cash/Swap Instruments and their Quotes from the given set of parameters.
* - Construct the Cash/Swap Instrument Set Stretch Builder.
* - Set up the Linear Curve Calibrator using the following parameters:
* - Cubic Exponential Mixture Basis Spline Set
* - Ck = 2, Segment Curvature Penalty = 2
* - Quadratic Rational Shape Controller
* - Natural Boundary Setting
* - Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array
* of Cash and Swap Stretches.
* - Cross-Comparison of the Cash/Swap Calibration Instrument "Rate" metric across the different curve
* construction methodologies.
*
* USE WITH CARE: This sample ignores errors and does not handle exceptions.
*/
private static final void OTCInstrumentCurve (
final JulianDate dtSpot,
final String strCurrency)
throws Exception
{
/*
* Construct the Array of Deposit Instruments and their Quotes from the given set of parameters
*/
SingleStreamComponent[] aDepositComp = DepositInstrumentsFromMaturityDays (
dtSpot,
strCurrency,
new int[] {
1, 2, 7, 14, 30, 60
}
);
double[] adblDepositQuote = new double[] {
0.0013, 0.0017, 0.0017, 0.0018, 0.0020, 0.0023
};
/*
* Construct the Deposit Instrument Set Stretch Builder
*/
LatentStateStretchSpec depositStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
"DEPOSIT",
aDepositComp,
"ForwardRate",
adblDepositQuote
);
/*
* Construct the Array of EDF Instruments and their Quotes from the given set of parameters
*/
SingleStreamComponent[] aEDFComp = SingleStreamComponentBuilder.ForwardRateFuturesPack (
dtSpot,
8,
strCurrency
);
double[] adblEDFQuote = new double[] {
0.0027, 0.0032, 0.0041, 0.0054, 0.0077, 0.0104, 0.0134, 0.0160
};
/*
* Construct the EDF Instrument Set Stretch Builder
*/
LatentStateStretchSpec edfStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
"EDF",
aEDFComp,
"ForwardRate",
adblEDFQuote
);
/*
* Construct the Array of Swap Instruments and their Quotes from the given set of parameters
*/
FixFloatComponent[] aSwapComp = SwapInstrumentsFromMaturityTenor (
dtSpot,
strCurrency,
new String[] {
"4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", "30Y", "40Y", "50Y"
}
);
double[] adblSwapQuote = new double[] {
0.0166, 0.0206, 0.0241, 0.0269, 0.0292, 0.0311, 0.0326, 0.0340, 0.0351, 0.0375, 0.0393, 0.0402, 0.0407, 0.0409, 0.0409
};
/*
* Construct the Swap Instrument Set Stretch Builder
*/
LatentStateStretchSpec swapStretch = LatentStateStretchBuilder.ForwardFundingStretchSpec (
"SWAP",
aSwapComp,
"SwapRate",
adblSwapQuote
);
LatentStateStretchSpec[] aStretchSpec = new LatentStateStretchSpec[] {
depositStretch,
edfStretch,
swapStretch
};
/*
* Set up the Linear Curve Calibrator using the following parameters:
* - Cubic Exponential Mixture Basis Spline Set
* - Ck = 2, Segment Curvature Penalty = 2
* - Quadratic Rational Shape Controller
* - Natural Boundary Setting
*/
LinearLatentStateCalibrator lcc = new LinearLatentStateCalibrator (
new SegmentCustomBuilderControl (
MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
new PolynomialFunctionSetParams (4),
SegmentInelasticDesignControl.Create (
2,
2
),
new ResponseScalingShapeControl (
true,
new QuadraticRationalShapeControl (0.)
),
null
),
BoundarySettings.NaturalStandard(),
MultiSegmentSequence.CALIBRATE,
null,
null
);
ValuationParams valParams = new ValuationParams (
dtSpot,
dtSpot,
strCurrency
);
/*
* Construct the Shape Preserving Discount Curve by applying the linear curve calibrator to the array
* of Deposit, Futures, and Swap Stretches.
*/
MergedDiscountForwardCurve dc = ScenarioDiscountCurveBuilder.ShapePreservingDFBuild (
strCurrency,
lcc,
aStretchSpec,
valParams,
null,
null,
null,
1.
);
CurveSurfaceQuoteContainer csqs = MarketParamsBuilder.Create (
dc,
null,
null,
null,
null,
null,
null
);
/*
* Cross-Comparison of the Deposit Calibration Instrument "Rate" metric across the different curve
* construction methodologies.
*/
System.out.println ("\n\n\t----------------------------------------------------------------");
System.out.println ("\t DEPOSIT INSTRUMENTS CALIBRATION RECOVERY");
System.out.println ("\t----------------------------------------------------------------");
for (int i = 0; i < aDepositComp.length; ++i)
System.out.println ("\t[" + aDepositComp[i].maturityDate() + "] = " +
FormatUtil.FormatDouble (aDepositComp[i].measureValue (valParams, null, csqs,
null, "Rate"), 1, 6, 1.) + " | " + FormatUtil.FormatDouble (adblDepositQuote[i], 1, 6, 1.));
System.out.println ("\t----------------------------------------------------------------");
/*
* Cross-Comparison of the EDF Calibration Instrument "Rate" metric across the different curve
* construction methodologies.
*/
System.out.println ("\n\t----------------------------------------------------------------");
System.out.println ("\t EDF INSTRUMENTS CALIBRATION RECOVERY");
System.out.println ("\t----------------------------------------------------------------");
for (int i = 0; i < aEDFComp.length; ++i)
System.out.println ("\t[" + aEDFComp[i].maturityDate() + "] = " +
FormatUtil.FormatDouble (aEDFComp[i].measureValue (valParams, null, csqs, null, "Rate"), 1, 6, 1.)
+ " | " + FormatUtil.FormatDouble (adblEDFQuote[i], 1, 6, 1.));
System.out.println ("\t----------------------------------------------------------------");
/*
* Cross-Comparison of the Swap Calibration Instrument "Rate" metric across the different curve
* construction methodologies.
*/
System.out.println ("\n\t----------------------------------------------------------------");
System.out.println ("\t SWAP INSTRUMENTS CALIBRATION RECOVERY");
System.out.println ("\t----------------------------------------------------------------");
for (int i = 0; i < aSwapComp.length; ++i)
System.out.println ("\t[" + aSwapComp[i].maturityDate() + "] = " +
FormatUtil.FormatDouble (aSwapComp[i].measureValue (valParams, null, csqs, null, "CalibSwapRate"), 1, 6, 1.)
+ " | " + FormatUtil.FormatDouble (adblSwapQuote[i], 1, 6, 1.) + " | " +
FormatUtil.FormatDouble (aSwapComp[i].measureValue (valParams, null, csqs, null, "FairPremium"), 1, 6, 1.));
System.out.println ("\t----------------------------------------------------------------");
}
public static final void main (
final String[] astrArgs)
throws Exception
{
/*
* Initialize the Credit Analytics Library
*/
EnvManager.InitEnv ("");
JulianDate dtToday = DateUtil.Today().addTenor ("0D");
String strCurrency = "USD";
OTCInstrumentCurve (
dtToday,
strCurrency
);
}
}
|
|
package com.suscipio_solutions.consecro_mud.Abilities.Spells;
import java.util.HashSet;
import java.util.Vector;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Areas.interfaces.Area;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CharStats;
import com.suscipio_solutions.consecro_mud.Common.interfaces.PhyStats;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.Races.interfaces.Race;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMProps;
import com.suscipio_solutions.consecro_mud.core.CMath;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
@SuppressWarnings("rawtypes")
public class Spell_ImprovedPolymorph extends Spell
{
@Override public String ID() { return "Spell_ImprovedPolymorph"; }
private final static String localizedName = CMLib.lang().L("Improved Polymorph");
@Override public String name() { return localizedName; }
private final static String localizedStaticDisplay = CMLib.lang().L("(Improved Polymorph)");
@Override public String displayText() { return localizedStaticDisplay; }
@Override protected int canAffectCode(){return CAN_MOBS;}
@Override public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_TRANSMUTATION;}
@Override public int abstractQuality(){ return Ability.QUALITY_OK_OTHERS;}
Race newRace=null;
@Override
public void affectPhyStats(Physical affected, PhyStats affectableStats)
{
super.affectPhyStats(affected,affectableStats);
if(newRace!=null)
{
if(affected.name().indexOf(' ')>0)
affectableStats.setName(L("a @x1 called @x2",newRace.name(),affected.name()));
else
affectableStats.setName(L("@x1 the @x2",affected.name(),newRace.name()));
final int oldAdd=affectableStats.weight()-affected.basePhyStats().weight();
newRace.setHeightWeight(affectableStats,'M');
if(oldAdd>0) affectableStats.setWeight(affectableStats.weight()+oldAdd);
}
}
@Override
public void affectCharStats(MOB affected, CharStats affectableStats)
{
super.affectCharStats(affected,affectableStats);
if(newRace!=null)
{
final int oldCat=affected.baseCharStats().ageCategory();
affectableStats.setMyRace(newRace);
if((affected.baseCharStats().getStat(CharStats.STAT_AGE)>0)
&&(newRace.getAgingChart()[oldCat]<Short.MAX_VALUE))
affectableStats.setStat(CharStats.STAT_AGE,newRace.getAgingChart()[oldCat]);
}
}
@Override
public void unInvoke()
{
// undo the affects of this spell
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
super.unInvoke();
if(canBeUninvoked())
if((mob.location()!=null)&&(!mob.amDead()))
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> morph(s) back to <S-HIS-HER> normal form."));
}
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
if(target instanceof MOB)
{
if((mob.getVictim()==target)&&(target.fetchEffect(ID())==null))
return Ability.QUALITY_MALICIOUS;
}
}
return super.castingQuality(mob,target);
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
if(commands.size()==0)
{
mob.tell(L("You need to specify what to turn your target into!"));
return false;
}
final String race=(String)commands.lastElement();
commands.removeElement(commands.lastElement());
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null) return false;
if((target==mob)&&(!auto))
{
mob.tell(L("You cannot hold enough energy to cast this on yourself."));
return false;
}
Race R=CMClass.getRace(race);
if((R==null)&&(!auto))
{
if(mob.isMonster())
{
R=CMClass.randomRace();
for(int i=0;i<10;i++)
{
if((R!=null)
&&(CMProps.isTheme(R.availabilityCode()))
&&(R!=mob.charStats().getMyRace()))
break;
R=CMClass.randomRace();
}
}
else
{
mob.tell(L("You can't turn @x1 into a '@x2'!",target.name(mob),race));
return false;
}
}
else
if(R==null)
{
R=CMClass.randomRace();
for(int i=0;i<10;i++)
{
if((R!=null)
&&(CMProps.isTheme(R.availabilityCode()))
&&(R!=mob.charStats().getMyRace()))
break;
R=CMClass.randomRace();
}
}
if(target.baseCharStats().getMyRace() != target.charStats().getMyRace())
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already polymorphed."));
return false;
}
if((R!=null)&&(!CMath.bset(R.availabilityCode(),Area.THEME_FANTASY)))
{
mob.tell(L("You can't turn @x1 into a '@x2'!",target.name(mob),R.name()));
return false;
}
// the invoke method for spells receives as
// parameters the invoker, and the REMAINING
// command line parameters, divided into words,
// and added as String objects to a vector.
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
int targetStatTotal=0;
final MOB fakeMOB=CMClass.getFactoryMOB();
for(final int s: CharStats.CODES.BASECODES())
{
targetStatTotal+=target.baseCharStats().getStat(s);
fakeMOB.baseCharStats().setStat(s,target.baseCharStats().getStat(s));
}
fakeMOB.baseCharStats().setMyRace(R);
fakeMOB.recoverCharStats();
fakeMOB.recoverPhyStats();
fakeMOB.recoverMaxState();
fakeMOB.recoverCharStats();
fakeMOB.recoverPhyStats();
fakeMOB.recoverMaxState();
int fakeStatTotal=0;
for(final int s: CharStats.CODES.BASECODES())
fakeStatTotal+=fakeMOB.charStats().getStat(s);
int statDiff=targetStatTotal-fakeStatTotal;
if(CMLib.flags().canMove(fakeMOB)!=CMLib.flags().canMove(target)) statDiff+=100;
if(CMLib.flags().canBreatheHere(fakeMOB,target.location())!=CMLib.flags().canBreatheHere(target,target.location())) statDiff+=50;
if(CMLib.flags().canSee(fakeMOB)!=CMLib.flags().canSee(target)) statDiff+=25;
if(CMLib.flags().canHear(fakeMOB)!=CMLib.flags().canHear(target)) statDiff+=10;
if(CMLib.flags().canSpeak(fakeMOB)!=CMLib.flags().canSpeak(target)) statDiff+=25;
if(CMLib.flags().canSmell(fakeMOB)!=CMLib.flags().canSmell(target)) statDiff+=5;
fakeMOB.destroy();
if(statDiff<0) statDiff=statDiff*-1;
final int levelDiff=((mob.phyStats().level()+(2*getXLEVELLevel(mob)))-target.phyStats().level());
boolean success=proficiencyCheck(mob,levelDiff-statDiff,auto);
if(success&&(!auto)&&(!mob.mayIFight(target))&&(mob!=target)&&(!mob.getGroupMembers(new HashSet<MOB>()).contains(target)))
{
mob.tell(L("@x1 is a player, so you must be group members, or your playerkill flags must be on for this to work.",target.name(mob)));
success=false;
}
if((success)&&((auto)||((levelDiff-statDiff)>-100)))
{
// it worked, so build a copy of this ability,
// and add it to the affects list of the
// affected MOB. Then tell everyone else
// what happened.
invoker=mob;
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> form(s) an improved spell around <T-NAMESELF>.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(msg.value()<=0)
{
newRace=R;
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> become(s) a @x1!",newRace.name()));
success=beneficialAffect(mob,target,asLevel,0)!=null;
target.recoverCharStats();
CMLib.utensils().confirmWearability(target);
}
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> form(s) an improved spell around <T-NAMESELF>, but the spell fizzles."));
// return whether it worked
return success;
}
}
|
|
package org.buddycloud.channelserver.packetprocessor.iq.namespace.register;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import org.apache.log4j.Logger;
import org.buddycloud.channelserver.Configuration;
import org.buddycloud.channelserver.channel.ChannelManager;
import org.buddycloud.channelserver.channel.Conf;
import org.buddycloud.channelserver.db.NodeStore.Transaction;
import org.buddycloud.channelserver.db.exception.NodeStoreException;
import org.buddycloud.channelserver.packetprocessor.PacketProcessor;
import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.JabberPubsub;
import org.buddycloud.channelserver.pubsub.affiliation.Affiliations;
import org.buddycloud.channelserver.pubsub.event.Event;
import org.buddycloud.channelserver.pubsub.model.NodeItem;
import org.buddycloud.channelserver.pubsub.model.NodeMembership;
import org.buddycloud.channelserver.pubsub.model.NodeSubscription;
import org.buddycloud.channelserver.pubsub.subscription.Subscriptions;
import org.buddycloud.channelserver.utils.node.item.payload.Buddycloud;
import org.dom4j.Element;
import org.xmpp.packet.IQ;
import org.xmpp.packet.IQ.Type;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.PacketError.Condition;
import org.xmpp.resultsetmanagement.ResultSet;
public class UnregisterSet implements PacketProcessor<IQ> {
public static final String ELEMENT_NAME = "query";
private static final Logger LOGGER = Logger.getLogger(UnregisterSet.class);
private final BlockingQueue<Packet> outQueue;
private final ChannelManager channelManager;
public UnregisterSet(BlockingQueue<Packet> outQueue, ChannelManager channelManager) {
this.outQueue = outQueue;
this.channelManager = channelManager;
}
@Override
public void process(IQ request) throws Exception {
JID actorJID = null;
Element removeEl = request.getElement().element(
"query").element("remove");
Element actorEl = removeEl.element("actor");
boolean isRemote = actorEl != null;
if (isRemote) {
actorJID = new JID(actorEl.getTextTrim());
if (!checkDomain(request, actorJID)) {
return;
}
} else {
actorJID = new JID(request.getFrom().toBareJID());
}
unregister(request, actorJID, isRemote);
}
private boolean checkDomain(IQ request, JID actorJID) throws InterruptedException {
if (!request.getFrom().getDomain().contains(actorJID.getDomain())) {
fail(request, org.xmpp.packet.PacketError.Condition.bad_request,
org.xmpp.packet.PacketError.Type.cancel);
return false;
}
return true;
}
private void unregister(IQ request, JID actorJID, boolean isRemote) throws Exception {
LOGGER.debug("Processing unregister request from " + request.getFrom());
if (!validateSingleChildElement(request)) {
failBadRequest(request);
return;
}
if (!isRemote && !userRegistered(actorJID)) {
failRegistrationRequired(request);
return;
}
Transaction t = null;
try {
t = channelManager.beginTransaction();
List<Packet> notifications = new LinkedList<Packet>();
Set<String> remoteDomains = getRemoteDomains();
ResultSet<NodeMembership> userMemberships = channelManager.getUserMemberships(actorJID);
for (NodeMembership userMembership : userMemberships) {
String nodeId = userMembership.getNodeId();
if (isPersonal(nodeId) || isSingleOwner(nodeId, actorJID)) {
channelManager.deleteNode(nodeId);
if (Configuration.getInstance().isLocalNode(nodeId)) {
addDeleteNodeNotifications(nodeId, notifications);
}
}
if (!isRemote) {
addUnsubscribeFromNodeNotifications(actorJID,
userMembership.getNodeId(), notifications);
}
}
ResultSet<NodeItem> userItems = channelManager.getUserPublishedItems(actorJID);
for (NodeItem userItem : userItems) {
if (Configuration.getInstance().isLocalNode(userItem.getNodeId())) {
addDeleteItemNotifications(userItem.getNodeId(), userItem.getId(), notifications);
}
}
channelManager.deleteUserItems(actorJID);
channelManager.deleteUserSubscriptions(actorJID);
channelManager.deleteUserAffiliations(actorJID);
outQueue.put(IQ.createResultIQ(request));
if (!isRemote) {
makeRemoteRequests(request, remoteDomains);
}
sendNotifications(notifications);
t.commit();
} finally {
if (t != null) {
t.close();
}
}
}
private void sendNotifications(List<Packet> notifications) throws InterruptedException {
for (Packet notification : notifications) {
outQueue.put(notification);
}
}
private void makeRemoteRequests(IQ request, Set<String> remoteDomains) throws Exception {
for (String remoteDomain : remoteDomains) {
IQ remoteRequest = request.createCopy();
remoteRequest.getElement().addAttribute("remote-server-discover", "false");
remoteRequest.setTo(remoteDomain);
Element actor = remoteRequest.getElement()
.element("query").element("remove")
.addElement("actor", Buddycloud.NS);
actor.addText(request.getFrom().toBareJID());
outQueue.put(remoteRequest);
}
}
private Set<String> getRemoteDomains() throws NodeStoreException {
ArrayList<String> nodeList = channelManager.getNodeList();
Set<String> remoteDomains = new HashSet<String>();
for (String node : nodeList) {
try {
if (!Configuration.getInstance().isLocalNode(node)) {
remoteDomains.add(new JID(node.split("/")[2]).getDomain());
}
} catch (IllegalArgumentException e) {
// Ignore bad formatted nodes
}
}
return remoteDomains;
}
private void addUnsubscribeFromNodeNotifications(JID userJid,
String node, List<Packet> notifications) throws NodeStoreException {
ResultSet<NodeSubscription> subscribers = channelManager
.getNodeSubscriptionListeners(node);
Message messagePacket = createUnsubscribeNotification(userJid, node);
if (subscribers != null) {
for (NodeSubscription subscriber : subscribers) {
Message notification = messagePacket.createCopy();
notification.setTo(subscriber.getListener());
notifications.add(notification);
}
}
Collection<JID> adminUsers = Configuration.getInstance()
.getAdminUsers();
for (JID admin : adminUsers) {
Message notification = messagePacket.createCopy();
notification.setTo(admin);
notifications.add(notification);
}
}
private Message createUnsubscribeNotification(JID userJid, String node) {
Message messagePacket = new Message();
Element messageEl = messagePacket.getElement();
messageEl.addAttribute("remote-server-discover", "false");
Element event = messageEl.addElement("event", Event.NAMESPACE);
Element subscription = event.addElement("subscription");
messageEl.addAttribute("type", "headline");
subscription.addAttribute("subscription", "none");
subscription.addAttribute("jid", userJid.toBareJID());
subscription.addAttribute("node", node);
return messagePacket;
}
private void addDeleteItemNotifications(String node, String itemId,
List<Packet> notifications) throws NodeStoreException {
ResultSet<NodeSubscription> subscriptions = channelManager
.getNodeSubscriptionListeners(node);
Message notification = createItemDeleteNotificationMessage(node, itemId);
if (subscriptions != null) {
for (NodeSubscription subscription : subscriptions) {
if (subscription.getSubscription().equals(Subscriptions.subscribed)) {
notification.setTo(subscription.getListener().toString());
notifications.add(notification);
}
}
}
Collection<JID> adminUsers = Configuration.getInstance()
.getAdminUsers();
for (JID admin : adminUsers) {
notification.setTo(admin);
notifications.add(notification);
}
}
private Message createItemDeleteNotificationMessage(String node, String itemId) {
Message notification = new Message();
notification.setType(Message.Type.headline);
notification.getElement().addAttribute("remote-server-discover", "false");
Element event = notification.addChildElement("event",
JabberPubsub.NS_PUBSUB_EVENT);
Element items = event.addElement("items");
items.addAttribute("node", node);
Element retract = items.addElement("retract");
retract.addAttribute("id", itemId);
return notification;
}
private void addDeleteNodeNotifications(String node, List<Packet> notifications) throws Exception {
ResultSet<NodeSubscription> subscriptions = channelManager
.getNodeSubscriptionListeners(node);
Message notification = createNodeDeletedNotificationMessage(node);
if (subscriptions != null) {
for (NodeSubscription subscription : subscriptions) {
notification.setTo(subscription.getListener().toString());
notifications.add(notification.createCopy());
}
}
Collection<JID> adminUsers = Configuration.getInstance()
.getAdminUsers();
for (JID admin : adminUsers) {
notification.setTo(admin);
notifications.add(notification.createCopy());
}
}
private Message createNodeDeletedNotificationMessage(String node) {
Message notification = new Message();
notification.setType(Message.Type.headline);
notification.getElement().addAttribute("remote-server-discover", "false");
Element eventEl = notification.addChildElement("event",
JabberPubsub.NS_PUBSUB_EVENT);
Element deleteEl = eventEl.addElement("delete");
deleteEl.addAttribute("node", node);
return notification;
}
private boolean isSingleOwner(String nodeId, JID userJid) throws NodeStoreException {
ResultSet<NodeMembership> nodeMemberships = channelManager.getNodeMemberships(nodeId);
int ownerCount = 0;
boolean isOwner = false;
for (NodeMembership nodeMembership : nodeMemberships) {
if (nodeMembership.getAffiliation().equals(Affiliations.owner)) {
ownerCount++;
if (nodeMembership.getUser().equals(userJid)) {
isOwner = true;
}
}
}
return isOwner && ownerCount == 1;
}
private boolean isPersonal(String nodeId) throws NodeStoreException {
String channelType = channelManager.getNodeConfValue(nodeId, Conf.CHANNEL_TYPE);
return channelType != null && channelType.equals("personal");
}
private boolean validateSingleChildElement(IQ request) {
return request.getElement().element("query").elements().size() == 1;
}
private void failBadRequest(IQ request) throws InterruptedException {
fail(request,
org.xmpp.packet.PacketError.Condition.bad_request,
org.xmpp.packet.PacketError.Type.modify);
}
private void failRegistrationRequired(IQ request) throws InterruptedException {
fail(request,
org.xmpp.packet.PacketError.Condition.registration_required,
org.xmpp.packet.PacketError.Type.auth);
}
private void fail(IQ request, Condition condition, org.xmpp.packet.PacketError.Type type) throws InterruptedException {
IQ reply = IQ.createResultIQ(request);
reply.setType(Type.error);
PacketError pe = new PacketError(condition, type);
reply.setError(pe);
outQueue.put(reply);
}
private boolean userRegistered(JID actorJID) throws Exception {
return channelManager.nodeExists("/user/" + actorJID.toBareJID() + "/posts");
}
}
|
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.functions.runtime;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.hotspot.BufferPoolsExports;
import io.prometheus.client.hotspot.ClassLoadingExports;
import io.prometheus.client.hotspot.GarbageCollectorExports;
import io.prometheus.client.hotspot.MemoryPoolsExports;
import io.prometheus.client.hotspot.StandardExports;
import io.prometheus.client.hotspot.ThreadExports;
import io.prometheus.client.hotspot.VersionInfoExports;
import io.prometheus.jmx.JmxCollector;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.common.util.ObjectMapperFactory;
import org.apache.pulsar.common.functions.AuthenticationConfig;
import org.apache.pulsar.functions.instance.InstanceConfig;
import org.apache.pulsar.functions.instance.go.GoInstanceConfig;
import org.apache.pulsar.functions.instance.stats.FunctionCollectorRegistry;
import org.apache.pulsar.functions.proto.Function;
import org.apache.pulsar.functions.utils.FunctionCommon;
import javax.management.MalformedObjectNameException;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* Util class for common runtime functionality.
*/
@Slf4j
public class RuntimeUtils {
private static final String FUNCTIONS_EXTRA_DEPS_PROPERTY = "pulsar.functions.extra.dependencies.dir";
public static final String FUNCTIONS_INSTANCE_CLASSPATH = "pulsar.functions.instance.classpath";
public static List<String> composeCmd(InstanceConfig instanceConfig,
String instanceFile,
String extraDependenciesDir, /* extra dependencies for running instances */
String logDirectory,
String originalCodeFileName,
String pulsarServiceUrl,
String stateStorageServiceUrl,
AuthenticationConfig authConfig,
String shardId,
Integer grpcPort,
Long expectedHealthCheckInterval,
String logConfigFile,
String secretsProviderClassName,
String secretsProviderConfig,
Boolean installUserCodeDependencies,
String pythonDependencyRepository,
String pythonExtraDependencyRepository,
String narExtractionDirectory,
String functionInstanceClassPath,
String pulsarWebServiceUrl) throws Exception {
final List<String> cmd = getArgsBeforeCmd(instanceConfig, extraDependenciesDir);
cmd.addAll(getCmd(instanceConfig, instanceFile, extraDependenciesDir, logDirectory,
originalCodeFileName, pulsarServiceUrl, stateStorageServiceUrl,
authConfig, shardId, grpcPort, expectedHealthCheckInterval,
logConfigFile, secretsProviderClassName, secretsProviderConfig,
installUserCodeDependencies, pythonDependencyRepository,
pythonExtraDependencyRepository, narExtractionDirectory,
functionInstanceClassPath, false, pulsarWebServiceUrl));
return cmd;
}
public static List<String> getArgsBeforeCmd(InstanceConfig instanceConfig, String extraDependenciesDir) {
final List<String> args = new LinkedList<>();
if (instanceConfig.getFunctionDetails().getRuntime() == Function.FunctionDetails.Runtime.JAVA) {
//no-op
} else if (instanceConfig.getFunctionDetails().getRuntime() == Function.FunctionDetails.Runtime.PYTHON) {
// add `extraDependenciesDir` to python package searching path
if (StringUtils.isNotEmpty(extraDependenciesDir)) {
args.add("PYTHONPATH=${PYTHONPATH}:" + extraDependenciesDir);
}
}
return args;
}
/**
* Different from python and java function, Go function uploads a complete executable file(including:
* instance file + user code file). Its parameter list is provided to the broker in the form of a yaml file,
* the advantage of this approach is that backward compatibility is guaranteed.
*
* In Java and Python the instance is managed by broker (or function worker) so the changes in command line
* is under control; but in Go the instance is compiled with the user function, so pulsar doesn't have the
* control what instance is used in the function. Hence in order to support BC for go function, we can't
* dynamically add more commandline arguments. Using an instance config to pass the parameters from function
* worker to go instance is the best way for maintaining the BC.
* <p>
* When we run the go function, we only need to specify the location of the go-function file and the yaml file.
* The content of the yaml file will be automatically generated according to the content provided by instanceConfig.
*/
public static List<String> getGoInstanceCmd(InstanceConfig instanceConfig,
String originalCodeFileName,
String pulsarServiceUrl,
boolean k8sRuntime) throws IOException {
final List<String> args = new LinkedList<>();
GoInstanceConfig goInstanceConfig = new GoInstanceConfig();
if (instanceConfig.getClusterName() != null) {
goInstanceConfig.setClusterName(instanceConfig.getClusterName());
}
if (instanceConfig.getInstanceId() != 0) {
goInstanceConfig.setInstanceID(instanceConfig.getInstanceId());
}
if (instanceConfig.getFunctionId() != null) {
goInstanceConfig.setFuncID(instanceConfig.getFunctionId());
}
if (instanceConfig.getFunctionVersion() != null) {
goInstanceConfig.setFuncVersion(instanceConfig.getFunctionVersion());
}
if (instanceConfig.getFunctionDetails().getAutoAck()) {
goInstanceConfig.setAutoAck(instanceConfig.getFunctionDetails().getAutoAck());
}
if (instanceConfig.getFunctionDetails().getTenant() != null) {
goInstanceConfig.setTenant(instanceConfig.getFunctionDetails().getTenant());
}
if (instanceConfig.getFunctionDetails().getNamespace() != null) {
goInstanceConfig.setNameSpace(instanceConfig.getFunctionDetails().getNamespace());
}
if (instanceConfig.getFunctionDetails().getName() != null) {
goInstanceConfig.setName(instanceConfig.getFunctionDetails().getName());
}
if (instanceConfig.getFunctionDetails().getLogTopic() != null) {
goInstanceConfig.setLogTopic(instanceConfig.getFunctionDetails().getLogTopic());
}
if (instanceConfig.getFunctionDetails().getProcessingGuarantees() != null) {
goInstanceConfig.setProcessingGuarantees(instanceConfig.getFunctionDetails().getProcessingGuaranteesValue());
}
if (instanceConfig.getFunctionDetails().getSecretsMap() != null) {
goInstanceConfig.setSecretsMap(instanceConfig.getFunctionDetails().getSecretsMap());
}
if (instanceConfig.getFunctionDetails().getUserConfig() != null) {
goInstanceConfig.setUserConfig(instanceConfig.getFunctionDetails().getUserConfig());
}
if (instanceConfig.getFunctionDetails().getParallelism() != 0) {
goInstanceConfig.setParallelism(instanceConfig.getFunctionDetails().getParallelism());
}
if (instanceConfig.getMaxBufferedTuples() != 0) {
goInstanceConfig.setMaxBufTuples(instanceConfig.getMaxBufferedTuples());
}
if (pulsarServiceUrl != null) {
goInstanceConfig.setPulsarServiceURL(pulsarServiceUrl);
}
if (instanceConfig.getFunctionDetails().getSource().getCleanupSubscription()) {
goInstanceConfig.setCleanupSubscription(instanceConfig.getFunctionDetails().getSource().getCleanupSubscription());
}
if (instanceConfig.getFunctionDetails().getSource().getSubscriptionName() != null) {
goInstanceConfig.setSubscriptionName(instanceConfig.getFunctionDetails().getSource().getSubscriptionName());
}
if (instanceConfig.getFunctionDetails().getSource().getInputSpecsMap() != null) {
for (String inputTopic : instanceConfig.getFunctionDetails().getSource().getInputSpecsMap().keySet()) {
goInstanceConfig.setSourceSpecsTopic(inputTopic);
}
}
if (instanceConfig.getFunctionDetails().getSource().getTimeoutMs() != 0) {
goInstanceConfig.setTimeoutMs(instanceConfig.getFunctionDetails().getSource().getTimeoutMs());
}
if (instanceConfig.getFunctionDetails().getSink().getTopic() != null) {
goInstanceConfig.setSinkSpecsTopic(instanceConfig.getFunctionDetails().getSink().getTopic());
}
if (instanceConfig.getFunctionDetails().getResources().getCpu() != 0) {
goInstanceConfig.setCpu(instanceConfig.getFunctionDetails().getResources().getCpu());
}
if (instanceConfig.getFunctionDetails().getResources().getRam() != 0) {
goInstanceConfig.setRam(instanceConfig.getFunctionDetails().getResources().getRam());
}
if (instanceConfig.getFunctionDetails().getResources().getDisk() != 0) {
goInstanceConfig.setDisk(instanceConfig.getFunctionDetails().getResources().getDisk());
}
if (instanceConfig.getFunctionDetails().getRetryDetails().getDeadLetterTopic() != null) {
goInstanceConfig.setDeadLetterTopic(instanceConfig.getFunctionDetails().getRetryDetails().getDeadLetterTopic());
}
if (instanceConfig.getFunctionDetails().getRetryDetails().getMaxMessageRetries() != 0) {
goInstanceConfig.setMaxMessageRetries(instanceConfig.getFunctionDetails().getRetryDetails().getMaxMessageRetries());
}
if (instanceConfig.hasValidMetricsPort()) {
goInstanceConfig.setMetricsPort(instanceConfig.getMetricsPort());
}
goInstanceConfig.setKillAfterIdleMs(0);
goInstanceConfig.setPort(instanceConfig.getPort());
// Parse the contents of goInstanceConfig into json form string
ObjectMapper objectMapper = ObjectMapperFactory.getThreadLocal();
String configContent = objectMapper.writeValueAsString(goInstanceConfig);
args.add(originalCodeFileName);
args.add("-instance-conf");
if (k8sRuntime) {
args.add("'" + configContent + "'");
} else {
args.add(configContent);
}
return args;
}
public static List<String> getCmd(InstanceConfig instanceConfig,
String instanceFile,
String extraDependenciesDir, /* extra dependencies for running instances */
String logDirectory,
String originalCodeFileName,
String pulsarServiceUrl,
String stateStorageServiceUrl,
AuthenticationConfig authConfig,
String shardId,
Integer grpcPort,
Long expectedHealthCheckInterval,
String logConfigFile,
String secretsProviderClassName,
String secretsProviderConfig,
Boolean installUserCodeDependencies,
String pythonDependencyRepository,
String pythonExtraDependencyRepository,
String narExtractionDirectory,
String functionInstanceClassPath,
boolean k8sRuntime,
String pulsarWebServiceUrl) throws Exception {
final List<String> args = new LinkedList<>();
if (instanceConfig.getFunctionDetails().getRuntime() == Function.FunctionDetails.Runtime.GO) {
return getGoInstanceCmd(instanceConfig, originalCodeFileName, pulsarServiceUrl, k8sRuntime);
}
if (instanceConfig.getFunctionDetails().getRuntime() == Function.FunctionDetails.Runtime.JAVA) {
args.add("java");
args.add("-cp");
String classpath = instanceFile;
if (StringUtils.isNotEmpty(extraDependenciesDir)) {
classpath = classpath + ":" + extraDependenciesDir + "/*";
}
args.add(classpath);
if (StringUtils.isNotEmpty(extraDependenciesDir)) {
args.add(String.format("-D%s=%s", FUNCTIONS_EXTRA_DEPS_PROPERTY, extraDependenciesDir));
}
if (StringUtils.isNotEmpty(functionInstanceClassPath)) {
args.add(String.format("-D%s=%s", FUNCTIONS_INSTANCE_CLASSPATH, functionInstanceClassPath));
} else {
// add complete classpath for broker/worker so that the function instance can load
// the functions instance dependencies separately from user code dependencies
String systemFunctionInstanceClasspath = System.getProperty(FUNCTIONS_INSTANCE_CLASSPATH);
if (systemFunctionInstanceClasspath == null) {
log.warn("Property {} is not set. Falling back to using classpath of current JVM", FUNCTIONS_INSTANCE_CLASSPATH);
systemFunctionInstanceClasspath = System.getProperty("java.class.path");
}
args.add(String.format("-D%s=%s", FUNCTIONS_INSTANCE_CLASSPATH, systemFunctionInstanceClasspath));
}
args.add("-Dlog4j.configurationFile=" + logConfigFile);
args.add("-Dpulsar.function.log.dir=" + genFunctionLogFolder(logDirectory, instanceConfig));
args.add("-Dpulsar.function.log.file=" + String.format(
"%s-%s",
instanceConfig.getFunctionDetails().getName(),
shardId));
if (!isEmpty(instanceConfig.getFunctionDetails().getRuntimeFlags())) {
for (String runtimeFlagArg : splitRuntimeArgs(instanceConfig.getFunctionDetails().getRuntimeFlags())) {
args.add(runtimeFlagArg);
}
}
if (instanceConfig.getFunctionDetails().getResources() != null) {
Function.Resources resources = instanceConfig.getFunctionDetails().getResources();
if (resources.getRam() != 0) {
args.add("-Xmx" + String.valueOf(resources.getRam()));
}
}
args.add("org.apache.pulsar.functions.instance.JavaInstanceMain");
args.add("--jar");
args.add(originalCodeFileName);
} else if (instanceConfig.getFunctionDetails().getRuntime() == Function.FunctionDetails.Runtime.PYTHON) {
args.add("python");
if (!isEmpty(instanceConfig.getFunctionDetails().getRuntimeFlags())) {
for (String runtimeFlagArg : splitRuntimeArgs(instanceConfig.getFunctionDetails().getRuntimeFlags())) {
args.add(runtimeFlagArg);
}
}
args.add(instanceFile);
args.add("--py");
args.add(originalCodeFileName);
args.add("--logging_directory");
args.add(logDirectory);
args.add("--logging_file");
args.add(instanceConfig.getFunctionDetails().getName());
// set logging config file
args.add("--logging_config_file");
args.add(logConfigFile);
// `installUserCodeDependencies` is only valid for python runtime
if (installUserCodeDependencies != null && installUserCodeDependencies) {
args.add("--install_usercode_dependencies");
args.add("True");
}
if (!isEmpty(pythonDependencyRepository)) {
args.add("--dependency_repository");
args.add(pythonDependencyRepository);
}
if (!isEmpty(pythonExtraDependencyRepository)) {
args.add("--extra_dependency_repository");
args.add(pythonExtraDependencyRepository);
}
// TODO:- Find a platform independent way of controlling memory for a python application
}
args.add("--instance_id");
args.add(shardId);
args.add("--function_id");
args.add(instanceConfig.getFunctionId());
args.add("--function_version");
args.add(instanceConfig.getFunctionVersion());
args.add("--function_details");
args.add("'" + JsonFormat.printer().omittingInsignificantWhitespace().print(instanceConfig.getFunctionDetails()) + "'");
args.add("--pulsar_serviceurl");
args.add(pulsarServiceUrl);
if (instanceConfig.getFunctionDetails().getRuntime() == Function.FunctionDetails.Runtime.JAVA) {
// TODO: for now only Java function context exposed pulsar admin, so python/go no need to pass this argument
// until pulsar admin client enabled in python/go function context.
// For backward compatibility, pass `--web_serviceurl` parameter only if
// exposed pulsar admin client enabled.
if (instanceConfig.isExposePulsarAdminClientEnabled() && StringUtils.isNotBlank(pulsarWebServiceUrl)) {
args.add("--web_serviceurl");
args.add(pulsarWebServiceUrl);
}
}
if (authConfig != null) {
if (isNotBlank(authConfig.getClientAuthenticationPlugin())
&& isNotBlank(authConfig.getClientAuthenticationParameters())) {
args.add("--client_auth_plugin");
args.add(authConfig.getClientAuthenticationPlugin());
args.add("--client_auth_params");
args.add(authConfig.getClientAuthenticationParameters());
}
args.add("--use_tls");
args.add(Boolean.toString(authConfig.isUseTls()));
args.add("--tls_allow_insecure");
args.add(Boolean.toString(authConfig.isTlsAllowInsecureConnection()));
args.add("--hostname_verification_enabled");
args.add(Boolean.toString(authConfig.isTlsHostnameVerificationEnable()));
if (isNotBlank(authConfig.getTlsTrustCertsFilePath())) {
args.add("--tls_trust_cert_path");
args.add(authConfig.getTlsTrustCertsFilePath());
}
}
args.add("--max_buffered_tuples");
args.add(String.valueOf(instanceConfig.getMaxBufferedTuples()));
args.add("--port");
args.add(String.valueOf(grpcPort));
args.add("--metrics_port");
args.add(String.valueOf(instanceConfig.getMetricsPort()));
// only the Java instance supports --pending_async_requests right now.
if (instanceConfig.getFunctionDetails().getRuntime() == Function.FunctionDetails.Runtime.JAVA) {
args.add("--pending_async_requests");
args.add(String.valueOf(instanceConfig.getMaxPendingAsyncRequests()));
}
// state storage configs
if (null != stateStorageServiceUrl) {
args.add("--state_storage_serviceurl");
args.add(stateStorageServiceUrl);
}
args.add("--expected_healthcheck_interval");
args.add(String.valueOf(expectedHealthCheckInterval));
if (!StringUtils.isEmpty(secretsProviderClassName)) {
args.add("--secrets_provider");
args.add(secretsProviderClassName);
if (!StringUtils.isEmpty(secretsProviderConfig)) {
args.add("--secrets_provider_config");
args.add("'" + secretsProviderConfig + "'");
}
}
args.add("--cluster_name");
args.add(instanceConfig.getClusterName());
if (instanceConfig.getFunctionDetails().getRuntime() == Function.FunctionDetails.Runtime.JAVA) {
if (!StringUtils.isEmpty(narExtractionDirectory)) {
args.add("--nar_extraction_directory");
args.add(narExtractionDirectory);
}
}
return args;
}
public static String genFunctionLogFolder(String logDirectory, InstanceConfig instanceConfig) {
return String.format(
"%s/%s",
logDirectory,
FunctionCommon.getFullyQualifiedName(instanceConfig.getFunctionDetails()));
}
public static String getPrometheusMetrics(int metricsPort) throws IOException {
StringBuilder result = new StringBuilder();
URL url = new URL(String.format("http://%s:%s", InetAddress.getLocalHost().getHostAddress(), metricsPort));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line + System.lineSeparator());
}
rd.close();
return result.toString();
}
/**
* Regex for splitting a string using space when not surrounded by single or double quotes
*/
public static String[] splitRuntimeArgs(String input) {
return input.split("\\s(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
}
public static <T> T getRuntimeFunctionConfig(Map<String, Object> configMap, Class<T> functionRuntimeConfigClass) {
return ObjectMapperFactory.getThreadLocal().convertValue(configMap, functionRuntimeConfigClass);
}
public static void registerDefaultCollectors(FunctionCollectorRegistry registry) {
// Add the JMX exporter for functionality similar to the kafka connect JMX metrics
try {
new JmxCollector("{}").register(registry);
} catch (MalformedObjectNameException ex) {
System.err.println(ex);
}
// Add the default exports from io.prometheus.client.hotspot.DefaultExports
new StandardExports().register(registry);
new MemoryPoolsExports().register(registry);
new BufferPoolsExports().register(registry);
new GarbageCollectorExports().register(registry);
new ThreadExports().register(registry);
new ClassLoadingExports().register(registry);
new VersionInfoExports().register(registry);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.